angular.js 702 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369
  1. /**
  2. * @license AngularJS v1.2.5
  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(string, string, ...): Error} 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.5/' +
  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. -isBoolean,
  120. -trim,
  121. -isElement,
  122. -makeMap,
  123. -map,
  124. -size,
  125. -includes,
  126. -indexOf,
  127. -arrayRemove,
  128. -isLeafNode,
  129. -copy,
  130. -shallowCopy,
  131. -equals,
  132. -csp,
  133. -concat,
  134. -sliceArgs,
  135. -bind,
  136. -toJsonReplacer,
  137. -toJson,
  138. -fromJson,
  139. -toBoolean,
  140. -startingTag,
  141. -tryDecodeURIComponent,
  142. -parseKeyValue,
  143. -toKeyValue,
  144. -encodeUriSegment,
  145. -encodeUriQuery,
  146. -angularInit,
  147. -bootstrap,
  148. -snake_case,
  149. -bindJQuery,
  150. -assertArg,
  151. -assertArgFn,
  152. -assertNotHasOwnProperty,
  153. -getter,
  154. -getBlockElements,
  155. */
  156. ////////////////////////////////////
  157. /**
  158. * @ngdoc function
  159. * @name angular.lowercase
  160. * @function
  161. *
  162. * @description Converts the specified string to lowercase.
  163. * @param {string} string String to be converted to lowercase.
  164. * @returns {string} Lowercased string.
  165. */
  166. var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
  167. /**
  168. * @ngdoc function
  169. * @name angular.uppercase
  170. * @function
  171. *
  172. * @description Converts the specified string to uppercase.
  173. * @param {string} string String to be converted to uppercase.
  174. * @returns {string} Uppercased string.
  175. */
  176. var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
  177. var manualLowercase = function(s) {
  178. /* jshint bitwise: false */
  179. return isString(s)
  180. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  181. : s;
  182. };
  183. var manualUppercase = function(s) {
  184. /* jshint bitwise: false */
  185. return isString(s)
  186. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  187. : s;
  188. };
  189. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  190. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  191. // with correct but slower alternatives.
  192. if ('i' !== 'I'.toLowerCase()) {
  193. lowercase = manualLowercase;
  194. uppercase = manualUppercase;
  195. }
  196. var /** holds major version number for IE or NaN for real browsers */
  197. msie,
  198. jqLite, // delay binding since jQuery could be loaded after us.
  199. jQuery, // delay binding
  200. slice = [].slice,
  201. push = [].push,
  202. toString = Object.prototype.toString,
  203. ngMinErr = minErr('ng'),
  204. _angular = window.angular,
  205. /** @name angular */
  206. angular = window.angular || (window.angular = {}),
  207. angularModule,
  208. nodeName_,
  209. uid = ['0', '0', '0'];
  210. /**
  211. * IE 11 changed the format of the UserAgent string.
  212. * See http://msdn.microsoft.com/en-us/library/ms537503.aspx
  213. */
  214. msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  215. if (isNaN(msie)) {
  216. msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  217. }
  218. /**
  219. * @private
  220. * @param {*} obj
  221. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  222. * String ...)
  223. */
  224. function isArrayLike(obj) {
  225. if (obj == null || isWindow(obj)) {
  226. return false;
  227. }
  228. var length = obj.length;
  229. if (obj.nodeType === 1 && length) {
  230. return true;
  231. }
  232. return isString(obj) || isArray(obj) || length === 0 ||
  233. typeof length === 'number' && length > 0 && (length - 1) in obj;
  234. }
  235. /**
  236. * @ngdoc function
  237. * @name angular.forEach
  238. * @function
  239. *
  240. * @description
  241. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  242. * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
  243. * is the value of an object property or an array element and `key` is the object property key or
  244. * array element index. Specifying a `context` for the function is optional.
  245. *
  246. * Note: this function was previously known as `angular.foreach`.
  247. *
  248. <pre>
  249. var values = {name: 'misko', gender: 'male'};
  250. var log = [];
  251. angular.forEach(values, function(value, key){
  252. this.push(key + ': ' + value);
  253. }, log);
  254. expect(log).toEqual(['name: misko', 'gender:male']);
  255. </pre>
  256. *
  257. * @param {Object|Array} obj Object to iterate over.
  258. * @param {Function} iterator Iterator function.
  259. * @param {Object=} context Object to become context (`this`) for the iterator function.
  260. * @returns {Object|Array} Reference to `obj`.
  261. */
  262. function forEach(obj, iterator, context) {
  263. var key;
  264. if (obj) {
  265. if (isFunction(obj)){
  266. for (key in obj) {
  267. if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
  268. iterator.call(context, obj[key], key);
  269. }
  270. }
  271. } else if (obj.forEach && obj.forEach !== forEach) {
  272. obj.forEach(iterator, context);
  273. } else if (isArrayLike(obj)) {
  274. for (key = 0; key < obj.length; key++)
  275. iterator.call(context, obj[key], key);
  276. } else {
  277. for (key in obj) {
  278. if (obj.hasOwnProperty(key)) {
  279. iterator.call(context, obj[key], key);
  280. }
  281. }
  282. }
  283. }
  284. return obj;
  285. }
  286. function sortedKeys(obj) {
  287. var keys = [];
  288. for (var key in obj) {
  289. if (obj.hasOwnProperty(key)) {
  290. keys.push(key);
  291. }
  292. }
  293. return keys.sort();
  294. }
  295. function forEachSorted(obj, iterator, context) {
  296. var keys = sortedKeys(obj);
  297. for ( var i = 0; i < keys.length; i++) {
  298. iterator.call(context, obj[keys[i]], keys[i]);
  299. }
  300. return keys;
  301. }
  302. /**
  303. * when using forEach the params are value, key, but it is often useful to have key, value.
  304. * @param {function(string, *)} iteratorFn
  305. * @returns {function(*, string)}
  306. */
  307. function reverseParams(iteratorFn) {
  308. return function(value, key) { iteratorFn(key, value); };
  309. }
  310. /**
  311. * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
  312. * characters such as '012ABC'. The reason why we are not using simply a number counter is that
  313. * the number string gets longer over time, and it can also overflow, where as the nextId
  314. * will grow much slower, it is a string, and it will never overflow.
  315. *
  316. * @returns an unique alpha-numeric string
  317. */
  318. function nextUid() {
  319. var index = uid.length;
  320. var digit;
  321. while(index) {
  322. index--;
  323. digit = uid[index].charCodeAt(0);
  324. if (digit == 57 /*'9'*/) {
  325. uid[index] = 'A';
  326. return uid.join('');
  327. }
  328. if (digit == 90 /*'Z'*/) {
  329. uid[index] = '0';
  330. } else {
  331. uid[index] = String.fromCharCode(digit + 1);
  332. return uid.join('');
  333. }
  334. }
  335. uid.unshift('0');
  336. return uid.join('');
  337. }
  338. /**
  339. * Set or clear the hashkey for an object.
  340. * @param obj object
  341. * @param h the hashkey (!truthy to delete the hashkey)
  342. */
  343. function setHashKey(obj, h) {
  344. if (h) {
  345. obj.$$hashKey = h;
  346. }
  347. else {
  348. delete obj.$$hashKey;
  349. }
  350. }
  351. /**
  352. * @ngdoc function
  353. * @name angular.extend
  354. * @function
  355. *
  356. * @description
  357. * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
  358. * to `dst`. You can specify multiple `src` objects.
  359. *
  360. * @param {Object} dst Destination object.
  361. * @param {...Object} src Source object(s).
  362. * @returns {Object} Reference to `dst`.
  363. */
  364. function extend(dst) {
  365. var h = dst.$$hashKey;
  366. forEach(arguments, function(obj){
  367. if (obj !== dst) {
  368. forEach(obj, function(value, key){
  369. dst[key] = value;
  370. });
  371. }
  372. });
  373. setHashKey(dst,h);
  374. return dst;
  375. }
  376. function int(str) {
  377. return parseInt(str, 10);
  378. }
  379. function inherit(parent, extra) {
  380. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  381. }
  382. /**
  383. * @ngdoc function
  384. * @name angular.noop
  385. * @function
  386. *
  387. * @description
  388. * A function that performs no operations. This function can be useful when writing code in the
  389. * functional style.
  390. <pre>
  391. function foo(callback) {
  392. var result = calculateResult();
  393. (callback || angular.noop)(result);
  394. }
  395. </pre>
  396. */
  397. function noop() {}
  398. noop.$inject = [];
  399. /**
  400. * @ngdoc function
  401. * @name angular.identity
  402. * @function
  403. *
  404. * @description
  405. * A function that returns its first argument. This function is useful when writing code in the
  406. * functional style.
  407. *
  408. <pre>
  409. function transformer(transformationFn, value) {
  410. return (transformationFn || angular.identity)(value);
  411. };
  412. </pre>
  413. */
  414. function identity($) {return $;}
  415. identity.$inject = [];
  416. function valueFn(value) {return function() {return value;};}
  417. /**
  418. * @ngdoc function
  419. * @name angular.isUndefined
  420. * @function
  421. *
  422. * @description
  423. * Determines if a reference is undefined.
  424. *
  425. * @param {*} value Reference to check.
  426. * @returns {boolean} True if `value` is undefined.
  427. */
  428. function isUndefined(value){return typeof value === 'undefined';}
  429. /**
  430. * @ngdoc function
  431. * @name angular.isDefined
  432. * @function
  433. *
  434. * @description
  435. * Determines if a reference is defined.
  436. *
  437. * @param {*} value Reference to check.
  438. * @returns {boolean} True if `value` is defined.
  439. */
  440. function isDefined(value){return typeof value !== 'undefined';}
  441. /**
  442. * @ngdoc function
  443. * @name angular.isObject
  444. * @function
  445. *
  446. * @description
  447. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  448. * considered to be objects.
  449. *
  450. * @param {*} value Reference to check.
  451. * @returns {boolean} True if `value` is an `Object` but not `null`.
  452. */
  453. function isObject(value){return value != null && typeof value === 'object';}
  454. /**
  455. * @ngdoc function
  456. * @name angular.isString
  457. * @function
  458. *
  459. * @description
  460. * Determines if a reference is a `String`.
  461. *
  462. * @param {*} value Reference to check.
  463. * @returns {boolean} True if `value` is a `String`.
  464. */
  465. function isString(value){return typeof value === 'string';}
  466. /**
  467. * @ngdoc function
  468. * @name angular.isNumber
  469. * @function
  470. *
  471. * @description
  472. * Determines if a reference is a `Number`.
  473. *
  474. * @param {*} value Reference to check.
  475. * @returns {boolean} True if `value` is a `Number`.
  476. */
  477. function isNumber(value){return typeof value === 'number';}
  478. /**
  479. * @ngdoc function
  480. * @name angular.isDate
  481. * @function
  482. *
  483. * @description
  484. * Determines if a value is a date.
  485. *
  486. * @param {*} value Reference to check.
  487. * @returns {boolean} True if `value` is a `Date`.
  488. */
  489. function isDate(value){
  490. return toString.call(value) === '[object Date]';
  491. }
  492. /**
  493. * @ngdoc function
  494. * @name angular.isArray
  495. * @function
  496. *
  497. * @description
  498. * Determines if a reference is an `Array`.
  499. *
  500. * @param {*} value Reference to check.
  501. * @returns {boolean} True if `value` is an `Array`.
  502. */
  503. function isArray(value) {
  504. return toString.call(value) === '[object Array]';
  505. }
  506. /**
  507. * @ngdoc function
  508. * @name angular.isFunction
  509. * @function
  510. *
  511. * @description
  512. * Determines if a reference is a `Function`.
  513. *
  514. * @param {*} value Reference to check.
  515. * @returns {boolean} True if `value` is a `Function`.
  516. */
  517. function isFunction(value){return typeof value === 'function';}
  518. /**
  519. * Determines if a value is a regular expression object.
  520. *
  521. * @private
  522. * @param {*} value Reference to check.
  523. * @returns {boolean} True if `value` is a `RegExp`.
  524. */
  525. function isRegExp(value) {
  526. return toString.call(value) === '[object RegExp]';
  527. }
  528. /**
  529. * Checks if `obj` is a window object.
  530. *
  531. * @private
  532. * @param {*} obj Object to check
  533. * @returns {boolean} True if `obj` is a window obj.
  534. */
  535. function isWindow(obj) {
  536. return obj && obj.document && obj.location && obj.alert && obj.setInterval;
  537. }
  538. function isScope(obj) {
  539. return obj && obj.$evalAsync && obj.$watch;
  540. }
  541. function isFile(obj) {
  542. return toString.call(obj) === '[object File]';
  543. }
  544. function isBoolean(value) {
  545. return typeof value === 'boolean';
  546. }
  547. var trim = (function() {
  548. // native trim is way faster: http://jsperf.com/angular-trim-test
  549. // but IE doesn't have it... :-(
  550. // TODO: we should move this into IE/ES5 polyfill
  551. if (!String.prototype.trim) {
  552. return function(value) {
  553. return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
  554. };
  555. }
  556. return function(value) {
  557. return isString(value) ? value.trim() : value;
  558. };
  559. })();
  560. /**
  561. * @ngdoc function
  562. * @name angular.isElement
  563. * @function
  564. *
  565. * @description
  566. * Determines if a reference is a DOM element (or wrapped jQuery element).
  567. *
  568. * @param {*} value Reference to check.
  569. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  570. */
  571. function isElement(node) {
  572. return !!(node &&
  573. (node.nodeName // we are a direct element
  574. || (node.on && node.find))); // we have an on and find method part of jQuery API
  575. }
  576. /**
  577. * @param str 'key1,key2,...'
  578. * @returns {object} in the form of {key1:true, key2:true, ...}
  579. */
  580. function makeMap(str){
  581. var obj = {}, items = str.split(","), i;
  582. for ( i = 0; i < items.length; i++ )
  583. obj[ items[i] ] = true;
  584. return obj;
  585. }
  586. if (msie < 9) {
  587. nodeName_ = function(element) {
  588. element = element.nodeName ? element : element[0];
  589. return (element.scopeName && element.scopeName != 'HTML')
  590. ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
  591. };
  592. } else {
  593. nodeName_ = function(element) {
  594. return element.nodeName ? element.nodeName : element[0].nodeName;
  595. };
  596. }
  597. function map(obj, iterator, context) {
  598. var results = [];
  599. forEach(obj, function(value, index, list) {
  600. results.push(iterator.call(context, value, index, list));
  601. });
  602. return results;
  603. }
  604. /**
  605. * @description
  606. * Determines the number of elements in an array, the number of properties an object has, or
  607. * the length of a string.
  608. *
  609. * Note: This function is used to augment the Object type in Angular expressions. See
  610. * {@link angular.Object} for more information about Angular arrays.
  611. *
  612. * @param {Object|Array|string} obj Object, array, or string to inspect.
  613. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
  614. * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
  615. */
  616. function size(obj, ownPropsOnly) {
  617. var count = 0, key;
  618. if (isArray(obj) || isString(obj)) {
  619. return obj.length;
  620. } else if (isObject(obj)){
  621. for (key in obj)
  622. if (!ownPropsOnly || obj.hasOwnProperty(key))
  623. count++;
  624. }
  625. return count;
  626. }
  627. function includes(array, obj) {
  628. return indexOf(array, obj) != -1;
  629. }
  630. function indexOf(array, obj) {
  631. if (array.indexOf) return array.indexOf(obj);
  632. for (var i = 0; i < array.length; i++) {
  633. if (obj === array[i]) return i;
  634. }
  635. return -1;
  636. }
  637. function arrayRemove(array, value) {
  638. var index = indexOf(array, value);
  639. if (index >=0)
  640. array.splice(index, 1);
  641. return value;
  642. }
  643. function isLeafNode (node) {
  644. if (node) {
  645. switch (node.nodeName) {
  646. case "OPTION":
  647. case "PRE":
  648. case "TITLE":
  649. return true;
  650. }
  651. }
  652. return false;
  653. }
  654. /**
  655. * @ngdoc function
  656. * @name angular.copy
  657. * @function
  658. *
  659. * @description
  660. * Creates a deep copy of `source`, which should be an object or an array.
  661. *
  662. * * If no destination is supplied, a copy of the object or array is created.
  663. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  664. * are deleted and then all elements/properties from the source are copied to it.
  665. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  666. * * If `source` is identical to 'destination' an exception will be thrown.
  667. *
  668. * @param {*} source The source that will be used to make a copy.
  669. * Can be any type, including primitives, `null`, and `undefined`.
  670. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  671. * provided, must be of the same type as `source`.
  672. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  673. *
  674. * @example
  675. <doc:example>
  676. <doc:source>
  677. <div ng-controller="Controller">
  678. <form novalidate class="simple-form">
  679. Name: <input type="text" ng-model="user.name" /><br />
  680. E-mail: <input type="email" ng-model="user.email" /><br />
  681. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  682. <input type="radio" ng-model="user.gender" value="female" />female<br />
  683. <button ng-click="reset()">RESET</button>
  684. <button ng-click="update(user)">SAVE</button>
  685. </form>
  686. <pre>form = {{user | json}}</pre>
  687. <pre>master = {{master | json}}</pre>
  688. </div>
  689. <script>
  690. function Controller($scope) {
  691. $scope.master= {};
  692. $scope.update = function(user) {
  693. // Example with 1 argument
  694. $scope.master= angular.copy(user);
  695. };
  696. $scope.reset = function() {
  697. // Example with 2 arguments
  698. angular.copy($scope.master, $scope.user);
  699. };
  700. $scope.reset();
  701. }
  702. </script>
  703. </doc:source>
  704. </doc:example>
  705. */
  706. function copy(source, destination){
  707. if (isWindow(source) || isScope(source)) {
  708. throw ngMinErr('cpws',
  709. "Can't copy! Making copies of Window or Scope instances is not supported.");
  710. }
  711. if (!destination) {
  712. destination = source;
  713. if (source) {
  714. if (isArray(source)) {
  715. destination = copy(source, []);
  716. } else if (isDate(source)) {
  717. destination = new Date(source.getTime());
  718. } else if (isRegExp(source)) {
  719. destination = new RegExp(source.source);
  720. } else if (isObject(source)) {
  721. destination = copy(source, {});
  722. }
  723. }
  724. } else {
  725. if (source === destination) throw ngMinErr('cpi',
  726. "Can't copy! Source and destination are identical.");
  727. if (isArray(source)) {
  728. destination.length = 0;
  729. for ( var i = 0; i < source.length; i++) {
  730. destination.push(copy(source[i]));
  731. }
  732. } else {
  733. var h = destination.$$hashKey;
  734. forEach(destination, function(value, key){
  735. delete destination[key];
  736. });
  737. for ( var key in source) {
  738. destination[key] = copy(source[key]);
  739. }
  740. setHashKey(destination,h);
  741. }
  742. }
  743. return destination;
  744. }
  745. /**
  746. * Create a shallow copy of an object
  747. */
  748. function shallowCopy(src, dst) {
  749. dst = dst || {};
  750. for(var key in src) {
  751. // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src
  752. // so we don't need to worry about using our custom hasOwnProperty here
  753. if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
  754. dst[key] = src[key];
  755. }
  756. }
  757. return dst;
  758. }
  759. /**
  760. * @ngdoc function
  761. * @name angular.equals
  762. * @function
  763. *
  764. * @description
  765. * Determines if two objects or two values are equivalent. Supports value types, regular
  766. * expressions, arrays and objects.
  767. *
  768. * Two objects or values are considered equivalent if at least one of the following is true:
  769. *
  770. * * Both objects or values pass `===` comparison.
  771. * * Both objects or values are of the same type and all of their properties are equal by
  772. * comparing them with `angular.equals`.
  773. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  774. * * Both values represent the same regular expression (In JavasScript,
  775. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  776. * representation matches).
  777. *
  778. * During a property comparison, properties of `function` type and properties with names
  779. * that begin with `$` are ignored.
  780. *
  781. * Scope and DOMWindow objects are being compared only by identify (`===`).
  782. *
  783. * @param {*} o1 Object or value to compare.
  784. * @param {*} o2 Object or value to compare.
  785. * @returns {boolean} True if arguments are equal.
  786. */
  787. function equals(o1, o2) {
  788. if (o1 === o2) return true;
  789. if (o1 === null || o2 === null) return false;
  790. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  791. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  792. if (t1 == t2) {
  793. if (t1 == 'object') {
  794. if (isArray(o1)) {
  795. if (!isArray(o2)) return false;
  796. if ((length = o1.length) == o2.length) {
  797. for(key=0; key<length; key++) {
  798. if (!equals(o1[key], o2[key])) return false;
  799. }
  800. return true;
  801. }
  802. } else if (isDate(o1)) {
  803. return isDate(o2) && o1.getTime() == o2.getTime();
  804. } else if (isRegExp(o1) && isRegExp(o2)) {
  805. return o1.toString() == o2.toString();
  806. } else {
  807. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  808. keySet = {};
  809. for(key in o1) {
  810. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  811. if (!equals(o1[key], o2[key])) return false;
  812. keySet[key] = true;
  813. }
  814. for(key in o2) {
  815. if (!keySet.hasOwnProperty(key) &&
  816. key.charAt(0) !== '$' &&
  817. o2[key] !== undefined &&
  818. !isFunction(o2[key])) return false;
  819. }
  820. return true;
  821. }
  822. }
  823. }
  824. return false;
  825. }
  826. function csp() {
  827. return (document.securityPolicy && document.securityPolicy.isActive) ||
  828. (document.querySelector &&
  829. !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]')));
  830. }
  831. function concat(array1, array2, index) {
  832. return array1.concat(slice.call(array2, index));
  833. }
  834. function sliceArgs(args, startIndex) {
  835. return slice.call(args, startIndex || 0);
  836. }
  837. /* jshint -W101 */
  838. /**
  839. * @ngdoc function
  840. * @name angular.bind
  841. * @function
  842. *
  843. * @description
  844. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  845. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  846. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  847. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  848. *
  849. * @param {Object} self Context which `fn` should be evaluated in.
  850. * @param {function()} fn Function to be bound.
  851. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  852. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  853. */
  854. /* jshint +W101 */
  855. function bind(self, fn) {
  856. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  857. if (isFunction(fn) && !(fn instanceof RegExp)) {
  858. return curryArgs.length
  859. ? function() {
  860. return arguments.length
  861. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  862. : fn.apply(self, curryArgs);
  863. }
  864. : function() {
  865. return arguments.length
  866. ? fn.apply(self, arguments)
  867. : fn.call(self);
  868. };
  869. } else {
  870. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  871. return fn;
  872. }
  873. }
  874. function toJsonReplacer(key, value) {
  875. var val = value;
  876. if (typeof key === 'string' && key.charAt(0) === '$') {
  877. val = undefined;
  878. } else if (isWindow(value)) {
  879. val = '$WINDOW';
  880. } else if (value && document === value) {
  881. val = '$DOCUMENT';
  882. } else if (isScope(value)) {
  883. val = '$SCOPE';
  884. }
  885. return val;
  886. }
  887. /**
  888. * @ngdoc function
  889. * @name angular.toJson
  890. * @function
  891. *
  892. * @description
  893. * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
  894. * stripped since angular uses this notation internally.
  895. *
  896. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  897. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  898. * @returns {string|undefined} JSON-ified string representing `obj`.
  899. */
  900. function toJson(obj, pretty) {
  901. if (typeof obj === 'undefined') return undefined;
  902. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  903. }
  904. /**
  905. * @ngdoc function
  906. * @name angular.fromJson
  907. * @function
  908. *
  909. * @description
  910. * Deserializes a JSON string.
  911. *
  912. * @param {string} json JSON string to deserialize.
  913. * @returns {Object|Array|Date|string|number} Deserialized thingy.
  914. */
  915. function fromJson(json) {
  916. return isString(json)
  917. ? JSON.parse(json)
  918. : json;
  919. }
  920. function toBoolean(value) {
  921. if (value && value.length !== 0) {
  922. var v = lowercase("" + value);
  923. value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
  924. } else {
  925. value = false;
  926. }
  927. return value;
  928. }
  929. /**
  930. * @returns {string} Returns the string representation of the element.
  931. */
  932. function startingTag(element) {
  933. element = jqLite(element).clone();
  934. try {
  935. // turns out IE does not let you set .html() on elements which
  936. // are not allowed to have children. So we just ignore it.
  937. element.empty();
  938. } catch(e) {}
  939. // As Per DOM Standards
  940. var TEXT_NODE = 3;
  941. var elemHtml = jqLite('<div>').append(element).html();
  942. try {
  943. return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
  944. elemHtml.
  945. match(/^(<[^>]+>)/)[1].
  946. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  947. } catch(e) {
  948. return lowercase(elemHtml);
  949. }
  950. }
  951. /////////////////////////////////////////////////
  952. /**
  953. * Tries to decode the URI component without throwing an exception.
  954. *
  955. * @private
  956. * @param str value potential URI component to check.
  957. * @returns {boolean} True if `value` can be decoded
  958. * with the decodeURIComponent function.
  959. */
  960. function tryDecodeURIComponent(value) {
  961. try {
  962. return decodeURIComponent(value);
  963. } catch(e) {
  964. // Ignore any invalid uri component
  965. }
  966. }
  967. /**
  968. * Parses an escaped url query string into key-value pairs.
  969. * @returns Object.<(string|boolean)>
  970. */
  971. function parseKeyValue(/**string*/keyValue) {
  972. var obj = {}, key_value, key;
  973. forEach((keyValue || "").split('&'), function(keyValue){
  974. if ( keyValue ) {
  975. key_value = keyValue.split('=');
  976. key = tryDecodeURIComponent(key_value[0]);
  977. if ( isDefined(key) ) {
  978. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  979. if (!obj[key]) {
  980. obj[key] = val;
  981. } else if(isArray(obj[key])) {
  982. obj[key].push(val);
  983. } else {
  984. obj[key] = [obj[key],val];
  985. }
  986. }
  987. }
  988. });
  989. return obj;
  990. }
  991. function toKeyValue(obj) {
  992. var parts = [];
  993. forEach(obj, function(value, key) {
  994. if (isArray(value)) {
  995. forEach(value, function(arrayValue) {
  996. parts.push(encodeUriQuery(key, true) +
  997. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  998. });
  999. } else {
  1000. parts.push(encodeUriQuery(key, true) +
  1001. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1002. }
  1003. });
  1004. return parts.length ? parts.join('&') : '';
  1005. }
  1006. /**
  1007. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1008. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1009. * segments:
  1010. * segment = *pchar
  1011. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1012. * pct-encoded = "%" HEXDIG HEXDIG
  1013. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1014. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1015. * / "*" / "+" / "," / ";" / "="
  1016. */
  1017. function encodeUriSegment(val) {
  1018. return encodeUriQuery(val, true).
  1019. replace(/%26/gi, '&').
  1020. replace(/%3D/gi, '=').
  1021. replace(/%2B/gi, '+');
  1022. }
  1023. /**
  1024. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1025. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1026. * encoded per http://tools.ietf.org/html/rfc3986:
  1027. * query = *( pchar / "/" / "?" )
  1028. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1029. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1030. * pct-encoded = "%" HEXDIG HEXDIG
  1031. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1032. * / "*" / "+" / "," / ";" / "="
  1033. */
  1034. function encodeUriQuery(val, pctEncodeSpaces) {
  1035. return encodeURIComponent(val).
  1036. replace(/%40/gi, '@').
  1037. replace(/%3A/gi, ':').
  1038. replace(/%24/g, '$').
  1039. replace(/%2C/gi, ',').
  1040. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1041. }
  1042. /**
  1043. * @ngdoc directive
  1044. * @name ng.directive:ngApp
  1045. *
  1046. * @element ANY
  1047. * @param {angular.Module} ngApp an optional application
  1048. * {@link angular.module module} name to load.
  1049. *
  1050. * @description
  1051. *
  1052. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1053. * designates the **root element** of the application and is typically placed near the root element
  1054. * of the page - e.g. on the `<body>` or `<html>` tags.
  1055. *
  1056. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1057. * found in the document will be used to define the root element to auto-bootstrap as an
  1058. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1059. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1060. *
  1061. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1062. * module will be loaded into the {@link AUTO.$injector} when the application is bootstrapped and
  1063. * should contain the application code needed or have dependencies on other modules that will
  1064. * contain the code. See {@link angular.module} for more information.
  1065. *
  1066. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1067. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1068. * would not be resolved to `3`.
  1069. *
  1070. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1071. *
  1072. <example module="ngAppDemo">
  1073. <file name="index.html">
  1074. <div ng-controller="ngAppDemoController">
  1075. I can add: {{a}} + {{b}} = {{ a+b }}
  1076. </file>
  1077. <file name="script.js">
  1078. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1079. $scope.a = 1;
  1080. $scope.b = 2;
  1081. });
  1082. </file>
  1083. </example>
  1084. *
  1085. */
  1086. function angularInit(element, bootstrap) {
  1087. var elements = [element],
  1088. appElement,
  1089. module,
  1090. names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
  1091. NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
  1092. function append(element) {
  1093. element && elements.push(element);
  1094. }
  1095. forEach(names, function(name) {
  1096. names[name] = true;
  1097. append(document.getElementById(name));
  1098. name = name.replace(':', '\\:');
  1099. if (element.querySelectorAll) {
  1100. forEach(element.querySelectorAll('.' + name), append);
  1101. forEach(element.querySelectorAll('.' + name + '\\:'), append);
  1102. forEach(element.querySelectorAll('[' + name + ']'), append);
  1103. }
  1104. });
  1105. forEach(elements, function(element) {
  1106. if (!appElement) {
  1107. var className = ' ' + element.className + ' ';
  1108. var match = NG_APP_CLASS_REGEXP.exec(className);
  1109. if (match) {
  1110. appElement = element;
  1111. module = (match[2] || '').replace(/\s+/g, ',');
  1112. } else {
  1113. forEach(element.attributes, function(attr) {
  1114. if (!appElement && names[attr.name]) {
  1115. appElement = element;
  1116. module = attr.value;
  1117. }
  1118. });
  1119. }
  1120. }
  1121. });
  1122. if (appElement) {
  1123. bootstrap(appElement, module ? [module] : []);
  1124. }
  1125. }
  1126. /**
  1127. * @ngdoc function
  1128. * @name angular.bootstrap
  1129. * @description
  1130. * Use this function to manually start up angular application.
  1131. *
  1132. * See: {@link guide/bootstrap Bootstrap}
  1133. *
  1134. * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
  1135. * They must use {@link api/ng.directive:ngApp ngApp}.
  1136. *
  1137. * @param {Element} element DOM element which is the root of angular application.
  1138. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1139. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1140. * function that will be invoked by the injector as a run block.
  1141. * See: {@link angular.module modules}
  1142. * @returns {AUTO.$injector} Returns the newly created injector for this app.
  1143. */
  1144. function bootstrap(element, modules) {
  1145. var doBootstrap = function() {
  1146. element = jqLite(element);
  1147. if (element.injector()) {
  1148. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1149. throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
  1150. }
  1151. modules = modules || [];
  1152. modules.unshift(['$provide', function($provide) {
  1153. $provide.value('$rootElement', element);
  1154. }]);
  1155. modules.unshift('ng');
  1156. var injector = createInjector(modules);
  1157. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
  1158. function(scope, element, compile, injector, animate) {
  1159. scope.$apply(function() {
  1160. element.data('$injector', injector);
  1161. compile(element)(scope);
  1162. });
  1163. }]
  1164. );
  1165. return injector;
  1166. };
  1167. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1168. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1169. return doBootstrap();
  1170. }
  1171. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1172. angular.resumeBootstrap = function(extraModules) {
  1173. forEach(extraModules, function(module) {
  1174. modules.push(module);
  1175. });
  1176. doBootstrap();
  1177. };
  1178. }
  1179. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1180. function snake_case(name, separator){
  1181. separator = separator || '_';
  1182. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1183. return (pos ? separator : '') + letter.toLowerCase();
  1184. });
  1185. }
  1186. function bindJQuery() {
  1187. // bind to jQuery if present;
  1188. jQuery = window.jQuery;
  1189. // reset to jQuery or default to us.
  1190. if (jQuery) {
  1191. jqLite = jQuery;
  1192. extend(jQuery.fn, {
  1193. scope: JQLitePrototype.scope,
  1194. isolateScope: JQLitePrototype.isolateScope,
  1195. controller: JQLitePrototype.controller,
  1196. injector: JQLitePrototype.injector,
  1197. inheritedData: JQLitePrototype.inheritedData
  1198. });
  1199. // Method signature:
  1200. // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
  1201. jqLitePatchJQueryRemove('remove', true, true, false);
  1202. jqLitePatchJQueryRemove('empty', false, false, false);
  1203. jqLitePatchJQueryRemove('html', false, false, true);
  1204. } else {
  1205. jqLite = JQLite;
  1206. }
  1207. angular.element = jqLite;
  1208. }
  1209. /**
  1210. * throw error if the argument is falsy.
  1211. */
  1212. function assertArg(arg, name, reason) {
  1213. if (!arg) {
  1214. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1215. }
  1216. return arg;
  1217. }
  1218. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1219. if (acceptArrayAnnotation && isArray(arg)) {
  1220. arg = arg[arg.length - 1];
  1221. }
  1222. assertArg(isFunction(arg), name, 'not a function, got ' +
  1223. (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1224. return arg;
  1225. }
  1226. /**
  1227. * throw error if the name given is hasOwnProperty
  1228. * @param {String} name the name to test
  1229. * @param {String} context the context in which the name is used, such as module or directive
  1230. */
  1231. function assertNotHasOwnProperty(name, context) {
  1232. if (name === 'hasOwnProperty') {
  1233. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1234. }
  1235. }
  1236. /**
  1237. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1238. * @param {Object} obj starting object
  1239. * @param {string} path path to traverse
  1240. * @param {boolean=true} bindFnToScope
  1241. * @returns value as accessible by path
  1242. */
  1243. //TODO(misko): this function needs to be removed
  1244. function getter(obj, path, bindFnToScope) {
  1245. if (!path) return obj;
  1246. var keys = path.split('.');
  1247. var key;
  1248. var lastInstance = obj;
  1249. var len = keys.length;
  1250. for (var i = 0; i < len; i++) {
  1251. key = keys[i];
  1252. if (obj) {
  1253. obj = (lastInstance = obj)[key];
  1254. }
  1255. }
  1256. if (!bindFnToScope && isFunction(obj)) {
  1257. return bind(lastInstance, obj);
  1258. }
  1259. return obj;
  1260. }
  1261. /**
  1262. * Return the DOM siblings between the first and last node in the given array.
  1263. * @param {Array} array like object
  1264. * @returns jQlite object containing the elements
  1265. */
  1266. function getBlockElements(nodes) {
  1267. var startNode = nodes[0],
  1268. endNode = nodes[nodes.length - 1];
  1269. if (startNode === endNode) {
  1270. return jqLite(startNode);
  1271. }
  1272. var element = startNode;
  1273. var elements = [element];
  1274. do {
  1275. element = element.nextSibling;
  1276. if (!element) break;
  1277. elements.push(element);
  1278. } while (element !== endNode);
  1279. return jqLite(elements);
  1280. }
  1281. /**
  1282. * @ngdoc interface
  1283. * @name angular.Module
  1284. * @description
  1285. *
  1286. * Interface for configuring angular {@link angular.module modules}.
  1287. */
  1288. function setupModuleLoader(window) {
  1289. var $injectorMinErr = minErr('$injector');
  1290. var ngMinErr = minErr('ng');
  1291. function ensure(obj, name, factory) {
  1292. return obj[name] || (obj[name] = factory());
  1293. }
  1294. var angular = ensure(window, 'angular', Object);
  1295. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1296. angular.$$minErr = angular.$$minErr || minErr;
  1297. return ensure(angular, 'module', function() {
  1298. /** @type {Object.<string, angular.Module>} */
  1299. var modules = {};
  1300. /**
  1301. * @ngdoc function
  1302. * @name angular.module
  1303. * @description
  1304. *
  1305. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1306. * modules.
  1307. * All modules (angular core or 3rd party) that should be available to an application must be
  1308. * registered using this mechanism.
  1309. *
  1310. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1311. * existing module (the name passed as the first argument to `module`) is retrieved.
  1312. *
  1313. *
  1314. * # Module
  1315. *
  1316. * A module is a collection of services, directives, filters, and configuration information.
  1317. * `angular.module` is used to configure the {@link AUTO.$injector $injector}.
  1318. *
  1319. * <pre>
  1320. * // Create a new module
  1321. * var myModule = angular.module('myModule', []);
  1322. *
  1323. * // register a new service
  1324. * myModule.value('appName', 'MyCoolApp');
  1325. *
  1326. * // configure existing services inside initialization blocks.
  1327. * myModule.config(function($locationProvider) {
  1328. * // Configure existing providers
  1329. * $locationProvider.hashPrefix('!');
  1330. * });
  1331. * </pre>
  1332. *
  1333. * Then you can create an injector and load your modules like this:
  1334. *
  1335. * <pre>
  1336. * var injector = angular.injector(['ng', 'MyModule'])
  1337. * </pre>
  1338. *
  1339. * However it's more likely that you'll just use
  1340. * {@link ng.directive:ngApp ngApp} or
  1341. * {@link angular.bootstrap} to simplify this process for you.
  1342. *
  1343. * @param {!string} name The name of the module to create or retrieve.
  1344. * @param {Array.<string>=} requires If specified then new module is being created. If
  1345. * unspecified then the the module is being retrieved for further configuration.
  1346. * @param {Function} configFn Optional configuration function for the module. Same as
  1347. * {@link angular.Module#methods_config Module#config()}.
  1348. * @returns {module} new module with the {@link angular.Module} api.
  1349. */
  1350. return function module(name, requires, configFn) {
  1351. var assertNotHasOwnProperty = function(name, context) {
  1352. if (name === 'hasOwnProperty') {
  1353. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1354. }
  1355. };
  1356. assertNotHasOwnProperty(name, 'module');
  1357. if (requires && modules.hasOwnProperty(name)) {
  1358. modules[name] = null;
  1359. }
  1360. return ensure(modules, name, function() {
  1361. if (!requires) {
  1362. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1363. "the module name or forgot to load it. If registering a module ensure that you " +
  1364. "specify the dependencies as the second argument.", name);
  1365. }
  1366. /** @type {!Array.<Array.<*>>} */
  1367. var invokeQueue = [];
  1368. /** @type {!Array.<Function>} */
  1369. var runBlocks = [];
  1370. var config = invokeLater('$injector', 'invoke');
  1371. /** @type {angular.Module} */
  1372. var moduleInstance = {
  1373. // Private state
  1374. _invokeQueue: invokeQueue,
  1375. _runBlocks: runBlocks,
  1376. /**
  1377. * @ngdoc property
  1378. * @name angular.Module#requires
  1379. * @propertyOf angular.Module
  1380. * @returns {Array.<string>} List of module names which must be loaded before this module.
  1381. * @description
  1382. * Holds the list of modules which the injector will load before the current module is
  1383. * loaded.
  1384. */
  1385. requires: requires,
  1386. /**
  1387. * @ngdoc property
  1388. * @name angular.Module#name
  1389. * @propertyOf angular.Module
  1390. * @returns {string} Name of the module.
  1391. * @description
  1392. */
  1393. name: name,
  1394. /**
  1395. * @ngdoc method
  1396. * @name angular.Module#provider
  1397. * @methodOf angular.Module
  1398. * @param {string} name service name
  1399. * @param {Function} providerType Construction function for creating new instance of the
  1400. * service.
  1401. * @description
  1402. * See {@link AUTO.$provide#provider $provide.provider()}.
  1403. */
  1404. provider: invokeLater('$provide', 'provider'),
  1405. /**
  1406. * @ngdoc method
  1407. * @name angular.Module#factory
  1408. * @methodOf angular.Module
  1409. * @param {string} name service name
  1410. * @param {Function} providerFunction Function for creating new instance of the service.
  1411. * @description
  1412. * See {@link AUTO.$provide#factory $provide.factory()}.
  1413. */
  1414. factory: invokeLater('$provide', 'factory'),
  1415. /**
  1416. * @ngdoc method
  1417. * @name angular.Module#service
  1418. * @methodOf angular.Module
  1419. * @param {string} name service name
  1420. * @param {Function} constructor A constructor function that will be instantiated.
  1421. * @description
  1422. * See {@link AUTO.$provide#service $provide.service()}.
  1423. */
  1424. service: invokeLater('$provide', 'service'),
  1425. /**
  1426. * @ngdoc method
  1427. * @name angular.Module#value
  1428. * @methodOf angular.Module
  1429. * @param {string} name service name
  1430. * @param {*} object Service instance object.
  1431. * @description
  1432. * See {@link AUTO.$provide#value $provide.value()}.
  1433. */
  1434. value: invokeLater('$provide', 'value'),
  1435. /**
  1436. * @ngdoc method
  1437. * @name angular.Module#constant
  1438. * @methodOf angular.Module
  1439. * @param {string} name constant name
  1440. * @param {*} object Constant value.
  1441. * @description
  1442. * Because the constant are fixed, they get applied before other provide methods.
  1443. * See {@link AUTO.$provide#constant $provide.constant()}.
  1444. */
  1445. constant: invokeLater('$provide', 'constant', 'unshift'),
  1446. /**
  1447. * @ngdoc method
  1448. * @name angular.Module#animation
  1449. * @methodOf angular.Module
  1450. * @param {string} name animation name
  1451. * @param {Function} animationFactory Factory function for creating new instance of an
  1452. * animation.
  1453. * @description
  1454. *
  1455. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1456. *
  1457. *
  1458. * Defines an animation hook that can be later used with
  1459. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1460. *
  1461. * <pre>
  1462. * module.animation('.animation-name', function($inject1, $inject2) {
  1463. * return {
  1464. * eventName : function(element, done) {
  1465. * //code to run the animation
  1466. * //once complete, then run done()
  1467. * return function cancellationFunction(element) {
  1468. * //code to cancel the animation
  1469. * }
  1470. * }
  1471. * }
  1472. * })
  1473. * </pre>
  1474. *
  1475. * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
  1476. * {@link ngAnimate ngAnimate module} for more information.
  1477. */
  1478. animation: invokeLater('$animateProvider', 'register'),
  1479. /**
  1480. * @ngdoc method
  1481. * @name angular.Module#filter
  1482. * @methodOf angular.Module
  1483. * @param {string} name Filter name.
  1484. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1485. * @description
  1486. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1487. */
  1488. filter: invokeLater('$filterProvider', 'register'),
  1489. /**
  1490. * @ngdoc method
  1491. * @name angular.Module#controller
  1492. * @methodOf angular.Module
  1493. * @param {string|Object} name Controller name, or an object map of controllers where the
  1494. * keys are the names and the values are the constructors.
  1495. * @param {Function} constructor Controller constructor function.
  1496. * @description
  1497. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1498. */
  1499. controller: invokeLater('$controllerProvider', 'register'),
  1500. /**
  1501. * @ngdoc method
  1502. * @name angular.Module#directive
  1503. * @methodOf angular.Module
  1504. * @param {string|Object} name Directive name, or an object map of directives where the
  1505. * keys are the names and the values are the factories.
  1506. * @param {Function} directiveFactory Factory function for creating new instance of
  1507. * directives.
  1508. * @description
  1509. * See {@link ng.$compileProvider#methods_directive $compileProvider.directive()}.
  1510. */
  1511. directive: invokeLater('$compileProvider', 'directive'),
  1512. /**
  1513. * @ngdoc method
  1514. * @name angular.Module#config
  1515. * @methodOf angular.Module
  1516. * @param {Function} configFn Execute this function on module load. Useful for service
  1517. * configuration.
  1518. * @description
  1519. * Use this method to register work which needs to be performed on module loading.
  1520. */
  1521. config: config,
  1522. /**
  1523. * @ngdoc method
  1524. * @name angular.Module#run
  1525. * @methodOf angular.Module
  1526. * @param {Function} initializationFn Execute this function after injector creation.
  1527. * Useful for application initialization.
  1528. * @description
  1529. * Use this method to register work which should be performed when the injector is done
  1530. * loading all modules.
  1531. */
  1532. run: function(block) {
  1533. runBlocks.push(block);
  1534. return this;
  1535. }
  1536. };
  1537. if (configFn) {
  1538. config(configFn);
  1539. }
  1540. return moduleInstance;
  1541. /**
  1542. * @param {string} provider
  1543. * @param {string} method
  1544. * @param {String=} insertMethod
  1545. * @returns {angular.Module}
  1546. */
  1547. function invokeLater(provider, method, insertMethod) {
  1548. return function() {
  1549. invokeQueue[insertMethod || 'push']([provider, method, arguments]);
  1550. return moduleInstance;
  1551. };
  1552. }
  1553. });
  1554. };
  1555. });
  1556. }
  1557. /* global
  1558. angularModule: true,
  1559. version: true,
  1560. $LocaleProvider,
  1561. $CompileProvider,
  1562. htmlAnchorDirective,
  1563. inputDirective,
  1564. inputDirective,
  1565. formDirective,
  1566. scriptDirective,
  1567. selectDirective,
  1568. styleDirective,
  1569. optionDirective,
  1570. ngBindDirective,
  1571. ngBindHtmlDirective,
  1572. ngBindTemplateDirective,
  1573. ngClassDirective,
  1574. ngClassEvenDirective,
  1575. ngClassOddDirective,
  1576. ngCspDirective,
  1577. ngCloakDirective,
  1578. ngControllerDirective,
  1579. ngFormDirective,
  1580. ngHideDirective,
  1581. ngIfDirective,
  1582. ngIncludeDirective,
  1583. ngIncludeFillContentDirective,
  1584. ngInitDirective,
  1585. ngNonBindableDirective,
  1586. ngPluralizeDirective,
  1587. ngRepeatDirective,
  1588. ngShowDirective,
  1589. ngStyleDirective,
  1590. ngSwitchDirective,
  1591. ngSwitchWhenDirective,
  1592. ngSwitchDefaultDirective,
  1593. ngOptionsDirective,
  1594. ngTranscludeDirective,
  1595. ngModelDirective,
  1596. ngListDirective,
  1597. ngChangeDirective,
  1598. requiredDirective,
  1599. requiredDirective,
  1600. ngValueDirective,
  1601. ngAttributeAliasDirectives,
  1602. ngEventDirectives,
  1603. $AnchorScrollProvider,
  1604. $AnimateProvider,
  1605. $BrowserProvider,
  1606. $CacheFactoryProvider,
  1607. $ControllerProvider,
  1608. $DocumentProvider,
  1609. $ExceptionHandlerProvider,
  1610. $FilterProvider,
  1611. $InterpolateProvider,
  1612. $IntervalProvider,
  1613. $HttpProvider,
  1614. $HttpBackendProvider,
  1615. $LocationProvider,
  1616. $LogProvider,
  1617. $ParseProvider,
  1618. $RootScopeProvider,
  1619. $QProvider,
  1620. $$SanitizeUriProvider,
  1621. $SceProvider,
  1622. $SceDelegateProvider,
  1623. $SnifferProvider,
  1624. $TemplateCacheProvider,
  1625. $TimeoutProvider,
  1626. $WindowProvider
  1627. */
  1628. /**
  1629. * @ngdoc property
  1630. * @name angular.version
  1631. * @description
  1632. * An object that contains information about the current AngularJS version. This object has the
  1633. * following properties:
  1634. *
  1635. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1636. * - `major` – `{number}` – Major version number, such as "0".
  1637. * - `minor` – `{number}` – Minor version number, such as "9".
  1638. * - `dot` – `{number}` – Dot version number, such as "18".
  1639. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1640. */
  1641. var version = {
  1642. full: '1.2.5', // all of these placeholder strings will be replaced by grunt's
  1643. major: 1, // package task
  1644. minor: 2,
  1645. dot: 5,
  1646. codeName: 'singularity-expansion'
  1647. };
  1648. function publishExternalAPI(angular){
  1649. extend(angular, {
  1650. 'bootstrap': bootstrap,
  1651. 'copy': copy,
  1652. 'extend': extend,
  1653. 'equals': equals,
  1654. 'element': jqLite,
  1655. 'forEach': forEach,
  1656. 'injector': createInjector,
  1657. 'noop':noop,
  1658. 'bind':bind,
  1659. 'toJson': toJson,
  1660. 'fromJson': fromJson,
  1661. 'identity':identity,
  1662. 'isUndefined': isUndefined,
  1663. 'isDefined': isDefined,
  1664. 'isString': isString,
  1665. 'isFunction': isFunction,
  1666. 'isObject': isObject,
  1667. 'isNumber': isNumber,
  1668. 'isElement': isElement,
  1669. 'isArray': isArray,
  1670. 'version': version,
  1671. 'isDate': isDate,
  1672. 'lowercase': lowercase,
  1673. 'uppercase': uppercase,
  1674. 'callbacks': {counter: 0},
  1675. '$$minErr': minErr,
  1676. '$$csp': csp
  1677. });
  1678. angularModule = setupModuleLoader(window);
  1679. try {
  1680. angularModule('ngLocale');
  1681. } catch (e) {
  1682. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1683. }
  1684. angularModule('ng', ['ngLocale'], ['$provide',
  1685. function ngModule($provide) {
  1686. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1687. $provide.provider({
  1688. $$sanitizeUri: $$SanitizeUriProvider
  1689. });
  1690. $provide.provider('$compile', $CompileProvider).
  1691. directive({
  1692. a: htmlAnchorDirective,
  1693. input: inputDirective,
  1694. textarea: inputDirective,
  1695. form: formDirective,
  1696. script: scriptDirective,
  1697. select: selectDirective,
  1698. style: styleDirective,
  1699. option: optionDirective,
  1700. ngBind: ngBindDirective,
  1701. ngBindHtml: ngBindHtmlDirective,
  1702. ngBindTemplate: ngBindTemplateDirective,
  1703. ngClass: ngClassDirective,
  1704. ngClassEven: ngClassEvenDirective,
  1705. ngClassOdd: ngClassOddDirective,
  1706. ngCloak: ngCloakDirective,
  1707. ngController: ngControllerDirective,
  1708. ngForm: ngFormDirective,
  1709. ngHide: ngHideDirective,
  1710. ngIf: ngIfDirective,
  1711. ngInclude: ngIncludeDirective,
  1712. ngInit: ngInitDirective,
  1713. ngNonBindable: ngNonBindableDirective,
  1714. ngPluralize: ngPluralizeDirective,
  1715. ngRepeat: ngRepeatDirective,
  1716. ngShow: ngShowDirective,
  1717. ngStyle: ngStyleDirective,
  1718. ngSwitch: ngSwitchDirective,
  1719. ngSwitchWhen: ngSwitchWhenDirective,
  1720. ngSwitchDefault: ngSwitchDefaultDirective,
  1721. ngOptions: ngOptionsDirective,
  1722. ngTransclude: ngTranscludeDirective,
  1723. ngModel: ngModelDirective,
  1724. ngList: ngListDirective,
  1725. ngChange: ngChangeDirective,
  1726. required: requiredDirective,
  1727. ngRequired: requiredDirective,
  1728. ngValue: ngValueDirective
  1729. }).
  1730. directive({
  1731. ngInclude: ngIncludeFillContentDirective
  1732. }).
  1733. directive(ngAttributeAliasDirectives).
  1734. directive(ngEventDirectives);
  1735. $provide.provider({
  1736. $anchorScroll: $AnchorScrollProvider,
  1737. $animate: $AnimateProvider,
  1738. $browser: $BrowserProvider,
  1739. $cacheFactory: $CacheFactoryProvider,
  1740. $controller: $ControllerProvider,
  1741. $document: $DocumentProvider,
  1742. $exceptionHandler: $ExceptionHandlerProvider,
  1743. $filter: $FilterProvider,
  1744. $interpolate: $InterpolateProvider,
  1745. $interval: $IntervalProvider,
  1746. $http: $HttpProvider,
  1747. $httpBackend: $HttpBackendProvider,
  1748. $location: $LocationProvider,
  1749. $log: $LogProvider,
  1750. $parse: $ParseProvider,
  1751. $rootScope: $RootScopeProvider,
  1752. $q: $QProvider,
  1753. $sce: $SceProvider,
  1754. $sceDelegate: $SceDelegateProvider,
  1755. $sniffer: $SnifferProvider,
  1756. $templateCache: $TemplateCacheProvider,
  1757. $timeout: $TimeoutProvider,
  1758. $window: $WindowProvider
  1759. });
  1760. }
  1761. ]);
  1762. }
  1763. /* global
  1764. -JQLitePrototype,
  1765. -addEventListenerFn,
  1766. -removeEventListenerFn,
  1767. -BOOLEAN_ATTR
  1768. */
  1769. //////////////////////////////////
  1770. //JQLite
  1771. //////////////////////////////////
  1772. /**
  1773. * @ngdoc function
  1774. * @name angular.element
  1775. * @function
  1776. *
  1777. * @description
  1778. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  1779. *
  1780. * If jQuery is available, `angular.element` is an alias for the
  1781. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  1782. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  1783. *
  1784. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  1785. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  1786. * commonly needed functionality with the goal of having a very small footprint.</div>
  1787. *
  1788. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  1789. *
  1790. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  1791. * jqLite; they are never raw DOM references.</div>
  1792. *
  1793. * ## Angular's jqLite
  1794. * jqLite provides only the following jQuery methods:
  1795. *
  1796. * - [`addClass()`](http://api.jquery.com/addClass/)
  1797. * - [`after()`](http://api.jquery.com/after/)
  1798. * - [`append()`](http://api.jquery.com/append/)
  1799. * - [`attr()`](http://api.jquery.com/attr/)
  1800. * - [`bind()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1801. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  1802. * - [`clone()`](http://api.jquery.com/clone/)
  1803. * - [`contents()`](http://api.jquery.com/contents/)
  1804. * - [`css()`](http://api.jquery.com/css/)
  1805. * - [`data()`](http://api.jquery.com/data/)
  1806. * - [`empty()`](http://api.jquery.com/empty/)
  1807. * - [`eq()`](http://api.jquery.com/eq/)
  1808. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  1809. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  1810. * - [`html()`](http://api.jquery.com/html/)
  1811. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  1812. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1813. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  1814. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  1815. * - [`prepend()`](http://api.jquery.com/prepend/)
  1816. * - [`prop()`](http://api.jquery.com/prop/)
  1817. * - [`ready()`](http://api.jquery.com/ready/)
  1818. * - [`remove()`](http://api.jquery.com/remove/)
  1819. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  1820. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  1821. * - [`removeData()`](http://api.jquery.com/removeData/)
  1822. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  1823. * - [`text()`](http://api.jquery.com/text/)
  1824. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  1825. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  1826. * - [`unbind()`](http://api.jquery.com/off/) - Does not support namespaces
  1827. * - [`val()`](http://api.jquery.com/val/)
  1828. * - [`wrap()`](http://api.jquery.com/wrap/)
  1829. *
  1830. * ## jQuery/jqLite Extras
  1831. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  1832. *
  1833. * ### Events
  1834. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  1835. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  1836. * element before it is removed.
  1837. *
  1838. * ### Methods
  1839. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  1840. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  1841. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  1842. * `'ngModel'`).
  1843. * - `injector()` - retrieves the injector of the current element or its parent.
  1844. * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
  1845. * element or its parent.
  1846. * - `isolateScope()` - retrieves an isolate {@link api/ng.$rootScope.Scope scope} if one is attached directly to the
  1847. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  1848. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  1849. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  1850. * parent element is reached.
  1851. *
  1852. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  1853. * @returns {Object} jQuery object.
  1854. */
  1855. var jqCache = JQLite.cache = {},
  1856. jqName = JQLite.expando = 'ng-' + new Date().getTime(),
  1857. jqId = 1,
  1858. addEventListenerFn = (window.document.addEventListener
  1859. ? function(element, type, fn) {element.addEventListener(type, fn, false);}
  1860. : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
  1861. removeEventListenerFn = (window.document.removeEventListener
  1862. ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
  1863. : function(element, type, fn) {element.detachEvent('on' + type, fn); });
  1864. function jqNextId() { return ++jqId; }
  1865. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  1866. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  1867. var jqLiteMinErr = minErr('jqLite');
  1868. /**
  1869. * Converts snake_case to camelCase.
  1870. * Also there is special case for Moz prefix starting with upper case letter.
  1871. * @param name Name to normalize
  1872. */
  1873. function camelCase(name) {
  1874. return name.
  1875. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  1876. return offset ? letter.toUpperCase() : letter;
  1877. }).
  1878. replace(MOZ_HACK_REGEXP, 'Moz$1');
  1879. }
  1880. /////////////////////////////////////////////
  1881. // jQuery mutation patch
  1882. //
  1883. // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
  1884. // $destroy event on all DOM nodes being removed.
  1885. //
  1886. /////////////////////////////////////////////
  1887. function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
  1888. var originalJqFn = jQuery.fn[name];
  1889. originalJqFn = originalJqFn.$original || originalJqFn;
  1890. removePatch.$original = originalJqFn;
  1891. jQuery.fn[name] = removePatch;
  1892. function removePatch(param) {
  1893. // jshint -W040
  1894. var list = filterElems && param ? [this.filter(param)] : [this],
  1895. fireEvent = dispatchThis,
  1896. set, setIndex, setLength,
  1897. element, childIndex, childLength, children;
  1898. if (!getterIfNoArguments || param != null) {
  1899. while(list.length) {
  1900. set = list.shift();
  1901. for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
  1902. element = jqLite(set[setIndex]);
  1903. if (fireEvent) {
  1904. element.triggerHandler('$destroy');
  1905. } else {
  1906. fireEvent = !fireEvent;
  1907. }
  1908. for(childIndex = 0, childLength = (children = element.children()).length;
  1909. childIndex < childLength;
  1910. childIndex++) {
  1911. list.push(jQuery(children[childIndex]));
  1912. }
  1913. }
  1914. }
  1915. }
  1916. return originalJqFn.apply(this, arguments);
  1917. }
  1918. }
  1919. /////////////////////////////////////////////
  1920. function JQLite(element) {
  1921. if (element instanceof JQLite) {
  1922. return element;
  1923. }
  1924. if (!(this instanceof JQLite)) {
  1925. if (isString(element) && element.charAt(0) != '<') {
  1926. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  1927. }
  1928. return new JQLite(element);
  1929. }
  1930. if (isString(element)) {
  1931. var div = document.createElement('div');
  1932. // Read about the NoScope elements here:
  1933. // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
  1934. div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work!
  1935. div.removeChild(div.firstChild); // remove the superfluous div
  1936. jqLiteAddNodes(this, div.childNodes);
  1937. var fragment = jqLite(document.createDocumentFragment());
  1938. fragment.append(this); // detach the elements from the temporary DOM div.
  1939. } else {
  1940. jqLiteAddNodes(this, element);
  1941. }
  1942. }
  1943. function jqLiteClone(element) {
  1944. return element.cloneNode(true);
  1945. }
  1946. function jqLiteDealoc(element){
  1947. jqLiteRemoveData(element);
  1948. for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
  1949. jqLiteDealoc(children[i]);
  1950. }
  1951. }
  1952. function jqLiteOff(element, type, fn, unsupported) {
  1953. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  1954. var events = jqLiteExpandoStore(element, 'events'),
  1955. handle = jqLiteExpandoStore(element, 'handle');
  1956. if (!handle) return; //no listeners registered
  1957. if (isUndefined(type)) {
  1958. forEach(events, function(eventHandler, type) {
  1959. removeEventListenerFn(element, type, eventHandler);
  1960. delete events[type];
  1961. });
  1962. } else {
  1963. forEach(type.split(' '), function(type) {
  1964. if (isUndefined(fn)) {
  1965. removeEventListenerFn(element, type, events[type]);
  1966. delete events[type];
  1967. } else {
  1968. arrayRemove(events[type] || [], fn);
  1969. }
  1970. });
  1971. }
  1972. }
  1973. function jqLiteRemoveData(element, name) {
  1974. var expandoId = element[jqName],
  1975. expandoStore = jqCache[expandoId];
  1976. if (expandoStore) {
  1977. if (name) {
  1978. delete jqCache[expandoId].data[name];
  1979. return;
  1980. }
  1981. if (expandoStore.handle) {
  1982. expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
  1983. jqLiteOff(element);
  1984. }
  1985. delete jqCache[expandoId];
  1986. element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
  1987. }
  1988. }
  1989. function jqLiteExpandoStore(element, key, value) {
  1990. var expandoId = element[jqName],
  1991. expandoStore = jqCache[expandoId || -1];
  1992. if (isDefined(value)) {
  1993. if (!expandoStore) {
  1994. element[jqName] = expandoId = jqNextId();
  1995. expandoStore = jqCache[expandoId] = {};
  1996. }
  1997. expandoStore[key] = value;
  1998. } else {
  1999. return expandoStore && expandoStore[key];
  2000. }
  2001. }
  2002. function jqLiteData(element, key, value) {
  2003. var data = jqLiteExpandoStore(element, 'data'),
  2004. isSetter = isDefined(value),
  2005. keyDefined = !isSetter && isDefined(key),
  2006. isSimpleGetter = keyDefined && !isObject(key);
  2007. if (!data && !isSimpleGetter) {
  2008. jqLiteExpandoStore(element, 'data', data = {});
  2009. }
  2010. if (isSetter) {
  2011. data[key] = value;
  2012. } else {
  2013. if (keyDefined) {
  2014. if (isSimpleGetter) {
  2015. // don't create data in this case.
  2016. return data && data[key];
  2017. } else {
  2018. extend(data, key);
  2019. }
  2020. } else {
  2021. return data;
  2022. }
  2023. }
  2024. }
  2025. function jqLiteHasClass(element, selector) {
  2026. if (!element.getAttribute) return false;
  2027. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2028. indexOf( " " + selector + " " ) > -1);
  2029. }
  2030. function jqLiteRemoveClass(element, cssClasses) {
  2031. if (cssClasses && element.setAttribute) {
  2032. forEach(cssClasses.split(' '), function(cssClass) {
  2033. element.setAttribute('class', trim(
  2034. (" " + (element.getAttribute('class') || '') + " ")
  2035. .replace(/[\n\t]/g, " ")
  2036. .replace(" " + trim(cssClass) + " ", " "))
  2037. );
  2038. });
  2039. }
  2040. }
  2041. function jqLiteAddClass(element, cssClasses) {
  2042. if (cssClasses && element.setAttribute) {
  2043. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2044. .replace(/[\n\t]/g, " ");
  2045. forEach(cssClasses.split(' '), function(cssClass) {
  2046. cssClass = trim(cssClass);
  2047. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2048. existingClasses += cssClass + ' ';
  2049. }
  2050. });
  2051. element.setAttribute('class', trim(existingClasses));
  2052. }
  2053. }
  2054. function jqLiteAddNodes(root, elements) {
  2055. if (elements) {
  2056. elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
  2057. ? elements
  2058. : [ elements ];
  2059. for(var i=0; i < elements.length; i++) {
  2060. root.push(elements[i]);
  2061. }
  2062. }
  2063. }
  2064. function jqLiteController(element, name) {
  2065. return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
  2066. }
  2067. function jqLiteInheritedData(element, name, value) {
  2068. element = jqLite(element);
  2069. // if element is the document object work with the html element instead
  2070. // this makes $(document).scope() possible
  2071. if(element[0].nodeType == 9) {
  2072. element = element.find('html');
  2073. }
  2074. var names = isArray(name) ? name : [name];
  2075. while (element.length) {
  2076. for (var i = 0, ii = names.length; i < ii; i++) {
  2077. if ((value = element.data(names[i])) !== undefined) return value;
  2078. }
  2079. element = element.parent();
  2080. }
  2081. }
  2082. function jqLiteEmpty(element) {
  2083. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2084. jqLiteDealoc(childNodes[i]);
  2085. }
  2086. while (element.firstChild) {
  2087. element.removeChild(element.firstChild);
  2088. }
  2089. }
  2090. //////////////////////////////////////////
  2091. // Functions which are declared directly.
  2092. //////////////////////////////////////////
  2093. var JQLitePrototype = JQLite.prototype = {
  2094. ready: function(fn) {
  2095. var fired = false;
  2096. function trigger() {
  2097. if (fired) return;
  2098. fired = true;
  2099. fn();
  2100. }
  2101. // check if document already is loaded
  2102. if (document.readyState === 'complete'){
  2103. setTimeout(trigger);
  2104. } else {
  2105. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2106. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2107. // jshint -W064
  2108. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2109. // jshint +W064
  2110. }
  2111. },
  2112. toString: function() {
  2113. var value = [];
  2114. forEach(this, function(e){ value.push('' + e);});
  2115. return '[' + value.join(', ') + ']';
  2116. },
  2117. eq: function(index) {
  2118. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2119. },
  2120. length: 0,
  2121. push: push,
  2122. sort: [].sort,
  2123. splice: [].splice
  2124. };
  2125. //////////////////////////////////////////
  2126. // Functions iterating getter/setters.
  2127. // these functions return self on setter and
  2128. // value on get.
  2129. //////////////////////////////////////////
  2130. var BOOLEAN_ATTR = {};
  2131. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2132. BOOLEAN_ATTR[lowercase(value)] = value;
  2133. });
  2134. var BOOLEAN_ELEMENTS = {};
  2135. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2136. BOOLEAN_ELEMENTS[uppercase(value)] = true;
  2137. });
  2138. function getBooleanAttrName(element, name) {
  2139. // check dom last since we will most likely fail on name
  2140. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2141. // booleanAttr is here twice to minimize DOM access
  2142. return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
  2143. }
  2144. forEach({
  2145. data: jqLiteData,
  2146. inheritedData: jqLiteInheritedData,
  2147. scope: function(element) {
  2148. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2149. return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2150. },
  2151. isolateScope: function(element) {
  2152. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2153. return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
  2154. },
  2155. controller: jqLiteController ,
  2156. injector: function(element) {
  2157. return jqLiteInheritedData(element, '$injector');
  2158. },
  2159. removeAttr: function(element,name) {
  2160. element.removeAttribute(name);
  2161. },
  2162. hasClass: jqLiteHasClass,
  2163. css: function(element, name, value) {
  2164. name = camelCase(name);
  2165. if (isDefined(value)) {
  2166. element.style[name] = value;
  2167. } else {
  2168. var val;
  2169. if (msie <= 8) {
  2170. // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
  2171. val = element.currentStyle && element.currentStyle[name];
  2172. if (val === '') val = 'auto';
  2173. }
  2174. val = val || element.style[name];
  2175. if (msie <= 8) {
  2176. // jquery weirdness :-/
  2177. val = (val === '') ? undefined : val;
  2178. }
  2179. return val;
  2180. }
  2181. },
  2182. attr: function(element, name, value){
  2183. var lowercasedName = lowercase(name);
  2184. if (BOOLEAN_ATTR[lowercasedName]) {
  2185. if (isDefined(value)) {
  2186. if (!!value) {
  2187. element[name] = true;
  2188. element.setAttribute(name, lowercasedName);
  2189. } else {
  2190. element[name] = false;
  2191. element.removeAttribute(lowercasedName);
  2192. }
  2193. } else {
  2194. return (element[name] ||
  2195. (element.attributes.getNamedItem(name)|| noop).specified)
  2196. ? lowercasedName
  2197. : undefined;
  2198. }
  2199. } else if (isDefined(value)) {
  2200. element.setAttribute(name, value);
  2201. } else if (element.getAttribute) {
  2202. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2203. // some elements (e.g. Document) don't have get attribute, so return undefined
  2204. var ret = element.getAttribute(name, 2);
  2205. // normalize non-existing attributes to undefined (as jQuery)
  2206. return ret === null ? undefined : ret;
  2207. }
  2208. },
  2209. prop: function(element, name, value) {
  2210. if (isDefined(value)) {
  2211. element[name] = value;
  2212. } else {
  2213. return element[name];
  2214. }
  2215. },
  2216. text: (function() {
  2217. var NODE_TYPE_TEXT_PROPERTY = [];
  2218. if (msie < 9) {
  2219. NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
  2220. NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
  2221. } else {
  2222. NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
  2223. NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
  2224. }
  2225. getText.$dv = '';
  2226. return getText;
  2227. function getText(element, value) {
  2228. var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
  2229. if (isUndefined(value)) {
  2230. return textProp ? element[textProp] : '';
  2231. }
  2232. element[textProp] = value;
  2233. }
  2234. })(),
  2235. val: function(element, value) {
  2236. if (isUndefined(value)) {
  2237. if (nodeName_(element) === 'SELECT' && element.multiple) {
  2238. var result = [];
  2239. forEach(element.options, function (option) {
  2240. if (option.selected) {
  2241. result.push(option.value || option.text);
  2242. }
  2243. });
  2244. return result.length === 0 ? null : result;
  2245. }
  2246. return element.value;
  2247. }
  2248. element.value = value;
  2249. },
  2250. html: function(element, value) {
  2251. if (isUndefined(value)) {
  2252. return element.innerHTML;
  2253. }
  2254. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2255. jqLiteDealoc(childNodes[i]);
  2256. }
  2257. element.innerHTML = value;
  2258. },
  2259. empty: jqLiteEmpty
  2260. }, function(fn, name){
  2261. /**
  2262. * Properties: writes return selection, reads return first value
  2263. */
  2264. JQLite.prototype[name] = function(arg1, arg2) {
  2265. var i, key;
  2266. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2267. // in a way that survives minification.
  2268. // jqLiteEmpty takes no arguments but is a setter.
  2269. if (fn !== jqLiteEmpty &&
  2270. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2271. if (isObject(arg1)) {
  2272. // we are a write, but the object properties are the key/values
  2273. for (i = 0; i < this.length; i++) {
  2274. if (fn === jqLiteData) {
  2275. // data() takes the whole object in jQuery
  2276. fn(this[i], arg1);
  2277. } else {
  2278. for (key in arg1) {
  2279. fn(this[i], key, arg1[key]);
  2280. }
  2281. }
  2282. }
  2283. // return self for chaining
  2284. return this;
  2285. } else {
  2286. // we are a read, so read the first child.
  2287. var value = fn.$dv;
  2288. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2289. var jj = (value === undefined) ? Math.min(this.length, 1) : this.length;
  2290. for (var j = 0; j < jj; j++) {
  2291. var nodeValue = fn(this[j], arg1, arg2);
  2292. value = value ? value + nodeValue : nodeValue;
  2293. }
  2294. return value;
  2295. }
  2296. } else {
  2297. // we are a write, so apply to all children
  2298. for (i = 0; i < this.length; i++) {
  2299. fn(this[i], arg1, arg2);
  2300. }
  2301. // return self for chaining
  2302. return this;
  2303. }
  2304. };
  2305. });
  2306. function createEventHandler(element, events) {
  2307. var eventHandler = function (event, type) {
  2308. if (!event.preventDefault) {
  2309. event.preventDefault = function() {
  2310. event.returnValue = false; //ie
  2311. };
  2312. }
  2313. if (!event.stopPropagation) {
  2314. event.stopPropagation = function() {
  2315. event.cancelBubble = true; //ie
  2316. };
  2317. }
  2318. if (!event.target) {
  2319. event.target = event.srcElement || document;
  2320. }
  2321. if (isUndefined(event.defaultPrevented)) {
  2322. var prevent = event.preventDefault;
  2323. event.preventDefault = function() {
  2324. event.defaultPrevented = true;
  2325. prevent.call(event);
  2326. };
  2327. event.defaultPrevented = false;
  2328. }
  2329. event.isDefaultPrevented = function() {
  2330. return event.defaultPrevented || event.returnValue === false;
  2331. };
  2332. forEach(events[type || event.type], function(fn) {
  2333. fn.call(element, event);
  2334. });
  2335. // Remove monkey-patched methods (IE),
  2336. // as they would cause memory leaks in IE8.
  2337. if (msie <= 8) {
  2338. // IE7/8 does not allow to delete property on native object
  2339. event.preventDefault = null;
  2340. event.stopPropagation = null;
  2341. event.isDefaultPrevented = null;
  2342. } else {
  2343. // It shouldn't affect normal browsers (native methods are defined on prototype).
  2344. delete event.preventDefault;
  2345. delete event.stopPropagation;
  2346. delete event.isDefaultPrevented;
  2347. }
  2348. };
  2349. eventHandler.elem = element;
  2350. return eventHandler;
  2351. }
  2352. //////////////////////////////////////////
  2353. // Functions iterating traversal.
  2354. // These functions chain results into a single
  2355. // selector.
  2356. //////////////////////////////////////////
  2357. forEach({
  2358. removeData: jqLiteRemoveData,
  2359. dealoc: jqLiteDealoc,
  2360. on: function onFn(element, type, fn, unsupported){
  2361. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2362. var events = jqLiteExpandoStore(element, 'events'),
  2363. handle = jqLiteExpandoStore(element, 'handle');
  2364. if (!events) jqLiteExpandoStore(element, 'events', events = {});
  2365. if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
  2366. forEach(type.split(' '), function(type){
  2367. var eventFns = events[type];
  2368. if (!eventFns) {
  2369. if (type == 'mouseenter' || type == 'mouseleave') {
  2370. var contains = document.body.contains || document.body.compareDocumentPosition ?
  2371. function( a, b ) {
  2372. // jshint bitwise: false
  2373. var adown = a.nodeType === 9 ? a.documentElement : a,
  2374. bup = b && b.parentNode;
  2375. return a === bup || !!( bup && bup.nodeType === 1 && (
  2376. adown.contains ?
  2377. adown.contains( bup ) :
  2378. a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
  2379. ));
  2380. } :
  2381. function( a, b ) {
  2382. if ( b ) {
  2383. while ( (b = b.parentNode) ) {
  2384. if ( b === a ) {
  2385. return true;
  2386. }
  2387. }
  2388. }
  2389. return false;
  2390. };
  2391. events[type] = [];
  2392. // Refer to jQuery's implementation of mouseenter & mouseleave
  2393. // Read about mouseenter and mouseleave:
  2394. // http://www.quirksmode.org/js/events_mouse.html#link8
  2395. var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
  2396. onFn(element, eventmap[type], function(event) {
  2397. var target = this, related = event.relatedTarget;
  2398. // For mousenter/leave call the handler if related is outside the target.
  2399. // NB: No relatedTarget if the mouse left/entered the browser window
  2400. if ( !related || (related !== target && !contains(target, related)) ){
  2401. handle(event, type);
  2402. }
  2403. });
  2404. } else {
  2405. addEventListenerFn(element, type, handle);
  2406. events[type] = [];
  2407. }
  2408. eventFns = events[type];
  2409. }
  2410. eventFns.push(fn);
  2411. });
  2412. },
  2413. off: jqLiteOff,
  2414. replaceWith: function(element, replaceNode) {
  2415. var index, parent = element.parentNode;
  2416. jqLiteDealoc(element);
  2417. forEach(new JQLite(replaceNode), function(node){
  2418. if (index) {
  2419. parent.insertBefore(node, index.nextSibling);
  2420. } else {
  2421. parent.replaceChild(node, element);
  2422. }
  2423. index = node;
  2424. });
  2425. },
  2426. children: function(element) {
  2427. var children = [];
  2428. forEach(element.childNodes, function(element){
  2429. if (element.nodeType === 1)
  2430. children.push(element);
  2431. });
  2432. return children;
  2433. },
  2434. contents: function(element) {
  2435. return element.childNodes || [];
  2436. },
  2437. append: function(element, node) {
  2438. forEach(new JQLite(node), function(child){
  2439. if (element.nodeType === 1 || element.nodeType === 11) {
  2440. element.appendChild(child);
  2441. }
  2442. });
  2443. },
  2444. prepend: function(element, node) {
  2445. if (element.nodeType === 1) {
  2446. var index = element.firstChild;
  2447. forEach(new JQLite(node), function(child){
  2448. element.insertBefore(child, index);
  2449. });
  2450. }
  2451. },
  2452. wrap: function(element, wrapNode) {
  2453. wrapNode = jqLite(wrapNode)[0];
  2454. var parent = element.parentNode;
  2455. if (parent) {
  2456. parent.replaceChild(wrapNode, element);
  2457. }
  2458. wrapNode.appendChild(element);
  2459. },
  2460. remove: function(element) {
  2461. jqLiteDealoc(element);
  2462. var parent = element.parentNode;
  2463. if (parent) parent.removeChild(element);
  2464. },
  2465. after: function(element, newElement) {
  2466. var index = element, parent = element.parentNode;
  2467. forEach(new JQLite(newElement), function(node){
  2468. parent.insertBefore(node, index.nextSibling);
  2469. index = node;
  2470. });
  2471. },
  2472. addClass: jqLiteAddClass,
  2473. removeClass: jqLiteRemoveClass,
  2474. toggleClass: function(element, selector, condition) {
  2475. if (isUndefined(condition)) {
  2476. condition = !jqLiteHasClass(element, selector);
  2477. }
  2478. (condition ? jqLiteAddClass : jqLiteRemoveClass)(element, selector);
  2479. },
  2480. parent: function(element) {
  2481. var parent = element.parentNode;
  2482. return parent && parent.nodeType !== 11 ? parent : null;
  2483. },
  2484. next: function(element) {
  2485. if (element.nextElementSibling) {
  2486. return element.nextElementSibling;
  2487. }
  2488. // IE8 doesn't have nextElementSibling
  2489. var elm = element.nextSibling;
  2490. while (elm != null && elm.nodeType !== 1) {
  2491. elm = elm.nextSibling;
  2492. }
  2493. return elm;
  2494. },
  2495. find: function(element, selector) {
  2496. if (element.getElementsByTagName) {
  2497. return element.getElementsByTagName(selector);
  2498. } else {
  2499. return [];
  2500. }
  2501. },
  2502. clone: jqLiteClone,
  2503. triggerHandler: function(element, eventName, eventData) {
  2504. var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
  2505. eventData = eventData || [];
  2506. var event = [{
  2507. preventDefault: noop,
  2508. stopPropagation: noop
  2509. }];
  2510. forEach(eventFns, function(fn) {
  2511. fn.apply(element, event.concat(eventData));
  2512. });
  2513. }
  2514. }, function(fn, name){
  2515. /**
  2516. * chaining functions
  2517. */
  2518. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2519. var value;
  2520. for(var i=0; i < this.length; i++) {
  2521. if (isUndefined(value)) {
  2522. value = fn(this[i], arg1, arg2, arg3);
  2523. if (isDefined(value)) {
  2524. // any function which returns a value needs to be wrapped
  2525. value = jqLite(value);
  2526. }
  2527. } else {
  2528. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2529. }
  2530. }
  2531. return isDefined(value) ? value : this;
  2532. };
  2533. // bind legacy bind/unbind to on/off
  2534. JQLite.prototype.bind = JQLite.prototype.on;
  2535. JQLite.prototype.unbind = JQLite.prototype.off;
  2536. });
  2537. /**
  2538. * Computes a hash of an 'obj'.
  2539. * Hash of a:
  2540. * string is string
  2541. * number is number as string
  2542. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2543. * that is also assigned to the $$hashKey property of the object.
  2544. *
  2545. * @param obj
  2546. * @returns {string} hash string such that the same input will have the same hash string.
  2547. * The resulting string key is in 'type:hashKey' format.
  2548. */
  2549. function hashKey(obj) {
  2550. var objType = typeof obj,
  2551. key;
  2552. if (objType == 'object' && obj !== null) {
  2553. if (typeof (key = obj.$$hashKey) == 'function') {
  2554. // must invoke on object to keep the right this
  2555. key = obj.$$hashKey();
  2556. } else if (key === undefined) {
  2557. key = obj.$$hashKey = nextUid();
  2558. }
  2559. } else {
  2560. key = obj;
  2561. }
  2562. return objType + ':' + key;
  2563. }
  2564. /**
  2565. * HashMap which can use objects as keys
  2566. */
  2567. function HashMap(array){
  2568. forEach(array, this.put, this);
  2569. }
  2570. HashMap.prototype = {
  2571. /**
  2572. * Store key value pair
  2573. * @param key key to store can be any type
  2574. * @param value value to store can be any type
  2575. */
  2576. put: function(key, value) {
  2577. this[hashKey(key)] = value;
  2578. },
  2579. /**
  2580. * @param key
  2581. * @returns the value for the key
  2582. */
  2583. get: function(key) {
  2584. return this[hashKey(key)];
  2585. },
  2586. /**
  2587. * Remove the key/value pair
  2588. * @param key
  2589. */
  2590. remove: function(key) {
  2591. var value = this[key = hashKey(key)];
  2592. delete this[key];
  2593. return value;
  2594. }
  2595. };
  2596. /**
  2597. * @ngdoc function
  2598. * @name angular.injector
  2599. * @function
  2600. *
  2601. * @description
  2602. * Creates an injector function that can be used for retrieving services as well as for
  2603. * dependency injection (see {@link guide/di dependency injection}).
  2604. *
  2605. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2606. * {@link angular.module}. The `ng` module must be explicitly added.
  2607. * @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
  2608. *
  2609. * @example
  2610. * Typical usage
  2611. * <pre>
  2612. * // create an injector
  2613. * var $injector = angular.injector(['ng']);
  2614. *
  2615. * // use the injector to kick off your application
  2616. * // use the type inference to auto inject arguments, or use implicit injection
  2617. * $injector.invoke(function($rootScope, $compile, $document){
  2618. * $compile($document)($rootScope);
  2619. * $rootScope.$digest();
  2620. * });
  2621. * </pre>
  2622. *
  2623. * Sometimes you want to get access to the injector of a currently running Angular app
  2624. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2625. * application has been bootstrapped. You can do this using extra `injector()` added
  2626. * to JQuery/jqLite elements. See {@link angular.element}.
  2627. *
  2628. * *This is fairly rare but could be the case if a third party library is injecting the
  2629. * markup.*
  2630. *
  2631. * In the following example a new block of HTML containing a `ng-controller`
  2632. * directive is added to the end of the document body by JQuery. We then compile and link
  2633. * it into the current AngularJS scope.
  2634. *
  2635. * <pre>
  2636. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2637. * $(document.body).append($div);
  2638. *
  2639. * angular.element(document).injector().invoke(function($compile) {
  2640. * var scope = angular.element($div).scope();
  2641. * $compile($div)(scope);
  2642. * });
  2643. * </pre>
  2644. */
  2645. /**
  2646. * @ngdoc overview
  2647. * @name AUTO
  2648. * @description
  2649. *
  2650. * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
  2651. */
  2652. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  2653. var FN_ARG_SPLIT = /,/;
  2654. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  2655. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  2656. var $injectorMinErr = minErr('$injector');
  2657. function annotate(fn) {
  2658. var $inject,
  2659. fnText,
  2660. argDecl,
  2661. last;
  2662. if (typeof fn == 'function') {
  2663. if (!($inject = fn.$inject)) {
  2664. $inject = [];
  2665. if (fn.length) {
  2666. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  2667. argDecl = fnText.match(FN_ARGS);
  2668. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
  2669. arg.replace(FN_ARG, function(all, underscore, name){
  2670. $inject.push(name);
  2671. });
  2672. });
  2673. }
  2674. fn.$inject = $inject;
  2675. }
  2676. } else if (isArray(fn)) {
  2677. last = fn.length - 1;
  2678. assertArgFn(fn[last], 'fn');
  2679. $inject = fn.slice(0, last);
  2680. } else {
  2681. assertArgFn(fn, 'fn', true);
  2682. }
  2683. return $inject;
  2684. }
  2685. ///////////////////////////////////////
  2686. /**
  2687. * @ngdoc object
  2688. * @name AUTO.$injector
  2689. * @function
  2690. *
  2691. * @description
  2692. *
  2693. * `$injector` is used to retrieve object instances as defined by
  2694. * {@link AUTO.$provide provider}, instantiate types, invoke methods,
  2695. * and load modules.
  2696. *
  2697. * The following always holds true:
  2698. *
  2699. * <pre>
  2700. * var $injector = angular.injector();
  2701. * expect($injector.get('$injector')).toBe($injector);
  2702. * expect($injector.invoke(function($injector){
  2703. * return $injector;
  2704. * }).toBe($injector);
  2705. * </pre>
  2706. *
  2707. * # Injection Function Annotation
  2708. *
  2709. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  2710. * following are all valid ways of annotating function with injection arguments and are equivalent.
  2711. *
  2712. * <pre>
  2713. * // inferred (only works if code not minified/obfuscated)
  2714. * $injector.invoke(function(serviceA){});
  2715. *
  2716. * // annotated
  2717. * function explicit(serviceA) {};
  2718. * explicit.$inject = ['serviceA'];
  2719. * $injector.invoke(explicit);
  2720. *
  2721. * // inline
  2722. * $injector.invoke(['serviceA', function(serviceA){}]);
  2723. * </pre>
  2724. *
  2725. * ## Inference
  2726. *
  2727. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  2728. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  2729. * minification, and obfuscation tools since these tools change the argument names.
  2730. *
  2731. * ## `$inject` Annotation
  2732. * By adding a `$inject` property onto a function the injection parameters can be specified.
  2733. *
  2734. * ## Inline
  2735. * As an array of injection names, where the last item in the array is the function to call.
  2736. */
  2737. /**
  2738. * @ngdoc method
  2739. * @name AUTO.$injector#get
  2740. * @methodOf AUTO.$injector
  2741. *
  2742. * @description
  2743. * Return an instance of the service.
  2744. *
  2745. * @param {string} name The name of the instance to retrieve.
  2746. * @return {*} The instance.
  2747. */
  2748. /**
  2749. * @ngdoc method
  2750. * @name AUTO.$injector#invoke
  2751. * @methodOf AUTO.$injector
  2752. *
  2753. * @description
  2754. * Invoke the method and supply the method arguments from the `$injector`.
  2755. *
  2756. * @param {!function} fn The function to invoke. Function parameters are injected according to the
  2757. * {@link guide/di $inject Annotation} rules.
  2758. * @param {Object=} self The `this` for the invoked method.
  2759. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2760. * object first, before the `$injector` is consulted.
  2761. * @returns {*} the value returned by the invoked `fn` function.
  2762. */
  2763. /**
  2764. * @ngdoc method
  2765. * @name AUTO.$injector#has
  2766. * @methodOf AUTO.$injector
  2767. *
  2768. * @description
  2769. * Allows the user to query if the particular service exist.
  2770. *
  2771. * @param {string} Name of the service to query.
  2772. * @returns {boolean} returns true if injector has given service.
  2773. */
  2774. /**
  2775. * @ngdoc method
  2776. * @name AUTO.$injector#instantiate
  2777. * @methodOf AUTO.$injector
  2778. * @description
  2779. * Create a new instance of JS type. The method takes a constructor function invokes the new
  2780. * operator and supplies all of the arguments to the constructor function as specified by the
  2781. * constructor annotation.
  2782. *
  2783. * @param {function} Type Annotated constructor function.
  2784. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2785. * object first, before the `$injector` is consulted.
  2786. * @returns {Object} new instance of `Type`.
  2787. */
  2788. /**
  2789. * @ngdoc method
  2790. * @name AUTO.$injector#annotate
  2791. * @methodOf AUTO.$injector
  2792. *
  2793. * @description
  2794. * Returns an array of service names which the function is requesting for injection. This API is
  2795. * used by the injector to determine which services need to be injected into the function when the
  2796. * function is invoked. There are three ways in which the function can be annotated with the needed
  2797. * dependencies.
  2798. *
  2799. * # Argument names
  2800. *
  2801. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  2802. * by converting the function into a string using `toString()` method and extracting the argument
  2803. * names.
  2804. * <pre>
  2805. * // Given
  2806. * function MyController($scope, $route) {
  2807. * // ...
  2808. * }
  2809. *
  2810. * // Then
  2811. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  2812. * </pre>
  2813. *
  2814. * This method does not work with code minification / obfuscation. For this reason the following
  2815. * annotation strategies are supported.
  2816. *
  2817. * # The `$inject` property
  2818. *
  2819. * If a function has an `$inject` property and its value is an array of strings, then the strings
  2820. * represent names of services to be injected into the function.
  2821. * <pre>
  2822. * // Given
  2823. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  2824. * // ...
  2825. * }
  2826. * // Define function dependencies
  2827. * MyController['$inject'] = ['$scope', '$route'];
  2828. *
  2829. * // Then
  2830. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  2831. * </pre>
  2832. *
  2833. * # The array notation
  2834. *
  2835. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  2836. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  2837. * a way that survives minification is a better choice:
  2838. *
  2839. * <pre>
  2840. * // We wish to write this (not minification / obfuscation safe)
  2841. * injector.invoke(function($compile, $rootScope) {
  2842. * // ...
  2843. * });
  2844. *
  2845. * // We are forced to write break inlining
  2846. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  2847. * // ...
  2848. * };
  2849. * tmpFn.$inject = ['$compile', '$rootScope'];
  2850. * injector.invoke(tmpFn);
  2851. *
  2852. * // To better support inline function the inline annotation is supported
  2853. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  2854. * // ...
  2855. * }]);
  2856. *
  2857. * // Therefore
  2858. * expect(injector.annotate(
  2859. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  2860. * ).toEqual(['$compile', '$rootScope']);
  2861. * </pre>
  2862. *
  2863. * @param {function|Array.<string|Function>} fn Function for which dependent service names need to
  2864. * be retrieved as described above.
  2865. *
  2866. * @returns {Array.<string>} The names of the services which the function requires.
  2867. */
  2868. /**
  2869. * @ngdoc object
  2870. * @name AUTO.$provide
  2871. *
  2872. * @description
  2873. *
  2874. * The {@link AUTO.$provide $provide} service has a number of methods for registering components
  2875. * with the {@link AUTO.$injector $injector}. Many of these functions are also exposed on
  2876. * {@link angular.Module}.
  2877. *
  2878. * An Angular **service** is a singleton object created by a **service factory**. These **service
  2879. * factories** are functions which, in turn, are created by a **service provider**.
  2880. * The **service providers** are constructor functions. When instantiated they must contain a
  2881. * property called `$get`, which holds the **service factory** function.
  2882. *
  2883. * When you request a service, the {@link AUTO.$injector $injector} is responsible for finding the
  2884. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  2885. * function to get the instance of the **service**.
  2886. *
  2887. * Often services have no configuration options and there is no need to add methods to the service
  2888. * provider. The provider will be no more than a constructor function with a `$get` property. For
  2889. * these cases the {@link AUTO.$provide $provide} service has additional helper methods to register
  2890. * services without specifying a provider.
  2891. *
  2892. * * {@link AUTO.$provide#methods_provider provider(provider)} - registers a **service provider** with the
  2893. * {@link AUTO.$injector $injector}
  2894. * * {@link AUTO.$provide#methods_constant constant(obj)} - registers a value/object that can be accessed by
  2895. * providers and services.
  2896. * * {@link AUTO.$provide#methods_value value(obj)} - registers a value/object that can only be accessed by
  2897. * services, not providers.
  2898. * * {@link AUTO.$provide#methods_factory factory(fn)} - registers a service **factory function**, `fn`,
  2899. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  2900. * given factory function.
  2901. * * {@link AUTO.$provide#methods_service service(class)} - registers a **constructor function**, `class` that
  2902. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  2903. * a new object using the given constructor function.
  2904. *
  2905. * See the individual methods for more information and examples.
  2906. */
  2907. /**
  2908. * @ngdoc method
  2909. * @name AUTO.$provide#provider
  2910. * @methodOf AUTO.$provide
  2911. * @description
  2912. *
  2913. * Register a **provider function** with the {@link AUTO.$injector $injector}. Provider functions
  2914. * are constructor functions, whose instances are responsible for "providing" a factory for a
  2915. * service.
  2916. *
  2917. * Service provider names start with the name of the service they provide followed by `Provider`.
  2918. * For example, the {@link ng.$log $log} service has a provider called
  2919. * {@link ng.$logProvider $logProvider}.
  2920. *
  2921. * Service provider objects can have additional methods which allow configuration of the provider
  2922. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  2923. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  2924. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  2925. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  2926. * console or not.
  2927. *
  2928. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  2929. 'Provider'` key.
  2930. * @param {(Object|function())} provider If the provider is:
  2931. *
  2932. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  2933. * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be
  2934. * created.
  2935. * - `Constructor`: a new instance of the provider will be created using
  2936. * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as
  2937. * `object`.
  2938. *
  2939. * @returns {Object} registered provider instance
  2940. * @example
  2941. *
  2942. * The following example shows how to create a simple event tracking service and register it using
  2943. * {@link AUTO.$provide#methods_provider $provide.provider()}.
  2944. *
  2945. * <pre>
  2946. * // Define the eventTracker provider
  2947. * function EventTrackerProvider() {
  2948. * var trackingUrl = '/track';
  2949. *
  2950. * // A provider method for configuring where the tracked events should been saved
  2951. * this.setTrackingUrl = function(url) {
  2952. * trackingUrl = url;
  2953. * };
  2954. *
  2955. * // The service factory function
  2956. * this.$get = ['$http', function($http) {
  2957. * var trackedEvents = {};
  2958. * return {
  2959. * // Call this to track an event
  2960. * event: function(event) {
  2961. * var count = trackedEvents[event] || 0;
  2962. * count += 1;
  2963. * trackedEvents[event] = count;
  2964. * return count;
  2965. * },
  2966. * // Call this to save the tracked events to the trackingUrl
  2967. * save: function() {
  2968. * $http.post(trackingUrl, trackedEvents);
  2969. * }
  2970. * };
  2971. * }];
  2972. * }
  2973. *
  2974. * describe('eventTracker', function() {
  2975. * var postSpy;
  2976. *
  2977. * beforeEach(module(function($provide) {
  2978. * // Register the eventTracker provider
  2979. * $provide.provider('eventTracker', EventTrackerProvider);
  2980. * }));
  2981. *
  2982. * beforeEach(module(function(eventTrackerProvider) {
  2983. * // Configure eventTracker provider
  2984. * eventTrackerProvider.setTrackingUrl('/custom-track');
  2985. * }));
  2986. *
  2987. * it('tracks events', inject(function(eventTracker) {
  2988. * expect(eventTracker.event('login')).toEqual(1);
  2989. * expect(eventTracker.event('login')).toEqual(2);
  2990. * }));
  2991. *
  2992. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  2993. * postSpy = spyOn($http, 'post');
  2994. * eventTracker.event('login');
  2995. * eventTracker.save();
  2996. * expect(postSpy).toHaveBeenCalled();
  2997. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  2998. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  2999. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3000. * }));
  3001. * });
  3002. * </pre>
  3003. */
  3004. /**
  3005. * @ngdoc method
  3006. * @name AUTO.$provide#factory
  3007. * @methodOf AUTO.$provide
  3008. * @description
  3009. *
  3010. * Register a **service factory**, which will be called to return the service instance.
  3011. * This is short for registering a service where its provider consists of only a `$get` property,
  3012. * which is the given service factory function.
  3013. * You should use {@link AUTO.$provide#factory $provide.factory(getFn)} if you do not need to
  3014. * configure your service in a provider.
  3015. *
  3016. * @param {string} name The name of the instance.
  3017. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3018. * for `$provide.provider(name, {$get: $getFn})`.
  3019. * @returns {Object} registered provider instance
  3020. *
  3021. * @example
  3022. * Here is an example of registering a service
  3023. * <pre>
  3024. * $provide.factory('ping', ['$http', function($http) {
  3025. * return function ping() {
  3026. * return $http.send('/ping');
  3027. * };
  3028. * }]);
  3029. * </pre>
  3030. * You would then inject and use this service like this:
  3031. * <pre>
  3032. * someModule.controller('Ctrl', ['ping', function(ping) {
  3033. * ping();
  3034. * }]);
  3035. * </pre>
  3036. */
  3037. /**
  3038. * @ngdoc method
  3039. * @name AUTO.$provide#service
  3040. * @methodOf AUTO.$provide
  3041. * @description
  3042. *
  3043. * Register a **service constructor**, which will be invoked with `new` to create the service
  3044. * instance.
  3045. * This is short for registering a service where its provider's `$get` property is the service
  3046. * constructor function that will be used to instantiate the service instance.
  3047. *
  3048. * You should use {@link AUTO.$provide#methods_service $provide.service(class)} if you define your service
  3049. * as a type/class. This is common when using {@link http://coffeescript.org CoffeeScript}.
  3050. *
  3051. * @param {string} name The name of the instance.
  3052. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3053. * @returns {Object} registered provider instance
  3054. *
  3055. * @example
  3056. * Here is an example of registering a service using
  3057. * {@link AUTO.$provide#methods_service $provide.service(class)} that is defined as a CoffeeScript class.
  3058. * <pre>
  3059. * class Ping
  3060. * constructor: (@$http)->
  3061. * send: ()=>
  3062. * @$http.get('/ping')
  3063. *
  3064. * $provide.service('ping', ['$http', Ping])
  3065. * </pre>
  3066. * You would then inject and use this service like this:
  3067. * <pre>
  3068. * someModule.controller 'Ctrl', ['ping', (ping)->
  3069. * ping.send()
  3070. * ]
  3071. * </pre>
  3072. */
  3073. /**
  3074. * @ngdoc method
  3075. * @name AUTO.$provide#value
  3076. * @methodOf AUTO.$provide
  3077. * @description
  3078. *
  3079. * Register a **value service** with the {@link AUTO.$injector $injector}, such as a string, a
  3080. * number, an array, an object or a function. This is short for registering a service where its
  3081. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3082. * service**.
  3083. *
  3084. * Value services are similar to constant services, except that they cannot be injected into a
  3085. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3086. * an Angular
  3087. * {@link AUTO.$provide#decorator decorator}.
  3088. *
  3089. * @param {string} name The name of the instance.
  3090. * @param {*} value The value.
  3091. * @returns {Object} registered provider instance
  3092. *
  3093. * @example
  3094. * Here are some examples of creating value services.
  3095. * <pre>
  3096. * $provide.value('ADMIN_USER', 'admin');
  3097. *
  3098. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3099. *
  3100. * $provide.value('halfOf', function(value) {
  3101. * return value / 2;
  3102. * });
  3103. * </pre>
  3104. */
  3105. /**
  3106. * @ngdoc method
  3107. * @name AUTO.$provide#constant
  3108. * @methodOf AUTO.$provide
  3109. * @description
  3110. *
  3111. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3112. * with the {@link AUTO.$injector $injector}. Unlike {@link AUTO.$provide#value value} it can be
  3113. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3114. * be overridden by an Angular {@link AUTO.$provide#decorator decorator}.
  3115. *
  3116. * @param {string} name The name of the constant.
  3117. * @param {*} value The constant value.
  3118. * @returns {Object} registered instance
  3119. *
  3120. * @example
  3121. * Here a some examples of creating constants:
  3122. * <pre>
  3123. * $provide.constant('SHARD_HEIGHT', 306);
  3124. *
  3125. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3126. *
  3127. * $provide.constant('double', function(value) {
  3128. * return value * 2;
  3129. * });
  3130. * </pre>
  3131. */
  3132. /**
  3133. * @ngdoc method
  3134. * @name AUTO.$provide#decorator
  3135. * @methodOf AUTO.$provide
  3136. * @description
  3137. *
  3138. * Register a **service decorator** with the {@link AUTO.$injector $injector}. A service decorator
  3139. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3140. * service. The object returned by the decorator may be the original service, or a new service
  3141. * object which replaces or wraps and delegates to the original service.
  3142. *
  3143. * @param {string} name The name of the service to decorate.
  3144. * @param {function()} decorator This function will be invoked when the service needs to be
  3145. * instantiated and should return the decorated service instance. The function is called using
  3146. * the {@link AUTO.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3147. * Local injection arguments:
  3148. *
  3149. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3150. * decorated or delegated to.
  3151. *
  3152. * @example
  3153. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3154. * calls to {@link ng.$log#error $log.warn()}.
  3155. * <pre>
  3156. * $provider.decorator('$log', ['$delegate', function($delegate) {
  3157. * $delegate.warn = $delegate.error;
  3158. * return $delegate;
  3159. * }]);
  3160. * </pre>
  3161. */
  3162. function createInjector(modulesToLoad) {
  3163. var INSTANTIATING = {},
  3164. providerSuffix = 'Provider',
  3165. path = [],
  3166. loadedModules = new HashMap(),
  3167. providerCache = {
  3168. $provide: {
  3169. provider: supportObject(provider),
  3170. factory: supportObject(factory),
  3171. service: supportObject(service),
  3172. value: supportObject(value),
  3173. constant: supportObject(constant),
  3174. decorator: decorator
  3175. }
  3176. },
  3177. providerInjector = (providerCache.$injector =
  3178. createInternalInjector(providerCache, function() {
  3179. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3180. })),
  3181. instanceCache = {},
  3182. instanceInjector = (instanceCache.$injector =
  3183. createInternalInjector(instanceCache, function(servicename) {
  3184. var provider = providerInjector.get(servicename + providerSuffix);
  3185. return instanceInjector.invoke(provider.$get, provider);
  3186. }));
  3187. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3188. return instanceInjector;
  3189. ////////////////////////////////////
  3190. // $provider
  3191. ////////////////////////////////////
  3192. function supportObject(delegate) {
  3193. return function(key, value) {
  3194. if (isObject(key)) {
  3195. forEach(key, reverseParams(delegate));
  3196. } else {
  3197. return delegate(key, value);
  3198. }
  3199. };
  3200. }
  3201. function provider(name, provider_) {
  3202. assertNotHasOwnProperty(name, 'service');
  3203. if (isFunction(provider_) || isArray(provider_)) {
  3204. provider_ = providerInjector.instantiate(provider_);
  3205. }
  3206. if (!provider_.$get) {
  3207. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3208. }
  3209. return providerCache[name + providerSuffix] = provider_;
  3210. }
  3211. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
  3212. function service(name, constructor) {
  3213. return factory(name, ['$injector', function($injector) {
  3214. return $injector.instantiate(constructor);
  3215. }]);
  3216. }
  3217. function value(name, val) { return factory(name, valueFn(val)); }
  3218. function constant(name, value) {
  3219. assertNotHasOwnProperty(name, 'constant');
  3220. providerCache[name] = value;
  3221. instanceCache[name] = value;
  3222. }
  3223. function decorator(serviceName, decorFn) {
  3224. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3225. orig$get = origProvider.$get;
  3226. origProvider.$get = function() {
  3227. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3228. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3229. };
  3230. }
  3231. ////////////////////////////////////
  3232. // Module Loading
  3233. ////////////////////////////////////
  3234. function loadModules(modulesToLoad){
  3235. var runBlocks = [], moduleFn, invokeQueue, i, ii;
  3236. forEach(modulesToLoad, function(module) {
  3237. if (loadedModules.get(module)) return;
  3238. loadedModules.put(module, true);
  3239. try {
  3240. if (isString(module)) {
  3241. moduleFn = angularModule(module);
  3242. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3243. for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
  3244. var invokeArgs = invokeQueue[i],
  3245. provider = providerInjector.get(invokeArgs[0]);
  3246. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3247. }
  3248. } else if (isFunction(module)) {
  3249. runBlocks.push(providerInjector.invoke(module));
  3250. } else if (isArray(module)) {
  3251. runBlocks.push(providerInjector.invoke(module));
  3252. } else {
  3253. assertArgFn(module, 'module');
  3254. }
  3255. } catch (e) {
  3256. if (isArray(module)) {
  3257. module = module[module.length - 1];
  3258. }
  3259. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3260. // Safari & FF's stack traces don't contain error.message content
  3261. // unlike those of Chrome and IE
  3262. // So if stack doesn't contain message, we create a new string that contains both.
  3263. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3264. /* jshint -W022 */
  3265. e = e.message + '\n' + e.stack;
  3266. }
  3267. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3268. module, e.stack || e.message || e);
  3269. }
  3270. });
  3271. return runBlocks;
  3272. }
  3273. ////////////////////////////////////
  3274. // internal Injector
  3275. ////////////////////////////////////
  3276. function createInternalInjector(cache, factory) {
  3277. function getService(serviceName) {
  3278. if (cache.hasOwnProperty(serviceName)) {
  3279. if (cache[serviceName] === INSTANTIATING) {
  3280. throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- '));
  3281. }
  3282. return cache[serviceName];
  3283. } else {
  3284. try {
  3285. path.unshift(serviceName);
  3286. cache[serviceName] = INSTANTIATING;
  3287. return cache[serviceName] = factory(serviceName);
  3288. } finally {
  3289. path.shift();
  3290. }
  3291. }
  3292. }
  3293. function invoke(fn, self, locals){
  3294. var args = [],
  3295. $inject = annotate(fn),
  3296. length, i,
  3297. key;
  3298. for(i = 0, length = $inject.length; i < length; i++) {
  3299. key = $inject[i];
  3300. if (typeof key !== 'string') {
  3301. throw $injectorMinErr('itkn',
  3302. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3303. }
  3304. args.push(
  3305. locals && locals.hasOwnProperty(key)
  3306. ? locals[key]
  3307. : getService(key)
  3308. );
  3309. }
  3310. if (!fn.$inject) {
  3311. // this means that we must be an array.
  3312. fn = fn[length];
  3313. }
  3314. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3315. // #5388
  3316. return fn.apply(self, args);
  3317. }
  3318. function instantiate(Type, locals) {
  3319. var Constructor = function() {},
  3320. instance, returnedValue;
  3321. // Check if Type is annotated and use just the given function at n-1 as parameter
  3322. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3323. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3324. instance = new Constructor();
  3325. returnedValue = invoke(Type, instance, locals);
  3326. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3327. }
  3328. return {
  3329. invoke: invoke,
  3330. instantiate: instantiate,
  3331. get: getService,
  3332. annotate: annotate,
  3333. has: function(name) {
  3334. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3335. }
  3336. };
  3337. }
  3338. }
  3339. /**
  3340. * @ngdoc function
  3341. * @name ng.$anchorScroll
  3342. * @requires $window
  3343. * @requires $location
  3344. * @requires $rootScope
  3345. *
  3346. * @description
  3347. * When called, it checks current value of `$location.hash()` and scroll to related element,
  3348. * according to rules specified in
  3349. * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
  3350. *
  3351. * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
  3352. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
  3353. *
  3354. * @example
  3355. <example>
  3356. <file name="index.html">
  3357. <div id="scrollArea" ng-controller="ScrollCtrl">
  3358. <a ng-click="gotoBottom()">Go to bottom</a>
  3359. <a id="bottom"></a> You're at the bottom!
  3360. </div>
  3361. </file>
  3362. <file name="script.js">
  3363. function ScrollCtrl($scope, $location, $anchorScroll) {
  3364. $scope.gotoBottom = function (){
  3365. // set the location.hash to the id of
  3366. // the element you wish to scroll to.
  3367. $location.hash('bottom');
  3368. // call $anchorScroll()
  3369. $anchorScroll();
  3370. }
  3371. }
  3372. </file>
  3373. <file name="style.css">
  3374. #scrollArea {
  3375. height: 350px;
  3376. overflow: auto;
  3377. }
  3378. #bottom {
  3379. display: block;
  3380. margin-top: 2000px;
  3381. }
  3382. </file>
  3383. </example>
  3384. */
  3385. function $AnchorScrollProvider() {
  3386. var autoScrollingEnabled = true;
  3387. this.disableAutoScrolling = function() {
  3388. autoScrollingEnabled = false;
  3389. };
  3390. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3391. var document = $window.document;
  3392. // helper function to get first anchor from a NodeList
  3393. // can't use filter.filter, as it accepts only instances of Array
  3394. // and IE can't convert NodeList to an array using [].slice
  3395. // TODO(vojta): use filter if we change it to accept lists as well
  3396. function getFirstAnchor(list) {
  3397. var result = null;
  3398. forEach(list, function(element) {
  3399. if (!result && lowercase(element.nodeName) === 'a') result = element;
  3400. });
  3401. return result;
  3402. }
  3403. function scroll() {
  3404. var hash = $location.hash(), elm;
  3405. // empty hash, scroll to the top of the page
  3406. if (!hash) $window.scrollTo(0, 0);
  3407. // element with given id
  3408. else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
  3409. // first anchor with given name :-D
  3410. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
  3411. // no element and hash == 'top', scroll to the top of the page
  3412. else if (hash === 'top') $window.scrollTo(0, 0);
  3413. }
  3414. // does not scroll when user clicks on anchor link that is currently on
  3415. // (no url change, no $location.hash() change), browser native does scroll
  3416. if (autoScrollingEnabled) {
  3417. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3418. function autoScrollWatchAction() {
  3419. $rootScope.$evalAsync(scroll);
  3420. });
  3421. }
  3422. return scroll;
  3423. }];
  3424. }
  3425. var $animateMinErr = minErr('$animate');
  3426. /**
  3427. * @ngdoc object
  3428. * @name ng.$animateProvider
  3429. *
  3430. * @description
  3431. * Default implementation of $animate that doesn't perform any animations, instead just
  3432. * synchronously performs DOM
  3433. * updates and calls done() callbacks.
  3434. *
  3435. * In order to enable animations the ngAnimate module has to be loaded.
  3436. *
  3437. * To see the functional implementation check out src/ngAnimate/animate.js
  3438. */
  3439. var $AnimateProvider = ['$provide', function($provide) {
  3440. this.$$selectors = {};
  3441. /**
  3442. * @ngdoc function
  3443. * @name ng.$animateProvider#register
  3444. * @methodOf ng.$animateProvider
  3445. *
  3446. * @description
  3447. * Registers a new injectable animation factory function. The factory function produces the
  3448. * animation object which contains callback functions for each event that is expected to be
  3449. * animated.
  3450. *
  3451. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3452. * must be called once the element animation is complete. If a function is returned then the
  3453. * animation service will use this function to cancel the animation whenever a cancel event is
  3454. * triggered.
  3455. *
  3456. *
  3457. *<pre>
  3458. * return {
  3459. * eventFn : function(element, done) {
  3460. * //code to run the animation
  3461. * //once complete, then run done()
  3462. * return function cancellationFunction() {
  3463. * //code to cancel the animation
  3464. * }
  3465. * }
  3466. * }
  3467. *</pre>
  3468. *
  3469. * @param {string} name The name of the animation.
  3470. * @param {function} factory The factory function that will be executed to return the animation
  3471. * object.
  3472. */
  3473. this.register = function(name, factory) {
  3474. var key = name + '-animation';
  3475. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  3476. "Expecting class selector starting with '.' got '{0}'.", name);
  3477. this.$$selectors[name.substr(1)] = key;
  3478. $provide.factory(key, factory);
  3479. };
  3480. this.$get = ['$timeout', function($timeout) {
  3481. /**
  3482. *
  3483. * @ngdoc object
  3484. * @name ng.$animate
  3485. * @description The $animate service provides rudimentary DOM manipulation functions to
  3486. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  3487. * This service is the core service used by the ngAnimate $animator service which provides
  3488. * high-level animation hooks for CSS and JavaScript.
  3489. *
  3490. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  3491. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  3492. * manipulation operations.
  3493. *
  3494. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  3495. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  3496. * page}.
  3497. */
  3498. return {
  3499. /**
  3500. *
  3501. * @ngdoc function
  3502. * @name ng.$animate#enter
  3503. * @methodOf ng.$animate
  3504. * @function
  3505. * @description Inserts the element into the DOM either after the `after` element or within
  3506. * the `parent` element. Once complete, the done() callback will be fired (if provided).
  3507. * @param {jQuery/jqLite element} element the element which will be inserted into the DOM
  3508. * @param {jQuery/jqLite element} parent the parent element which will append the element as
  3509. * a child (if the after element is not present)
  3510. * @param {jQuery/jqLite element} after the sibling element which will append the element
  3511. * after itself
  3512. * @param {function=} done callback function that will be called after the element has been
  3513. * inserted into the DOM
  3514. */
  3515. enter : function(element, parent, after, done) {
  3516. if (after) {
  3517. after.after(element);
  3518. } else {
  3519. if (!parent || !parent[0]) {
  3520. parent = after.parent();
  3521. }
  3522. parent.append(element);
  3523. }
  3524. done && $timeout(done, 0, false);
  3525. },
  3526. /**
  3527. *
  3528. * @ngdoc function
  3529. * @name ng.$animate#leave
  3530. * @methodOf ng.$animate
  3531. * @function
  3532. * @description Removes the element from the DOM. Once complete, the done() callback will be
  3533. * fired (if provided).
  3534. * @param {jQuery/jqLite element} element the element which will be removed from the DOM
  3535. * @param {function=} done callback function that will be called after the element has been
  3536. * removed from the DOM
  3537. */
  3538. leave : function(element, done) {
  3539. element.remove();
  3540. done && $timeout(done, 0, false);
  3541. },
  3542. /**
  3543. *
  3544. * @ngdoc function
  3545. * @name ng.$animate#move
  3546. * @methodOf ng.$animate
  3547. * @function
  3548. * @description Moves the position of the provided element within the DOM to be placed
  3549. * either after the `after` element or inside of the `parent` element. Once complete, the
  3550. * done() callback will be fired (if provided).
  3551. *
  3552. * @param {jQuery/jqLite element} element the element which will be moved around within the
  3553. * DOM
  3554. * @param {jQuery/jqLite element} parent the parent element where the element will be
  3555. * inserted into (if the after element is not present)
  3556. * @param {jQuery/jqLite element} after the sibling element where the element will be
  3557. * positioned next to
  3558. * @param {function=} done the callback function (if provided) that will be fired after the
  3559. * element has been moved to its new position
  3560. */
  3561. move : function(element, parent, after, done) {
  3562. // Do not remove element before insert. Removing will cause data associated with the
  3563. // element to be dropped. Insert will implicitly do the remove.
  3564. this.enter(element, parent, after, done);
  3565. },
  3566. /**
  3567. *
  3568. * @ngdoc function
  3569. * @name ng.$animate#addClass
  3570. * @methodOf ng.$animate
  3571. * @function
  3572. * @description Adds the provided className CSS class value to the provided element. Once
  3573. * complete, the done() callback will be fired (if provided).
  3574. * @param {jQuery/jqLite element} element the element which will have the className value
  3575. * added to it
  3576. * @param {string} className the CSS class which will be added to the element
  3577. * @param {function=} done the callback function (if provided) that will be fired after the
  3578. * className value has been added to the element
  3579. */
  3580. addClass : function(element, className, done) {
  3581. className = isString(className) ?
  3582. className :
  3583. isArray(className) ? className.join(' ') : '';
  3584. forEach(element, function (element) {
  3585. jqLiteAddClass(element, className);
  3586. });
  3587. done && $timeout(done, 0, false);
  3588. },
  3589. /**
  3590. *
  3591. * @ngdoc function
  3592. * @name ng.$animate#removeClass
  3593. * @methodOf ng.$animate
  3594. * @function
  3595. * @description Removes the provided className CSS class value from the provided element.
  3596. * Once complete, the done() callback will be fired (if provided).
  3597. * @param {jQuery/jqLite element} element the element which will have the className value
  3598. * removed from it
  3599. * @param {string} className the CSS class which will be removed from the element
  3600. * @param {function=} done the callback function (if provided) that will be fired after the
  3601. * className value has been removed from the element
  3602. */
  3603. removeClass : function(element, className, done) {
  3604. className = isString(className) ?
  3605. className :
  3606. isArray(className) ? className.join(' ') : '';
  3607. forEach(element, function (element) {
  3608. jqLiteRemoveClass(element, className);
  3609. });
  3610. done && $timeout(done, 0, false);
  3611. },
  3612. enabled : noop
  3613. };
  3614. }];
  3615. }];
  3616. /**
  3617. * ! This is a private undocumented service !
  3618. *
  3619. * @name ng.$browser
  3620. * @requires $log
  3621. * @description
  3622. * This object has two goals:
  3623. *
  3624. * - hide all the global state in the browser caused by the window object
  3625. * - abstract away all the browser specific features and inconsistencies
  3626. *
  3627. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  3628. * service, which can be used for convenient testing of the application without the interaction with
  3629. * the real browser apis.
  3630. */
  3631. /**
  3632. * @param {object} window The global window object.
  3633. * @param {object} document jQuery wrapped document.
  3634. * @param {function()} XHR XMLHttpRequest constructor.
  3635. * @param {object} $log console.log or an object with the same interface.
  3636. * @param {object} $sniffer $sniffer service
  3637. */
  3638. function Browser(window, document, $log, $sniffer) {
  3639. var self = this,
  3640. rawDocument = document[0],
  3641. location = window.location,
  3642. history = window.history,
  3643. setTimeout = window.setTimeout,
  3644. clearTimeout = window.clearTimeout,
  3645. pendingDeferIds = {};
  3646. self.isMock = false;
  3647. var outstandingRequestCount = 0;
  3648. var outstandingRequestCallbacks = [];
  3649. // TODO(vojta): remove this temporary api
  3650. self.$$completeOutstandingRequest = completeOutstandingRequest;
  3651. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  3652. /**
  3653. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  3654. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  3655. */
  3656. function completeOutstandingRequest(fn) {
  3657. try {
  3658. fn.apply(null, sliceArgs(arguments, 1));
  3659. } finally {
  3660. outstandingRequestCount--;
  3661. if (outstandingRequestCount === 0) {
  3662. while(outstandingRequestCallbacks.length) {
  3663. try {
  3664. outstandingRequestCallbacks.pop()();
  3665. } catch (e) {
  3666. $log.error(e);
  3667. }
  3668. }
  3669. }
  3670. }
  3671. }
  3672. /**
  3673. * @private
  3674. * Note: this method is used only by scenario runner
  3675. * TODO(vojta): prefix this method with $$ ?
  3676. * @param {function()} callback Function that will be called when no outstanding request
  3677. */
  3678. self.notifyWhenNoOutstandingRequests = function(callback) {
  3679. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  3680. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  3681. // regular poller would result in flaky tests.
  3682. forEach(pollFns, function(pollFn){ pollFn(); });
  3683. if (outstandingRequestCount === 0) {
  3684. callback();
  3685. } else {
  3686. outstandingRequestCallbacks.push(callback);
  3687. }
  3688. };
  3689. //////////////////////////////////////////////////////////////
  3690. // Poll Watcher API
  3691. //////////////////////////////////////////////////////////////
  3692. var pollFns = [],
  3693. pollTimeout;
  3694. /**
  3695. * @name ng.$browser#addPollFn
  3696. * @methodOf ng.$browser
  3697. *
  3698. * @param {function()} fn Poll function to add
  3699. *
  3700. * @description
  3701. * Adds a function to the list of functions that poller periodically executes,
  3702. * and starts polling if not started yet.
  3703. *
  3704. * @returns {function()} the added function
  3705. */
  3706. self.addPollFn = function(fn) {
  3707. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  3708. pollFns.push(fn);
  3709. return fn;
  3710. };
  3711. /**
  3712. * @param {number} interval How often should browser call poll functions (ms)
  3713. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  3714. *
  3715. * @description
  3716. * Configures the poller to run in the specified intervals, using the specified
  3717. * setTimeout fn and kicks it off.
  3718. */
  3719. function startPoller(interval, setTimeout) {
  3720. (function check() {
  3721. forEach(pollFns, function(pollFn){ pollFn(); });
  3722. pollTimeout = setTimeout(check, interval);
  3723. })();
  3724. }
  3725. //////////////////////////////////////////////////////////////
  3726. // URL API
  3727. //////////////////////////////////////////////////////////////
  3728. var lastBrowserUrl = location.href,
  3729. baseElement = document.find('base'),
  3730. newLocation = null;
  3731. /**
  3732. * @name ng.$browser#url
  3733. * @methodOf ng.$browser
  3734. *
  3735. * @description
  3736. * GETTER:
  3737. * Without any argument, this method just returns current value of location.href.
  3738. *
  3739. * SETTER:
  3740. * With at least one argument, this method sets url to new value.
  3741. * If html5 history api supported, pushState/replaceState is used, otherwise
  3742. * location.href/location.replace is used.
  3743. * Returns its own instance to allow chaining
  3744. *
  3745. * NOTE: this api is intended for use only by the $location service. Please use the
  3746. * {@link ng.$location $location service} to change url.
  3747. *
  3748. * @param {string} url New url (when used as setter)
  3749. * @param {boolean=} replace Should new url replace current history record ?
  3750. */
  3751. self.url = function(url, replace) {
  3752. // Android Browser BFCache causes location reference to become stale.
  3753. if (location !== window.location) location = window.location;
  3754. // setter
  3755. if (url) {
  3756. if (lastBrowserUrl == url) return;
  3757. lastBrowserUrl = url;
  3758. if ($sniffer.history) {
  3759. if (replace) history.replaceState(null, '', url);
  3760. else {
  3761. history.pushState(null, '', url);
  3762. // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
  3763. baseElement.attr('href', baseElement.attr('href'));
  3764. }
  3765. } else {
  3766. newLocation = url;
  3767. if (replace) {
  3768. location.replace(url);
  3769. } else {
  3770. location.href = url;
  3771. }
  3772. }
  3773. return self;
  3774. // getter
  3775. } else {
  3776. // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
  3777. // methods not updating location.href synchronously.
  3778. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  3779. return newLocation || location.href.replace(/%27/g,"'");
  3780. }
  3781. };
  3782. var urlChangeListeners = [],
  3783. urlChangeInit = false;
  3784. function fireUrlChange() {
  3785. newLocation = null;
  3786. if (lastBrowserUrl == self.url()) return;
  3787. lastBrowserUrl = self.url();
  3788. forEach(urlChangeListeners, function(listener) {
  3789. listener(self.url());
  3790. });
  3791. }
  3792. /**
  3793. * @name ng.$browser#onUrlChange
  3794. * @methodOf ng.$browser
  3795. * @TODO(vojta): refactor to use node's syntax for events
  3796. *
  3797. * @description
  3798. * Register callback function that will be called, when url changes.
  3799. *
  3800. * It's only called when the url is changed by outside of angular:
  3801. * - user types different url into address bar
  3802. * - user clicks on history (forward/back) button
  3803. * - user clicks on a link
  3804. *
  3805. * It's not called when url is changed by $browser.url() method
  3806. *
  3807. * The listener gets called with new url as parameter.
  3808. *
  3809. * NOTE: this api is intended for use only by the $location service. Please use the
  3810. * {@link ng.$location $location service} to monitor url changes in angular apps.
  3811. *
  3812. * @param {function(string)} listener Listener function to be called when url changes.
  3813. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  3814. */
  3815. self.onUrlChange = function(callback) {
  3816. if (!urlChangeInit) {
  3817. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  3818. // don't fire popstate when user change the address bar and don't fire hashchange when url
  3819. // changed by push/replaceState
  3820. // html5 history api - popstate event
  3821. if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
  3822. // hashchange event
  3823. if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
  3824. // polling
  3825. else self.addPollFn(fireUrlChange);
  3826. urlChangeInit = true;
  3827. }
  3828. urlChangeListeners.push(callback);
  3829. return callback;
  3830. };
  3831. //////////////////////////////////////////////////////////////
  3832. // Misc API
  3833. //////////////////////////////////////////////////////////////
  3834. /**
  3835. * @name ng.$browser#baseHref
  3836. * @methodOf ng.$browser
  3837. *
  3838. * @description
  3839. * Returns current <base href>
  3840. * (always relative - without domain)
  3841. *
  3842. * @returns {string=} current <base href>
  3843. */
  3844. self.baseHref = function() {
  3845. var href = baseElement.attr('href');
  3846. return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : '';
  3847. };
  3848. //////////////////////////////////////////////////////////////
  3849. // Cookies API
  3850. //////////////////////////////////////////////////////////////
  3851. var lastCookies = {};
  3852. var lastCookieString = '';
  3853. var cookiePath = self.baseHref();
  3854. /**
  3855. * @name ng.$browser#cookies
  3856. * @methodOf ng.$browser
  3857. *
  3858. * @param {string=} name Cookie name
  3859. * @param {string=} value Cookie value
  3860. *
  3861. * @description
  3862. * The cookies method provides a 'private' low level access to browser cookies.
  3863. * It is not meant to be used directly, use the $cookie service instead.
  3864. *
  3865. * The return values vary depending on the arguments that the method was called with as follows:
  3866. *
  3867. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  3868. * it
  3869. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  3870. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  3871. * way)
  3872. *
  3873. * @returns {Object} Hash of all cookies (if called without any parameter)
  3874. */
  3875. self.cookies = function(name, value) {
  3876. /* global escape: false, unescape: false */
  3877. var cookieLength, cookieArray, cookie, i, index;
  3878. if (name) {
  3879. if (value === undefined) {
  3880. rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
  3881. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  3882. } else {
  3883. if (isString(value)) {
  3884. cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
  3885. ';path=' + cookiePath).length + 1;
  3886. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  3887. // - 300 cookies
  3888. // - 20 cookies per unique domain
  3889. // - 4096 bytes per cookie
  3890. if (cookieLength > 4096) {
  3891. $log.warn("Cookie '"+ name +
  3892. "' possibly not set or overflowed because it was too large ("+
  3893. cookieLength + " > 4096 bytes)!");
  3894. }
  3895. }
  3896. }
  3897. } else {
  3898. if (rawDocument.cookie !== lastCookieString) {
  3899. lastCookieString = rawDocument.cookie;
  3900. cookieArray = lastCookieString.split("; ");
  3901. lastCookies = {};
  3902. for (i = 0; i < cookieArray.length; i++) {
  3903. cookie = cookieArray[i];
  3904. index = cookie.indexOf('=');
  3905. if (index > 0) { //ignore nameless cookies
  3906. name = unescape(cookie.substring(0, index));
  3907. // the first value that is seen for a cookie is the most
  3908. // specific one. values for the same cookie name that
  3909. // follow are for less specific paths.
  3910. if (lastCookies[name] === undefined) {
  3911. lastCookies[name] = unescape(cookie.substring(index + 1));
  3912. }
  3913. }
  3914. }
  3915. }
  3916. return lastCookies;
  3917. }
  3918. };
  3919. /**
  3920. * @name ng.$browser#defer
  3921. * @methodOf ng.$browser
  3922. * @param {function()} fn A function, who's execution should be deferred.
  3923. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  3924. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  3925. *
  3926. * @description
  3927. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  3928. *
  3929. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  3930. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  3931. * via `$browser.defer.flush()`.
  3932. *
  3933. */
  3934. self.defer = function(fn, delay) {
  3935. var timeoutId;
  3936. outstandingRequestCount++;
  3937. timeoutId = setTimeout(function() {
  3938. delete pendingDeferIds[timeoutId];
  3939. completeOutstandingRequest(fn);
  3940. }, delay || 0);
  3941. pendingDeferIds[timeoutId] = true;
  3942. return timeoutId;
  3943. };
  3944. /**
  3945. * @name ng.$browser#defer.cancel
  3946. * @methodOf ng.$browser.defer
  3947. *
  3948. * @description
  3949. * Cancels a deferred task identified with `deferId`.
  3950. *
  3951. * @param {*} deferId Token returned by the `$browser.defer` function.
  3952. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  3953. * canceled.
  3954. */
  3955. self.defer.cancel = function(deferId) {
  3956. if (pendingDeferIds[deferId]) {
  3957. delete pendingDeferIds[deferId];
  3958. clearTimeout(deferId);
  3959. completeOutstandingRequest(noop);
  3960. return true;
  3961. }
  3962. return false;
  3963. };
  3964. }
  3965. function $BrowserProvider(){
  3966. this.$get = ['$window', '$log', '$sniffer', '$document',
  3967. function( $window, $log, $sniffer, $document){
  3968. return new Browser($window, $document, $log, $sniffer);
  3969. }];
  3970. }
  3971. /**
  3972. * @ngdoc object
  3973. * @name ng.$cacheFactory
  3974. *
  3975. * @description
  3976. * Factory that constructs cache objects and gives access to them.
  3977. *
  3978. * <pre>
  3979. *
  3980. * var cache = $cacheFactory('cacheId');
  3981. * expect($cacheFactory.get('cacheId')).toBe(cache);
  3982. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  3983. *
  3984. * cache.put("key", "value");
  3985. * cache.put("another key", "another value");
  3986. *
  3987. * // We've specified no options on creation
  3988. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  3989. *
  3990. * </pre>
  3991. *
  3992. *
  3993. * @param {string} cacheId Name or id of the newly created cache.
  3994. * @param {object=} options Options object that specifies the cache behavior. Properties:
  3995. *
  3996. * - `{number=}` `capacity` — turns the cache into LRU cache.
  3997. *
  3998. * @returns {object} Newly created cache object with the following set of methods:
  3999. *
  4000. * - `{object}` `info()` — Returns id, size, and options of cache.
  4001. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4002. * it.
  4003. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4004. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4005. * - `{void}` `removeAll()` — Removes all cached values.
  4006. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4007. *
  4008. */
  4009. function $CacheFactoryProvider() {
  4010. this.$get = function() {
  4011. var caches = {};
  4012. function cacheFactory(cacheId, options) {
  4013. if (cacheId in caches) {
  4014. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4015. }
  4016. var size = 0,
  4017. stats = extend({}, options, {id: cacheId}),
  4018. data = {},
  4019. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4020. lruHash = {},
  4021. freshEnd = null,
  4022. staleEnd = null;
  4023. return caches[cacheId] = {
  4024. put: function(key, value) {
  4025. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4026. refresh(lruEntry);
  4027. if (isUndefined(value)) return;
  4028. if (!(key in data)) size++;
  4029. data[key] = value;
  4030. if (size > capacity) {
  4031. this.remove(staleEnd.key);
  4032. }
  4033. return value;
  4034. },
  4035. get: function(key) {
  4036. var lruEntry = lruHash[key];
  4037. if (!lruEntry) return;
  4038. refresh(lruEntry);
  4039. return data[key];
  4040. },
  4041. remove: function(key) {
  4042. var lruEntry = lruHash[key];
  4043. if (!lruEntry) return;
  4044. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4045. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4046. link(lruEntry.n,lruEntry.p);
  4047. delete lruHash[key];
  4048. delete data[key];
  4049. size--;
  4050. },
  4051. removeAll: function() {
  4052. data = {};
  4053. size = 0;
  4054. lruHash = {};
  4055. freshEnd = staleEnd = null;
  4056. },
  4057. destroy: function() {
  4058. data = null;
  4059. stats = null;
  4060. lruHash = null;
  4061. delete caches[cacheId];
  4062. },
  4063. info: function() {
  4064. return extend({}, stats, {size: size});
  4065. }
  4066. };
  4067. /**
  4068. * makes the `entry` the freshEnd of the LRU linked list
  4069. */
  4070. function refresh(entry) {
  4071. if (entry != freshEnd) {
  4072. if (!staleEnd) {
  4073. staleEnd = entry;
  4074. } else if (staleEnd == entry) {
  4075. staleEnd = entry.n;
  4076. }
  4077. link(entry.n, entry.p);
  4078. link(entry, freshEnd);
  4079. freshEnd = entry;
  4080. freshEnd.n = null;
  4081. }
  4082. }
  4083. /**
  4084. * bidirectionally links two entries of the LRU linked list
  4085. */
  4086. function link(nextEntry, prevEntry) {
  4087. if (nextEntry != prevEntry) {
  4088. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4089. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4090. }
  4091. }
  4092. }
  4093. /**
  4094. * @ngdoc method
  4095. * @name ng.$cacheFactory#info
  4096. * @methodOf ng.$cacheFactory
  4097. *
  4098. * @description
  4099. * Get information about all the of the caches that have been created
  4100. *
  4101. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  4102. */
  4103. cacheFactory.info = function() {
  4104. var info = {};
  4105. forEach(caches, function(cache, cacheId) {
  4106. info[cacheId] = cache.info();
  4107. });
  4108. return info;
  4109. };
  4110. /**
  4111. * @ngdoc method
  4112. * @name ng.$cacheFactory#get
  4113. * @methodOf ng.$cacheFactory
  4114. *
  4115. * @description
  4116. * Get access to a cache object by the `cacheId` used when it was created.
  4117. *
  4118. * @param {string} cacheId Name or id of a cache to access.
  4119. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  4120. */
  4121. cacheFactory.get = function(cacheId) {
  4122. return caches[cacheId];
  4123. };
  4124. return cacheFactory;
  4125. };
  4126. }
  4127. /**
  4128. * @ngdoc object
  4129. * @name ng.$templateCache
  4130. *
  4131. * @description
  4132. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  4133. * can load templates directly into the cache in a `script` tag, or by consuming the
  4134. * `$templateCache` service directly.
  4135. *
  4136. * Adding via the `script` tag:
  4137. * <pre>
  4138. * <html ng-app>
  4139. * <head>
  4140. * <script type="text/ng-template" id="templateId.html">
  4141. * This is the content of the template
  4142. * </script>
  4143. * </head>
  4144. * ...
  4145. * </html>
  4146. * </pre>
  4147. *
  4148. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  4149. * the document, but it must be below the `ng-app` definition.
  4150. *
  4151. * Adding via the $templateCache service:
  4152. *
  4153. * <pre>
  4154. * var myApp = angular.module('myApp', []);
  4155. * myApp.run(function($templateCache) {
  4156. * $templateCache.put('templateId.html', 'This is the content of the template');
  4157. * });
  4158. * </pre>
  4159. *
  4160. * To retrieve the template later, simply use it in your HTML:
  4161. * <pre>
  4162. * <div ng-include=" 'templateId.html' "></div>
  4163. * </pre>
  4164. *
  4165. * or get it via Javascript:
  4166. * <pre>
  4167. * $templateCache.get('templateId.html')
  4168. * </pre>
  4169. *
  4170. * See {@link ng.$cacheFactory $cacheFactory}.
  4171. *
  4172. */
  4173. function $TemplateCacheProvider() {
  4174. this.$get = ['$cacheFactory', function($cacheFactory) {
  4175. return $cacheFactory('templates');
  4176. }];
  4177. }
  4178. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  4179. *
  4180. * DOM-related variables:
  4181. *
  4182. * - "node" - DOM Node
  4183. * - "element" - DOM Element or Node
  4184. * - "$node" or "$element" - jqLite-wrapped node or element
  4185. *
  4186. *
  4187. * Compiler related stuff:
  4188. *
  4189. * - "linkFn" - linking fn of a single directive
  4190. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  4191. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  4192. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  4193. */
  4194. /**
  4195. * @ngdoc function
  4196. * @name ng.$compile
  4197. * @function
  4198. *
  4199. * @description
  4200. * Compiles a piece of HTML string or DOM into a template and produces a template function, which
  4201. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  4202. *
  4203. * The compilation is a process of walking the DOM tree and matching DOM elements to
  4204. * {@link ng.$compileProvider#methods_directive directives}.
  4205. *
  4206. * <div class="alert alert-warning">
  4207. * **Note:** This document is an in-depth reference of all directive options.
  4208. * For a gentle introduction to directives with examples of common use cases,
  4209. * see the {@link guide/directive directive guide}.
  4210. * </div>
  4211. *
  4212. * ## Comprehensive Directive API
  4213. *
  4214. * There are many different options for a directive.
  4215. *
  4216. * The difference resides in the return value of the factory function.
  4217. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  4218. * or just the `postLink` function (all other properties will have the default values).
  4219. *
  4220. * <div class="alert alert-success">
  4221. * **Best Practice:** It's recommended to use the "directive definition object" form.
  4222. * </div>
  4223. *
  4224. * Here's an example directive declared with a Directive Definition Object:
  4225. *
  4226. * <pre>
  4227. * var myModule = angular.module(...);
  4228. *
  4229. * myModule.directive('directiveName', function factory(injectables) {
  4230. * var directiveDefinitionObject = {
  4231. * priority: 0,
  4232. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  4233. * // or
  4234. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  4235. * replace: false,
  4236. * transclude: false,
  4237. * restrict: 'A',
  4238. * scope: false,
  4239. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  4240. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  4241. * compile: function compile(tElement, tAttrs, transclude) {
  4242. * return {
  4243. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4244. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4245. * }
  4246. * // or
  4247. * // return function postLink( ... ) { ... }
  4248. * },
  4249. * // or
  4250. * // link: {
  4251. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4252. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4253. * // }
  4254. * // or
  4255. * // link: function postLink( ... ) { ... }
  4256. * };
  4257. * return directiveDefinitionObject;
  4258. * });
  4259. * </pre>
  4260. *
  4261. * <div class="alert alert-warning">
  4262. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  4263. * </div>
  4264. *
  4265. * Therefore the above can be simplified as:
  4266. *
  4267. * <pre>
  4268. * var myModule = angular.module(...);
  4269. *
  4270. * myModule.directive('directiveName', function factory(injectables) {
  4271. * var directiveDefinitionObject = {
  4272. * link: function postLink(scope, iElement, iAttrs) { ... }
  4273. * };
  4274. * return directiveDefinitionObject;
  4275. * // or
  4276. * // return function postLink(scope, iElement, iAttrs) { ... }
  4277. * });
  4278. * </pre>
  4279. *
  4280. *
  4281. *
  4282. * ### Directive Definition Object
  4283. *
  4284. * The directive definition object provides instructions to the {@link api/ng.$compile
  4285. * compiler}. The attributes are:
  4286. *
  4287. * #### `priority`
  4288. * When there are multiple directives defined on a single DOM element, sometimes it
  4289. * is necessary to specify the order in which the directives are applied. The `priority` is used
  4290. * to sort the directives before their `compile` functions get called. Priority is defined as a
  4291. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  4292. * are also run in priority order, but post-link functions are run in reverse order. The order
  4293. * of directives with the same priority is undefined. The default priority is `0`.
  4294. *
  4295. * #### `terminal`
  4296. * If set to true then the current `priority` will be the last set of directives
  4297. * which will execute (any directives at the current priority will still execute
  4298. * as the order of execution on same `priority` is undefined).
  4299. *
  4300. * #### `scope`
  4301. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  4302. * same element request a new scope, only one new scope is created. The new scope rule does not
  4303. * apply for the root of the template since the root of the template always gets a new scope.
  4304. *
  4305. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  4306. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  4307. * when creating reusable components, which should not accidentally read or modify data in the
  4308. * parent scope.
  4309. *
  4310. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  4311. * derived from the parent scope. These local properties are useful for aliasing values for
  4312. * templates. Locals definition is a hash of local scope property to its source:
  4313. *
  4314. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  4315. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  4316. * attribute name is assumed to be the same as the local name.
  4317. * Given `<widget my-attr="hello {{name}}">` and widget definition
  4318. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  4319. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  4320. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  4321. * component scope).
  4322. *
  4323. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  4324. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  4325. * name is specified then the attribute name is assumed to be the same as the local name.
  4326. * Given `<widget my-attr="parentModel">` and widget definition of
  4327. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  4328. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  4329. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  4330. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  4331. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  4332. *
  4333. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  4334. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  4335. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  4336. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  4337. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  4338. * pass data from the isolated scope via an expression and to the parent scope, this can be
  4339. * done by passing a map of local variable names and values into the expression wrapper fn.
  4340. * For example, if the expression is `increment(amount)` then we can specify the amount value
  4341. * by calling the `localFn` as `localFn({amount: 22})`.
  4342. *
  4343. *
  4344. *
  4345. * #### `controller`
  4346. * Controller constructor function. The controller is instantiated before the
  4347. * pre-linking phase and it is shared with other directives (see
  4348. * `require` attribute). This allows the directives to communicate with each other and augment
  4349. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  4350. *
  4351. * * `$scope` - Current scope associated with the element
  4352. * * `$element` - Current element
  4353. * * `$attrs` - Current attributes object for the element
  4354. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  4355. * The scope can be overridden by an optional first argument.
  4356. * `function([scope], cloneLinkingFn)`.
  4357. *
  4358. *
  4359. * #### `require`
  4360. * Require another directive and inject its controller as the fourth argument to the linking function. The
  4361. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  4362. * injected argument will be an array in corresponding order. If no such directive can be
  4363. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  4364. *
  4365. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  4366. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  4367. * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  4368. * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
  4369. * `link` fn if not found.
  4370. *
  4371. *
  4372. * #### `controllerAs`
  4373. * Controller alias at the directive scope. An alias for the controller so it
  4374. * can be referenced at the directive template. The directive needs to define a scope for this
  4375. * configuration to be used. Useful in the case when directive is used as component.
  4376. *
  4377. *
  4378. * #### `restrict`
  4379. * String of subset of `EACM` which restricts the directive to a specific directive
  4380. * declaration style. If omitted, the default (attributes only) is used.
  4381. *
  4382. * * `E` - Element name: `<my-directive></my-directive>`
  4383. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  4384. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  4385. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  4386. *
  4387. *
  4388. * #### `template`
  4389. * replace the current element with the contents of the HTML. The replacement process
  4390. * migrates all of the attributes / classes from the old element to the new one. See the
  4391. * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  4392. * Directives Guide} for an example.
  4393. *
  4394. * You can specify `template` as a string representing the template or as a function which takes
  4395. * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
  4396. * returns a string value representing the template.
  4397. *
  4398. *
  4399. * #### `templateUrl`
  4400. * Same as `template` but the template is loaded from the specified URL. Because
  4401. * the template loading is asynchronous the compilation/linking is suspended until the template
  4402. * is loaded.
  4403. *
  4404. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  4405. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  4406. * a string value representing the url. In either case, the template URL is passed through {@link
  4407. * api/ng.$sce#methods_getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  4408. *
  4409. *
  4410. * #### `replace`
  4411. * specify where the template should be inserted. Defaults to `false`.
  4412. *
  4413. * * `true` - the template will replace the current element.
  4414. * * `false` - the template will replace the contents of the current element.
  4415. *
  4416. *
  4417. * #### `transclude`
  4418. * compile the content of the element and make it available to the directive.
  4419. * Typically used with {@link api/ng.directive:ngTransclude
  4420. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  4421. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  4422. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  4423. * scope. This makes it possible for the widget to have private state, and the transclusion to
  4424. * be bound to the parent (pre-`isolate`) scope.
  4425. *
  4426. * * `true` - transclude the content of the directive.
  4427. * * `'element'` - transclude the whole element including any directives defined at lower priority.
  4428. *
  4429. *
  4430. * #### `compile`
  4431. *
  4432. * <pre>
  4433. * function compile(tElement, tAttrs, transclude) { ... }
  4434. * </pre>
  4435. *
  4436. * The compile function deals with transforming the template DOM. Since most directives do not do
  4437. * template transformation, it is not used often. Examples that require compile functions are
  4438. * directives that transform template DOM, such as {@link
  4439. * api/ng.directive:ngRepeat ngRepeat}, or load the contents
  4440. * asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The
  4441. * compile function takes the following arguments.
  4442. *
  4443. * * `tElement` - template element - The element where the directive has been declared. It is
  4444. * safe to do template transformation on the element and child elements only.
  4445. *
  4446. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  4447. * between all directive compile functions.
  4448. *
  4449. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  4450. *
  4451. * <div class="alert alert-warning">
  4452. * **Note:** The template instance and the link instance may be different objects if the template has
  4453. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  4454. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  4455. * should be done in a linking function rather than in a compile function.
  4456. * </div>
  4457. *
  4458. * <div class="alert alert-error">
  4459. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  4460. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  4461. * to the link function instead.
  4462. * </div>
  4463. * A compile function can have a return value which can be either a function or an object.
  4464. *
  4465. * * returning a (post-link) function - is equivalent to registering the linking function via the
  4466. * `link` property of the config object when the compile function is empty.
  4467. *
  4468. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  4469. * control when a linking function should be called during the linking phase. See info about
  4470. * pre-linking and post-linking functions below.
  4471. *
  4472. *
  4473. * #### `link`
  4474. * This property is used only if the `compile` property is not defined.
  4475. *
  4476. * <pre>
  4477. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  4478. * </pre>
  4479. *
  4480. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  4481. * executed after the template has been cloned. This is where most of the directive logic will be
  4482. * put.
  4483. *
  4484. * * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the
  4485. * directive for registering {@link api/ng.$rootScope.Scope#methods_$watch watches}.
  4486. *
  4487. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  4488. * manipulate the children of the element only in `postLink` function since the children have
  4489. * already been linked.
  4490. *
  4491. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  4492. * between all directive linking functions.
  4493. *
  4494. * * `controller` - a controller instance - A controller instance if at least one directive on the
  4495. * element defines a controller. The controller is shared among all the directives, which allows
  4496. * the directives to use the controllers as a communication channel.
  4497. *
  4498. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  4499. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  4500. * parameter of directive controllers.
  4501. * `function([scope], cloneLinkingFn)`.
  4502. *
  4503. *
  4504. * #### Pre-linking function
  4505. *
  4506. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  4507. * compiler linking function will fail to locate the correct elements for linking.
  4508. *
  4509. * #### Post-linking function
  4510. *
  4511. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  4512. *
  4513. * <a name="Attributes"></a>
  4514. * ### Attributes
  4515. *
  4516. * The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  4517. * `link()` or `compile()` functions. It has a variety of uses.
  4518. *
  4519. * accessing *Normalized attribute names:*
  4520. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  4521. * the attributes object allows for normalized access to
  4522. * the attributes.
  4523. *
  4524. * * *Directive inter-communication:* All directives share the same instance of the attributes
  4525. * object which allows the directives to use the attributes object as inter directive
  4526. * communication.
  4527. *
  4528. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  4529. * allowing other directives to read the interpolated value.
  4530. *
  4531. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  4532. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  4533. * the only way to easily get the actual value because during the linking phase the interpolation
  4534. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  4535. *
  4536. * <pre>
  4537. * function linkingFn(scope, elm, attrs, ctrl) {
  4538. * // get the attribute value
  4539. * console.log(attrs.ngModel);
  4540. *
  4541. * // change the attribute
  4542. * attrs.$set('ngModel', 'new value');
  4543. *
  4544. * // observe changes to interpolated attribute
  4545. * attrs.$observe('ngModel', function(value) {
  4546. * console.log('ngModel has changed value to ' + value);
  4547. * });
  4548. * }
  4549. * </pre>
  4550. *
  4551. * Below is an example using `$compileProvider`.
  4552. *
  4553. * <div class="alert alert-warning">
  4554. * **Note**: Typically directives are registered with `module.directive`. The example below is
  4555. * to illustrate how `$compile` works.
  4556. * </div>
  4557. *
  4558. <doc:example module="compile">
  4559. <doc:source>
  4560. <script>
  4561. angular.module('compile', [], function($compileProvider) {
  4562. // configure new 'compile' directive by passing a directive
  4563. // factory function. The factory function injects the '$compile'
  4564. $compileProvider.directive('compile', function($compile) {
  4565. // directive factory creates a link function
  4566. return function(scope, element, attrs) {
  4567. scope.$watch(
  4568. function(scope) {
  4569. // watch the 'compile' expression for changes
  4570. return scope.$eval(attrs.compile);
  4571. },
  4572. function(value) {
  4573. // when the 'compile' expression changes
  4574. // assign it into the current DOM
  4575. element.html(value);
  4576. // compile the new DOM and link it to the current
  4577. // scope.
  4578. // NOTE: we only compile .childNodes so that
  4579. // we don't get into infinite loop compiling ourselves
  4580. $compile(element.contents())(scope);
  4581. }
  4582. );
  4583. };
  4584. })
  4585. });
  4586. function Ctrl($scope) {
  4587. $scope.name = 'Angular';
  4588. $scope.html = 'Hello {{name}}';
  4589. }
  4590. </script>
  4591. <div ng-controller="Ctrl">
  4592. <input ng-model="name"> <br>
  4593. <textarea ng-model="html"></textarea> <br>
  4594. <div compile="html"></div>
  4595. </div>
  4596. </doc:source>
  4597. <doc:scenario>
  4598. it('should auto compile', function() {
  4599. expect(element('div[compile]').text()).toBe('Hello Angular');
  4600. input('html').enter('{{name}}!');
  4601. expect(element('div[compile]').text()).toBe('Angular!');
  4602. });
  4603. </doc:scenario>
  4604. </doc:example>
  4605. *
  4606. *
  4607. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  4608. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
  4609. * @param {number} maxPriority only apply directives lower then given priority (Only effects the
  4610. * root element(s), not their children)
  4611. * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
  4612. * (a DOM element/tree) to a scope. Where:
  4613. *
  4614. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  4615. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  4616. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  4617. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  4618. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  4619. *
  4620. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  4621. * * `scope` - is the current scope with which the linking function is working with.
  4622. *
  4623. * Calling the linking function returns the element of the template. It is either the original
  4624. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  4625. *
  4626. * After linking the view is not updated until after a call to $digest which typically is done by
  4627. * Angular automatically.
  4628. *
  4629. * If you need access to the bound view, there are two ways to do it:
  4630. *
  4631. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  4632. * before you send them to the compiler and keep this reference around.
  4633. * <pre>
  4634. * var element = $compile('<p>{{total}}</p>')(scope);
  4635. * </pre>
  4636. *
  4637. * - if on the other hand, you need the element to be cloned, the view reference from the original
  4638. * example would not point to the clone, but rather to the original template that was cloned. In
  4639. * this case, you can access the clone via the cloneAttachFn:
  4640. * <pre>
  4641. * var templateHTML = angular.element('<p>{{total}}</p>'),
  4642. * scope = ....;
  4643. *
  4644. * var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
  4645. * //attach the clone to DOM document at the right place
  4646. * });
  4647. *
  4648. * //now we have reference to the cloned DOM via `clone`
  4649. * </pre>
  4650. *
  4651. *
  4652. * For information on how the compiler works, see the
  4653. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  4654. */
  4655. var $compileMinErr = minErr('$compile');
  4656. /**
  4657. * @ngdoc service
  4658. * @name ng.$compileProvider
  4659. * @function
  4660. *
  4661. * @description
  4662. */
  4663. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  4664. function $CompileProvider($provide, $$sanitizeUriProvider) {
  4665. var hasDirectives = {},
  4666. Suffix = 'Directive',
  4667. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
  4668. CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/;
  4669. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  4670. // The assumption is that future DOM event attribute names will begin with
  4671. // 'on' and be composed of only English letters.
  4672. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  4673. /**
  4674. * @ngdoc function
  4675. * @name ng.$compileProvider#directive
  4676. * @methodOf ng.$compileProvider
  4677. * @function
  4678. *
  4679. * @description
  4680. * Register a new directive with the compiler.
  4681. *
  4682. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  4683. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  4684. * names and the values are the factories.
  4685. * @param {function|Array} directiveFactory An injectable directive factory function. See
  4686. * {@link guide/directive} for more info.
  4687. * @returns {ng.$compileProvider} Self for chaining.
  4688. */
  4689. this.directive = function registerDirective(name, directiveFactory) {
  4690. assertNotHasOwnProperty(name, 'directive');
  4691. if (isString(name)) {
  4692. assertArg(directiveFactory, 'directiveFactory');
  4693. if (!hasDirectives.hasOwnProperty(name)) {
  4694. hasDirectives[name] = [];
  4695. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  4696. function($injector, $exceptionHandler) {
  4697. var directives = [];
  4698. forEach(hasDirectives[name], function(directiveFactory, index) {
  4699. try {
  4700. var directive = $injector.invoke(directiveFactory);
  4701. if (isFunction(directive)) {
  4702. directive = { compile: valueFn(directive) };
  4703. } else if (!directive.compile && directive.link) {
  4704. directive.compile = valueFn(directive.link);
  4705. }
  4706. directive.priority = directive.priority || 0;
  4707. directive.index = index;
  4708. directive.name = directive.name || name;
  4709. directive.require = directive.require || (directive.controller && directive.name);
  4710. directive.restrict = directive.restrict || 'A';
  4711. directives.push(directive);
  4712. } catch (e) {
  4713. $exceptionHandler(e);
  4714. }
  4715. });
  4716. return directives;
  4717. }]);
  4718. }
  4719. hasDirectives[name].push(directiveFactory);
  4720. } else {
  4721. forEach(name, reverseParams(registerDirective));
  4722. }
  4723. return this;
  4724. };
  4725. /**
  4726. * @ngdoc function
  4727. * @name ng.$compileProvider#aHrefSanitizationWhitelist
  4728. * @methodOf ng.$compileProvider
  4729. * @function
  4730. *
  4731. * @description
  4732. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  4733. * urls during a[href] sanitization.
  4734. *
  4735. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  4736. *
  4737. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  4738. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  4739. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  4740. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  4741. *
  4742. * @param {RegExp=} regexp New regexp to whitelist urls with.
  4743. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  4744. * chaining otherwise.
  4745. */
  4746. this.aHrefSanitizationWhitelist = function(regexp) {
  4747. if (isDefined(regexp)) {
  4748. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  4749. return this;
  4750. } else {
  4751. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  4752. }
  4753. };
  4754. /**
  4755. * @ngdoc function
  4756. * @name ng.$compileProvider#imgSrcSanitizationWhitelist
  4757. * @methodOf ng.$compileProvider
  4758. * @function
  4759. *
  4760. * @description
  4761. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  4762. * urls during img[src] sanitization.
  4763. *
  4764. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  4765. *
  4766. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  4767. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  4768. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  4769. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  4770. *
  4771. * @param {RegExp=} regexp New regexp to whitelist urls with.
  4772. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  4773. * chaining otherwise.
  4774. */
  4775. this.imgSrcSanitizationWhitelist = function(regexp) {
  4776. if (isDefined(regexp)) {
  4777. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  4778. return this;
  4779. } else {
  4780. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  4781. }
  4782. };
  4783. this.$get = [
  4784. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  4785. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  4786. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  4787. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  4788. var Attributes = function(element, attr) {
  4789. this.$$element = element;
  4790. this.$attr = attr || {};
  4791. };
  4792. Attributes.prototype = {
  4793. $normalize: directiveNormalize,
  4794. /**
  4795. * @ngdoc function
  4796. * @name ng.$compile.directive.Attributes#$addClass
  4797. * @methodOf ng.$compile.directive.Attributes
  4798. * @function
  4799. *
  4800. * @description
  4801. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  4802. * are enabled then an animation will be triggered for the class addition.
  4803. *
  4804. * @param {string} classVal The className value that will be added to the element
  4805. */
  4806. $addClass : function(classVal) {
  4807. if(classVal && classVal.length > 0) {
  4808. $animate.addClass(this.$$element, classVal);
  4809. }
  4810. },
  4811. /**
  4812. * @ngdoc function
  4813. * @name ng.$compile.directive.Attributes#$removeClass
  4814. * @methodOf ng.$compile.directive.Attributes
  4815. * @function
  4816. *
  4817. * @description
  4818. * Removes the CSS class value specified by the classVal parameter from the element. If
  4819. * animations are enabled then an animation will be triggered for the class removal.
  4820. *
  4821. * @param {string} classVal The className value that will be removed from the element
  4822. */
  4823. $removeClass : function(classVal) {
  4824. if(classVal && classVal.length > 0) {
  4825. $animate.removeClass(this.$$element, classVal);
  4826. }
  4827. },
  4828. /**
  4829. * @ngdoc function
  4830. * @name ng.$compile.directive.Attributes#$updateClass
  4831. * @methodOf ng.$compile.directive.Attributes
  4832. * @function
  4833. *
  4834. * @description
  4835. * Adds and removes the appropriate CSS class values to the element based on the difference
  4836. * between the new and old CSS class values (specified as newClasses and oldClasses).
  4837. *
  4838. * @param {string} newClasses The current CSS className value
  4839. * @param {string} oldClasses The former CSS className value
  4840. */
  4841. $updateClass : function(newClasses, oldClasses) {
  4842. this.$removeClass(tokenDifference(oldClasses, newClasses));
  4843. this.$addClass(tokenDifference(newClasses, oldClasses));
  4844. },
  4845. /**
  4846. * Set a normalized attribute on the element in a way such that all directives
  4847. * can share the attribute. This function properly handles boolean attributes.
  4848. * @param {string} key Normalized key. (ie ngAttribute)
  4849. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  4850. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  4851. * Defaults to true.
  4852. * @param {string=} attrName Optional none normalized name. Defaults to key.
  4853. */
  4854. $set: function(key, value, writeAttr, attrName) {
  4855. // TODO: decide whether or not to throw an error if "class"
  4856. //is set through this function since it may cause $updateClass to
  4857. //become unstable.
  4858. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  4859. normalizedVal,
  4860. nodeName;
  4861. if (booleanKey) {
  4862. this.$$element.prop(key, value);
  4863. attrName = booleanKey;
  4864. }
  4865. this[key] = value;
  4866. // translate normalized key to actual key
  4867. if (attrName) {
  4868. this.$attr[key] = attrName;
  4869. } else {
  4870. attrName = this.$attr[key];
  4871. if (!attrName) {
  4872. this.$attr[key] = attrName = snake_case(key, '-');
  4873. }
  4874. }
  4875. nodeName = nodeName_(this.$$element);
  4876. // sanitize a[href] and img[src] values
  4877. if ((nodeName === 'A' && key === 'href') ||
  4878. (nodeName === 'IMG' && key === 'src')) {
  4879. this[key] = value = $$sanitizeUri(value, key === 'src');
  4880. }
  4881. if (writeAttr !== false) {
  4882. if (value === null || value === undefined) {
  4883. this.$$element.removeAttr(attrName);
  4884. } else {
  4885. this.$$element.attr(attrName, value);
  4886. }
  4887. }
  4888. // fire observers
  4889. var $$observers = this.$$observers;
  4890. $$observers && forEach($$observers[key], function(fn) {
  4891. try {
  4892. fn(value);
  4893. } catch (e) {
  4894. $exceptionHandler(e);
  4895. }
  4896. });
  4897. },
  4898. /**
  4899. * @ngdoc function
  4900. * @name ng.$compile.directive.Attributes#$observe
  4901. * @methodOf ng.$compile.directive.Attributes
  4902. * @function
  4903. *
  4904. * @description
  4905. * Observes an interpolated attribute.
  4906. *
  4907. * The observer function will be invoked once during the next `$digest` following
  4908. * compilation. The observer is then invoked whenever the interpolated value
  4909. * changes.
  4910. *
  4911. * @param {string} key Normalized key. (ie ngAttribute) .
  4912. * @param {function(interpolatedValue)} fn Function that will be called whenever
  4913. the interpolated value of the attribute changes.
  4914. * See the {@link guide/directive#Attributes Directives} guide for more info.
  4915. * @returns {function()} the `fn` parameter.
  4916. */
  4917. $observe: function(key, fn) {
  4918. var attrs = this,
  4919. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  4920. listeners = ($$observers[key] || ($$observers[key] = []));
  4921. listeners.push(fn);
  4922. $rootScope.$evalAsync(function() {
  4923. if (!listeners.$$inter) {
  4924. // no one registered attribute interpolation function, so lets call it manually
  4925. fn(attrs[key]);
  4926. }
  4927. });
  4928. return fn;
  4929. }
  4930. };
  4931. var startSymbol = $interpolate.startSymbol(),
  4932. endSymbol = $interpolate.endSymbol(),
  4933. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  4934. ? identity
  4935. : function denormalizeTemplate(template) {
  4936. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  4937. },
  4938. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  4939. return compile;
  4940. //================================
  4941. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  4942. previousCompileContext) {
  4943. if (!($compileNodes instanceof jqLite)) {
  4944. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  4945. // modify it.
  4946. $compileNodes = jqLite($compileNodes);
  4947. }
  4948. // We can not compile top level text elements since text nodes can be merged and we will
  4949. // not be able to attach scope data to them, so we will wrap them in <span>
  4950. forEach($compileNodes, function(node, index){
  4951. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  4952. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  4953. }
  4954. });
  4955. var compositeLinkFn =
  4956. compileNodes($compileNodes, transcludeFn, $compileNodes,
  4957. maxPriority, ignoreDirective, previousCompileContext);
  4958. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){
  4959. assertArg(scope, 'scope');
  4960. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  4961. // and sometimes changes the structure of the DOM.
  4962. var $linkNode = cloneConnectFn
  4963. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  4964. : $compileNodes;
  4965. forEach(transcludeControllers, function(instance, name) {
  4966. $linkNode.data('$' + name + 'Controller', instance);
  4967. });
  4968. // Attach scope only to non-text nodes.
  4969. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  4970. var node = $linkNode[i];
  4971. if (node.nodeType == 1 /* element */ || node.nodeType == 9 /* document */) {
  4972. $linkNode.eq(i).data('$scope', scope);
  4973. }
  4974. }
  4975. safeAddClass($linkNode, 'ng-scope');
  4976. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  4977. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
  4978. return $linkNode;
  4979. };
  4980. }
  4981. function safeAddClass($element, className) {
  4982. try {
  4983. $element.addClass(className);
  4984. } catch(e) {
  4985. // ignore, since it means that we are trying to set class on
  4986. // SVG element, where class name is read-only.
  4987. }
  4988. }
  4989. /**
  4990. * Compile function matches each node in nodeList against the directives. Once all directives
  4991. * for a particular node are collected their compile functions are executed. The compile
  4992. * functions return values - the linking functions - are combined into a composite linking
  4993. * function, which is the a linking function for the node.
  4994. *
  4995. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  4996. * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
  4997. * scope argument is auto-generated to the new child of the transcluded parent scope.
  4998. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  4999. * the rootElement must be set the jqLite collection of the compile root. This is
  5000. * needed so that the jqLite collection items can be replaced with widgets.
  5001. * @param {number=} max directive priority
  5002. * @returns {?function} A composite linking function of all of the matched directives or null.
  5003. */
  5004. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  5005. previousCompileContext) {
  5006. var linkFns = [],
  5007. nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
  5008. for(var i = 0; i < nodeList.length; i++) {
  5009. attrs = new Attributes();
  5010. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  5011. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  5012. ignoreDirective);
  5013. nodeLinkFn = (directives.length)
  5014. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  5015. null, [], [], previousCompileContext)
  5016. : null;
  5017. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  5018. !nodeList[i].childNodes ||
  5019. !nodeList[i].childNodes.length)
  5020. ? null
  5021. : compileNodes(nodeList[i].childNodes,
  5022. nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
  5023. linkFns.push(nodeLinkFn);
  5024. linkFns.push(childLinkFn);
  5025. linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
  5026. //use the previous context only for the first element in the virtual group
  5027. previousCompileContext = null;
  5028. }
  5029. // return a linking function if we have found anything, null otherwise
  5030. return linkFnFound ? compositeLinkFn : null;
  5031. function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
  5032. var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n;
  5033. // copy nodeList so that linking doesn't break due to live list updates.
  5034. var stableNodeList = [];
  5035. for (i = 0, ii = nodeList.length; i < ii; i++) {
  5036. stableNodeList.push(nodeList[i]);
  5037. }
  5038. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  5039. node = stableNodeList[n];
  5040. nodeLinkFn = linkFns[i++];
  5041. childLinkFn = linkFns[i++];
  5042. $node = jqLite(node);
  5043. if (nodeLinkFn) {
  5044. if (nodeLinkFn.scope) {
  5045. childScope = scope.$new();
  5046. $node.data('$scope', childScope);
  5047. safeAddClass($node, 'ng-scope');
  5048. } else {
  5049. childScope = scope;
  5050. }
  5051. childTranscludeFn = nodeLinkFn.transclude;
  5052. if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
  5053. nodeLinkFn(childLinkFn, childScope, node, $rootElement,
  5054. createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn)
  5055. );
  5056. } else {
  5057. nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn);
  5058. }
  5059. } else if (childLinkFn) {
  5060. childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
  5061. }
  5062. }
  5063. }
  5064. }
  5065. function createBoundTranscludeFn(scope, transcludeFn) {
  5066. return function boundTranscludeFn(transcludedScope, cloneFn, controllers) {
  5067. var scopeCreated = false;
  5068. if (!transcludedScope) {
  5069. transcludedScope = scope.$new();
  5070. transcludedScope.$$transcluded = true;
  5071. scopeCreated = true;
  5072. }
  5073. var clone = transcludeFn(transcludedScope, cloneFn, controllers);
  5074. if (scopeCreated) {
  5075. clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy));
  5076. }
  5077. return clone;
  5078. };
  5079. }
  5080. /**
  5081. * Looks for directives on the given node and adds them to the directive collection which is
  5082. * sorted.
  5083. *
  5084. * @param node Node to search.
  5085. * @param directives An array to which the directives are added to. This array is sorted before
  5086. * the function returns.
  5087. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  5088. * @param {number=} maxPriority Max directive priority.
  5089. */
  5090. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  5091. var nodeType = node.nodeType,
  5092. attrsMap = attrs.$attr,
  5093. match,
  5094. className;
  5095. switch(nodeType) {
  5096. case 1: /* Element */
  5097. // use the node name: <directive>
  5098. addDirective(directives,
  5099. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  5100. // iterate over the attributes
  5101. for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
  5102. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  5103. var attrStartName = false;
  5104. var attrEndName = false;
  5105. attr = nAttrs[j];
  5106. if (!msie || msie >= 8 || attr.specified) {
  5107. name = attr.name;
  5108. // support ngAttr attribute binding
  5109. ngAttrName = directiveNormalize(name);
  5110. if (NG_ATTR_BINDING.test(ngAttrName)) {
  5111. name = snake_case(ngAttrName.substr(6), '-');
  5112. }
  5113. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  5114. if (ngAttrName === directiveNName + 'Start') {
  5115. attrStartName = name;
  5116. attrEndName = name.substr(0, name.length - 5) + 'end';
  5117. name = name.substr(0, name.length - 6);
  5118. }
  5119. nName = directiveNormalize(name.toLowerCase());
  5120. attrsMap[nName] = name;
  5121. attrs[nName] = value = trim((msie && name == 'href')
  5122. ? decodeURIComponent(node.getAttribute(name, 2))
  5123. : attr.value);
  5124. if (getBooleanAttrName(node, nName)) {
  5125. attrs[nName] = true; // presence means true
  5126. }
  5127. addAttrInterpolateDirective(node, directives, value, nName);
  5128. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  5129. attrEndName);
  5130. }
  5131. }
  5132. // use class as directive
  5133. className = node.className;
  5134. if (isString(className) && className !== '') {
  5135. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  5136. nName = directiveNormalize(match[2]);
  5137. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  5138. attrs[nName] = trim(match[3]);
  5139. }
  5140. className = className.substr(match.index + match[0].length);
  5141. }
  5142. }
  5143. break;
  5144. case 3: /* Text Node */
  5145. addTextInterpolateDirective(directives, node.nodeValue);
  5146. break;
  5147. case 8: /* Comment */
  5148. try {
  5149. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  5150. if (match) {
  5151. nName = directiveNormalize(match[1]);
  5152. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  5153. attrs[nName] = trim(match[2]);
  5154. }
  5155. }
  5156. } catch (e) {
  5157. // turns out that under some circumstances IE9 throws errors when one attempts to read
  5158. // comment's node value.
  5159. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  5160. }
  5161. break;
  5162. }
  5163. directives.sort(byPriority);
  5164. return directives;
  5165. }
  5166. /**
  5167. * Given a node with an directive-start it collects all of the siblings until it finds
  5168. * directive-end.
  5169. * @param node
  5170. * @param attrStart
  5171. * @param attrEnd
  5172. * @returns {*}
  5173. */
  5174. function groupScan(node, attrStart, attrEnd) {
  5175. var nodes = [];
  5176. var depth = 0;
  5177. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  5178. var startNode = node;
  5179. do {
  5180. if (!node) {
  5181. throw $compileMinErr('uterdir',
  5182. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  5183. attrStart, attrEnd);
  5184. }
  5185. if (node.nodeType == 1 /** Element **/) {
  5186. if (node.hasAttribute(attrStart)) depth++;
  5187. if (node.hasAttribute(attrEnd)) depth--;
  5188. }
  5189. nodes.push(node);
  5190. node = node.nextSibling;
  5191. } while (depth > 0);
  5192. } else {
  5193. nodes.push(node);
  5194. }
  5195. return jqLite(nodes);
  5196. }
  5197. /**
  5198. * Wrapper for linking function which converts normal linking function into a grouped
  5199. * linking function.
  5200. * @param linkFn
  5201. * @param attrStart
  5202. * @param attrEnd
  5203. * @returns {Function}
  5204. */
  5205. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  5206. return function(scope, element, attrs, controllers, transcludeFn) {
  5207. element = groupScan(element[0], attrStart, attrEnd);
  5208. return linkFn(scope, element, attrs, controllers, transcludeFn);
  5209. };
  5210. }
  5211. /**
  5212. * Once the directives have been collected, their compile functions are executed. This method
  5213. * is responsible for inlining directive templates as well as terminating the application
  5214. * of the directives if the terminal directive has been reached.
  5215. *
  5216. * @param {Array} directives Array of collected directives to execute their compile function.
  5217. * this needs to be pre-sorted by priority order.
  5218. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  5219. * @param {Object} templateAttrs The shared attribute function
  5220. * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
  5221. * scope argument is auto-generated to the new
  5222. * child of the transcluded parent scope.
  5223. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  5224. * argument has the root jqLite array so that we can replace nodes
  5225. * on it.
  5226. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  5227. * compiling the transclusion.
  5228. * @param {Array.<Function>} preLinkFns
  5229. * @param {Array.<Function>} postLinkFns
  5230. * @param {Object} previousCompileContext Context used for previous compilation of the current
  5231. * node
  5232. * @returns linkFn
  5233. */
  5234. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  5235. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  5236. previousCompileContext) {
  5237. previousCompileContext = previousCompileContext || {};
  5238. var terminalPriority = -Number.MAX_VALUE,
  5239. newScopeDirective,
  5240. controllerDirectives = previousCompileContext.controllerDirectives,
  5241. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  5242. templateDirective = previousCompileContext.templateDirective,
  5243. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  5244. hasTranscludeDirective = false,
  5245. hasElementTranscludeDirective = false,
  5246. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  5247. directive,
  5248. directiveName,
  5249. $template,
  5250. replaceDirective = originalReplaceDirective,
  5251. childTranscludeFn = transcludeFn,
  5252. linkFn,
  5253. directiveValue;
  5254. // executes all directives on the current element
  5255. for(var i = 0, ii = directives.length; i < ii; i++) {
  5256. directive = directives[i];
  5257. var attrStart = directive.$$start;
  5258. var attrEnd = directive.$$end;
  5259. // collect multiblock sections
  5260. if (attrStart) {
  5261. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  5262. }
  5263. $template = undefined;
  5264. if (terminalPriority > directive.priority) {
  5265. break; // prevent further processing of directives
  5266. }
  5267. if (directiveValue = directive.scope) {
  5268. newScopeDirective = newScopeDirective || directive;
  5269. // skip the check for directives with async templates, we'll check the derived sync
  5270. // directive when the template arrives
  5271. if (!directive.templateUrl) {
  5272. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  5273. $compileNode);
  5274. if (isObject(directiveValue)) {
  5275. newIsolateScopeDirective = directive;
  5276. }
  5277. }
  5278. }
  5279. directiveName = directive.name;
  5280. if (!directive.templateUrl && directive.controller) {
  5281. directiveValue = directive.controller;
  5282. controllerDirectives = controllerDirectives || {};
  5283. assertNoDuplicate("'" + directiveName + "' controller",
  5284. controllerDirectives[directiveName], directive, $compileNode);
  5285. controllerDirectives[directiveName] = directive;
  5286. }
  5287. if (directiveValue = directive.transclude) {
  5288. hasTranscludeDirective = true;
  5289. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  5290. // This option should only be used by directives that know how to how to safely handle element transclusion,
  5291. // where the transcluded nodes are added or replaced after linking.
  5292. if (!directive.$$tlb) {
  5293. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  5294. nonTlbTranscludeDirective = directive;
  5295. }
  5296. if (directiveValue == 'element') {
  5297. hasElementTranscludeDirective = true;
  5298. terminalPriority = directive.priority;
  5299. $template = groupScan(compileNode, attrStart, attrEnd);
  5300. $compileNode = templateAttrs.$$element =
  5301. jqLite(document.createComment(' ' + directiveName + ': ' +
  5302. templateAttrs[directiveName] + ' '));
  5303. compileNode = $compileNode[0];
  5304. replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
  5305. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  5306. replaceDirective && replaceDirective.name, {
  5307. // Don't pass in:
  5308. // - controllerDirectives - otherwise we'll create duplicates controllers
  5309. // - newIsolateScopeDirective or templateDirective - combining templates with
  5310. // element transclusion doesn't make sense.
  5311. //
  5312. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  5313. // on the same element more than once.
  5314. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5315. });
  5316. } else {
  5317. $template = jqLite(jqLiteClone(compileNode)).contents();
  5318. $compileNode.empty(); // clear contents
  5319. childTranscludeFn = compile($template, transcludeFn);
  5320. }
  5321. }
  5322. if (directive.template) {
  5323. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5324. templateDirective = directive;
  5325. directiveValue = (isFunction(directive.template))
  5326. ? directive.template($compileNode, templateAttrs)
  5327. : directive.template;
  5328. directiveValue = denormalizeTemplate(directiveValue);
  5329. if (directive.replace) {
  5330. replaceDirective = directive;
  5331. $template = jqLite('<div>' +
  5332. trim(directiveValue) +
  5333. '</div>').contents();
  5334. compileNode = $template[0];
  5335. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5336. throw $compileMinErr('tplrt',
  5337. "Template for directive '{0}' must have exactly one root element. {1}",
  5338. directiveName, '');
  5339. }
  5340. replaceWith(jqCollection, $compileNode, compileNode);
  5341. var newTemplateAttrs = {$attr: {}};
  5342. // combine directives from the original node and from the template:
  5343. // - take the array of directives for this element
  5344. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  5345. // - collect directives from the template and sort them by priority
  5346. // - combine directives as: processed + template + unprocessed
  5347. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  5348. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  5349. if (newIsolateScopeDirective) {
  5350. markDirectivesAsIsolate(templateDirectives);
  5351. }
  5352. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  5353. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  5354. ii = directives.length;
  5355. } else {
  5356. $compileNode.html(directiveValue);
  5357. }
  5358. }
  5359. if (directive.templateUrl) {
  5360. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5361. templateDirective = directive;
  5362. if (directive.replace) {
  5363. replaceDirective = directive;
  5364. }
  5365. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  5366. templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, {
  5367. controllerDirectives: controllerDirectives,
  5368. newIsolateScopeDirective: newIsolateScopeDirective,
  5369. templateDirective: templateDirective,
  5370. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5371. });
  5372. ii = directives.length;
  5373. } else if (directive.compile) {
  5374. try {
  5375. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  5376. if (isFunction(linkFn)) {
  5377. addLinkFns(null, linkFn, attrStart, attrEnd);
  5378. } else if (linkFn) {
  5379. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  5380. }
  5381. } catch (e) {
  5382. $exceptionHandler(e, startingTag($compileNode));
  5383. }
  5384. }
  5385. if (directive.terminal) {
  5386. nodeLinkFn.terminal = true;
  5387. terminalPriority = Math.max(terminalPriority, directive.priority);
  5388. }
  5389. }
  5390. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  5391. nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn;
  5392. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  5393. return nodeLinkFn;
  5394. ////////////////////
  5395. function addLinkFns(pre, post, attrStart, attrEnd) {
  5396. if (pre) {
  5397. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  5398. pre.require = directive.require;
  5399. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5400. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  5401. }
  5402. preLinkFns.push(pre);
  5403. }
  5404. if (post) {
  5405. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  5406. post.require = directive.require;
  5407. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5408. post = cloneAndAnnotateFn(post, {isolateScope: true});
  5409. }
  5410. postLinkFns.push(post);
  5411. }
  5412. }
  5413. function getControllers(require, $element, elementControllers) {
  5414. var value, retrievalMethod = 'data', optional = false;
  5415. if (isString(require)) {
  5416. while((value = require.charAt(0)) == '^' || value == '?') {
  5417. require = require.substr(1);
  5418. if (value == '^') {
  5419. retrievalMethod = 'inheritedData';
  5420. }
  5421. optional = optional || value == '?';
  5422. }
  5423. value = null;
  5424. if (elementControllers && retrievalMethod === 'data') {
  5425. value = elementControllers[require];
  5426. }
  5427. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  5428. if (!value && !optional) {
  5429. throw $compileMinErr('ctreq',
  5430. "Controller '{0}', required by directive '{1}', can't be found!",
  5431. require, directiveName);
  5432. }
  5433. return value;
  5434. } else if (isArray(require)) {
  5435. value = [];
  5436. forEach(require, function(require) {
  5437. value.push(getControllers(require, $element, elementControllers));
  5438. });
  5439. }
  5440. return value;
  5441. }
  5442. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  5443. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  5444. if (compileNode === linkNode) {
  5445. attrs = templateAttrs;
  5446. } else {
  5447. attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  5448. }
  5449. $element = attrs.$$element;
  5450. if (newIsolateScopeDirective) {
  5451. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5452. var $linkNode = jqLite(linkNode);
  5453. isolateScope = scope.$new(true);
  5454. if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  5455. $linkNode.data('$isolateScope', isolateScope) ;
  5456. } else {
  5457. $linkNode.data('$isolateScopeNoTemplate', isolateScope);
  5458. }
  5459. safeAddClass($linkNode, 'ng-isolate-scope');
  5460. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  5461. var match = definition.match(LOCAL_REGEXP) || [],
  5462. attrName = match[3] || scopeName,
  5463. optional = (match[2] == '?'),
  5464. mode = match[1], // @, =, or &
  5465. lastValue,
  5466. parentGet, parentSet, compare;
  5467. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  5468. switch (mode) {
  5469. case '@':
  5470. attrs.$observe(attrName, function(value) {
  5471. isolateScope[scopeName] = value;
  5472. });
  5473. attrs.$$observers[attrName].$$scope = scope;
  5474. if( attrs[attrName] ) {
  5475. // If the attribute has been provided then we trigger an interpolation to ensure
  5476. // the value is there for use in the link fn
  5477. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  5478. }
  5479. break;
  5480. case '=':
  5481. if (optional && !attrs[attrName]) {
  5482. return;
  5483. }
  5484. parentGet = $parse(attrs[attrName]);
  5485. if (parentGet.literal) {
  5486. compare = equals;
  5487. } else {
  5488. compare = function(a,b) { return a === b; };
  5489. }
  5490. parentSet = parentGet.assign || function() {
  5491. // reset the change, or we will throw this exception on every $digest
  5492. lastValue = isolateScope[scopeName] = parentGet(scope);
  5493. throw $compileMinErr('nonassign',
  5494. "Expression '{0}' used with directive '{1}' is non-assignable!",
  5495. attrs[attrName], newIsolateScopeDirective.name);
  5496. };
  5497. lastValue = isolateScope[scopeName] = parentGet(scope);
  5498. isolateScope.$watch(function parentValueWatch() {
  5499. var parentValue = parentGet(scope);
  5500. if (!compare(parentValue, isolateScope[scopeName])) {
  5501. // we are out of sync and need to copy
  5502. if (!compare(parentValue, lastValue)) {
  5503. // parent changed and it has precedence
  5504. isolateScope[scopeName] = parentValue;
  5505. } else {
  5506. // if the parent can be assigned then do so
  5507. parentSet(scope, parentValue = isolateScope[scopeName]);
  5508. }
  5509. }
  5510. return lastValue = parentValue;
  5511. }, null, parentGet.literal);
  5512. break;
  5513. case '&':
  5514. parentGet = $parse(attrs[attrName]);
  5515. isolateScope[scopeName] = function(locals) {
  5516. return parentGet(scope, locals);
  5517. };
  5518. break;
  5519. default:
  5520. throw $compileMinErr('iscp',
  5521. "Invalid isolate scope definition for directive '{0}'." +
  5522. " Definition: {... {1}: '{2}' ...}",
  5523. newIsolateScopeDirective.name, scopeName, definition);
  5524. }
  5525. });
  5526. }
  5527. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  5528. if (controllerDirectives) {
  5529. forEach(controllerDirectives, function(directive) {
  5530. var locals = {
  5531. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  5532. $element: $element,
  5533. $attrs: attrs,
  5534. $transclude: transcludeFn
  5535. }, controllerInstance;
  5536. controller = directive.controller;
  5537. if (controller == '@') {
  5538. controller = attrs[directive.name];
  5539. }
  5540. controllerInstance = $controller(controller, locals);
  5541. // For directives with element transclusion the element is a comment,
  5542. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  5543. // clean up (http://bugs.jquery.com/ticket/8335).
  5544. // Instead, we save the controllers for the element in a local hash and attach to .data
  5545. // later, once we have the actual element.
  5546. elementControllers[directive.name] = controllerInstance;
  5547. if (!hasElementTranscludeDirective) {
  5548. $element.data('$' + directive.name + 'Controller', controllerInstance);
  5549. }
  5550. if (directive.controllerAs) {
  5551. locals.$scope[directive.controllerAs] = controllerInstance;
  5552. }
  5553. });
  5554. }
  5555. // PRELINKING
  5556. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  5557. try {
  5558. linkFn = preLinkFns[i];
  5559. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  5560. linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
  5561. } catch (e) {
  5562. $exceptionHandler(e, startingTag($element));
  5563. }
  5564. }
  5565. // RECURSION
  5566. // We only pass the isolate scope, if the isolate directive has a template,
  5567. // otherwise the child elements do not belong to the isolate directive.
  5568. var scopeToChild = scope;
  5569. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  5570. scopeToChild = isolateScope;
  5571. }
  5572. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  5573. // POSTLINKING
  5574. for(i = postLinkFns.length - 1; i >= 0; i--) {
  5575. try {
  5576. linkFn = postLinkFns[i];
  5577. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  5578. linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
  5579. } catch (e) {
  5580. $exceptionHandler(e, startingTag($element));
  5581. }
  5582. }
  5583. // This is the function that is injected as `$transclude`.
  5584. function controllersBoundTransclude(scope, cloneAttachFn) {
  5585. var transcludeControllers;
  5586. // no scope passed
  5587. if (arguments.length < 2) {
  5588. cloneAttachFn = scope;
  5589. scope = undefined;
  5590. }
  5591. if (hasElementTranscludeDirective) {
  5592. transcludeControllers = elementControllers;
  5593. }
  5594. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  5595. }
  5596. }
  5597. }
  5598. function markDirectivesAsIsolate(directives) {
  5599. // mark all directives as needing isolate scope.
  5600. for (var j = 0, jj = directives.length; j < jj; j++) {
  5601. directives[j] = inherit(directives[j], {$$isolateScope: true});
  5602. }
  5603. }
  5604. /**
  5605. * looks up the directive and decorates it with exception handling and proper parameters. We
  5606. * call this the boundDirective.
  5607. *
  5608. * @param {string} name name of the directive to look up.
  5609. * @param {string} location The directive must be found in specific format.
  5610. * String containing any of theses characters:
  5611. *
  5612. * * `E`: element name
  5613. * * `A': attribute
  5614. * * `C`: class
  5615. * * `M`: comment
  5616. * @returns true if directive was added.
  5617. */
  5618. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  5619. endAttrName) {
  5620. if (name === ignoreDirective) return null;
  5621. var match = null;
  5622. if (hasDirectives.hasOwnProperty(name)) {
  5623. for(var directive, directives = $injector.get(name + Suffix),
  5624. i = 0, ii = directives.length; i<ii; i++) {
  5625. try {
  5626. directive = directives[i];
  5627. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  5628. directive.restrict.indexOf(location) != -1) {
  5629. if (startAttrName) {
  5630. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  5631. }
  5632. tDirectives.push(directive);
  5633. match = directive;
  5634. }
  5635. } catch(e) { $exceptionHandler(e); }
  5636. }
  5637. }
  5638. return match;
  5639. }
  5640. /**
  5641. * When the element is replaced with HTML template then the new attributes
  5642. * on the template need to be merged with the existing attributes in the DOM.
  5643. * The desired effect is to have both of the attributes present.
  5644. *
  5645. * @param {object} dst destination attributes (original DOM)
  5646. * @param {object} src source attributes (from the directive template)
  5647. */
  5648. function mergeTemplateAttributes(dst, src) {
  5649. var srcAttr = src.$attr,
  5650. dstAttr = dst.$attr,
  5651. $element = dst.$$element;
  5652. // reapply the old attributes to the new element
  5653. forEach(dst, function(value, key) {
  5654. if (key.charAt(0) != '$') {
  5655. if (src[key]) {
  5656. value += (key === 'style' ? ';' : ' ') + src[key];
  5657. }
  5658. dst.$set(key, value, true, srcAttr[key]);
  5659. }
  5660. });
  5661. // copy the new attributes on the old attrs object
  5662. forEach(src, function(value, key) {
  5663. if (key == 'class') {
  5664. safeAddClass($element, value);
  5665. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  5666. } else if (key == 'style') {
  5667. $element.attr('style', $element.attr('style') + ';' + value);
  5668. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  5669. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  5670. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  5671. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  5672. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  5673. dst[key] = value;
  5674. dstAttr[key] = srcAttr[key];
  5675. }
  5676. });
  5677. }
  5678. function compileTemplateUrl(directives, $compileNode, tAttrs,
  5679. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  5680. var linkQueue = [],
  5681. afterTemplateNodeLinkFn,
  5682. afterTemplateChildLinkFn,
  5683. beforeTemplateCompileNode = $compileNode[0],
  5684. origAsyncDirective = directives.shift(),
  5685. // The fact that we have to copy and patch the directive seems wrong!
  5686. derivedSyncDirective = extend({}, origAsyncDirective, {
  5687. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  5688. }),
  5689. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  5690. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  5691. : origAsyncDirective.templateUrl;
  5692. $compileNode.empty();
  5693. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  5694. success(function(content) {
  5695. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  5696. content = denormalizeTemplate(content);
  5697. if (origAsyncDirective.replace) {
  5698. $template = jqLite('<div>' + trim(content) + '</div>').contents();
  5699. compileNode = $template[0];
  5700. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5701. throw $compileMinErr('tplrt',
  5702. "Template for directive '{0}' must have exactly one root element. {1}",
  5703. origAsyncDirective.name, templateUrl);
  5704. }
  5705. tempTemplateAttrs = {$attr: {}};
  5706. replaceWith($rootElement, $compileNode, compileNode);
  5707. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  5708. if (isObject(origAsyncDirective.scope)) {
  5709. markDirectivesAsIsolate(templateDirectives);
  5710. }
  5711. directives = templateDirectives.concat(directives);
  5712. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  5713. } else {
  5714. compileNode = beforeTemplateCompileNode;
  5715. $compileNode.html(content);
  5716. }
  5717. directives.unshift(derivedSyncDirective);
  5718. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  5719. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  5720. previousCompileContext);
  5721. forEach($rootElement, function(node, i) {
  5722. if (node == compileNode) {
  5723. $rootElement[i] = $compileNode[0];
  5724. }
  5725. });
  5726. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  5727. while(linkQueue.length) {
  5728. var scope = linkQueue.shift(),
  5729. beforeTemplateLinkNode = linkQueue.shift(),
  5730. linkRootElement = linkQueue.shift(),
  5731. boundTranscludeFn = linkQueue.shift(),
  5732. linkNode = $compileNode[0];
  5733. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  5734. // it was cloned therefore we have to clone as well.
  5735. linkNode = jqLiteClone(compileNode);
  5736. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  5737. }
  5738. if (afterTemplateNodeLinkFn.transclude) {
  5739. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude);
  5740. } else {
  5741. childBoundTranscludeFn = boundTranscludeFn;
  5742. }
  5743. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  5744. childBoundTranscludeFn);
  5745. }
  5746. linkQueue = null;
  5747. }).
  5748. error(function(response, code, headers, config) {
  5749. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  5750. });
  5751. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  5752. if (linkQueue) {
  5753. linkQueue.push(scope);
  5754. linkQueue.push(node);
  5755. linkQueue.push(rootElement);
  5756. linkQueue.push(boundTranscludeFn);
  5757. } else {
  5758. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn);
  5759. }
  5760. };
  5761. }
  5762. /**
  5763. * Sorting function for bound directives.
  5764. */
  5765. function byPriority(a, b) {
  5766. var diff = b.priority - a.priority;
  5767. if (diff !== 0) return diff;
  5768. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  5769. return a.index - b.index;
  5770. }
  5771. function assertNoDuplicate(what, previousDirective, directive, element) {
  5772. if (previousDirective) {
  5773. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  5774. previousDirective.name, directive.name, what, startingTag(element));
  5775. }
  5776. }
  5777. function addTextInterpolateDirective(directives, text) {
  5778. var interpolateFn = $interpolate(text, true);
  5779. if (interpolateFn) {
  5780. directives.push({
  5781. priority: 0,
  5782. compile: valueFn(function textInterpolateLinkFn(scope, node) {
  5783. var parent = node.parent(),
  5784. bindings = parent.data('$binding') || [];
  5785. bindings.push(interpolateFn);
  5786. safeAddClass(parent.data('$binding', bindings), 'ng-binding');
  5787. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  5788. node[0].nodeValue = value;
  5789. });
  5790. })
  5791. });
  5792. }
  5793. }
  5794. function getTrustedContext(node, attrNormalizedName) {
  5795. if (attrNormalizedName == "srcdoc") {
  5796. return $sce.HTML;
  5797. }
  5798. var tag = nodeName_(node);
  5799. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  5800. if (attrNormalizedName == "xlinkHref" ||
  5801. (tag == "FORM" && attrNormalizedName == "action") ||
  5802. (tag != "IMG" && (attrNormalizedName == "src" ||
  5803. attrNormalizedName == "ngSrc"))) {
  5804. return $sce.RESOURCE_URL;
  5805. }
  5806. }
  5807. function addAttrInterpolateDirective(node, directives, value, name) {
  5808. var interpolateFn = $interpolate(value, true);
  5809. // no interpolation found -> ignore
  5810. if (!interpolateFn) return;
  5811. if (name === "multiple" && nodeName_(node) === "SELECT") {
  5812. throw $compileMinErr("selmulti",
  5813. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  5814. startingTag(node));
  5815. }
  5816. directives.push({
  5817. priority: 100,
  5818. compile: function() {
  5819. return {
  5820. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  5821. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  5822. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  5823. throw $compileMinErr('nodomevents',
  5824. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  5825. "ng- versions (such as ng-click instead of onclick) instead.");
  5826. }
  5827. // we need to interpolate again, in case the attribute value has been updated
  5828. // (e.g. by another directive's compile function)
  5829. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  5830. // if attribute was updated so that there is no interpolation going on we don't want to
  5831. // register any observers
  5832. if (!interpolateFn) return;
  5833. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  5834. // actual attr value
  5835. attr[name] = interpolateFn(scope);
  5836. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  5837. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  5838. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  5839. //special case for class attribute addition + removal
  5840. //so that class changes can tap into the animation
  5841. //hooks provided by the $animate service. Be sure to
  5842. //skip animations when the first digest occurs (when
  5843. //both the new and the old values are the same) since
  5844. //the CSS classes are the non-interpolated values
  5845. if(name === 'class' && newValue != oldValue) {
  5846. attr.$updateClass(newValue, oldValue);
  5847. } else {
  5848. attr.$set(name, newValue);
  5849. }
  5850. });
  5851. }
  5852. };
  5853. }
  5854. });
  5855. }
  5856. /**
  5857. * This is a special jqLite.replaceWith, which can replace items which
  5858. * have no parents, provided that the containing jqLite collection is provided.
  5859. *
  5860. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  5861. * in the root of the tree.
  5862. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  5863. * the shell, but replace its DOM node reference.
  5864. * @param {Node} newNode The new DOM node.
  5865. */
  5866. function replaceWith($rootElement, elementsToRemove, newNode) {
  5867. var firstElementToRemove = elementsToRemove[0],
  5868. removeCount = elementsToRemove.length,
  5869. parent = firstElementToRemove.parentNode,
  5870. i, ii;
  5871. if ($rootElement) {
  5872. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  5873. if ($rootElement[i] == firstElementToRemove) {
  5874. $rootElement[i++] = newNode;
  5875. for (var j = i, j2 = j + removeCount - 1,
  5876. jj = $rootElement.length;
  5877. j < jj; j++, j2++) {
  5878. if (j2 < jj) {
  5879. $rootElement[j] = $rootElement[j2];
  5880. } else {
  5881. delete $rootElement[j];
  5882. }
  5883. }
  5884. $rootElement.length -= removeCount - 1;
  5885. break;
  5886. }
  5887. }
  5888. }
  5889. if (parent) {
  5890. parent.replaceChild(newNode, firstElementToRemove);
  5891. }
  5892. var fragment = document.createDocumentFragment();
  5893. fragment.appendChild(firstElementToRemove);
  5894. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  5895. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  5896. var element = elementsToRemove[k];
  5897. jqLite(element).remove(); // must do this way to clean up expando
  5898. fragment.appendChild(element);
  5899. delete elementsToRemove[k];
  5900. }
  5901. elementsToRemove[0] = newNode;
  5902. elementsToRemove.length = 1;
  5903. }
  5904. function cloneAndAnnotateFn(fn, annotation) {
  5905. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  5906. }
  5907. }];
  5908. }
  5909. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  5910. /**
  5911. * Converts all accepted directives format into proper directive name.
  5912. * All of these will become 'myDirective':
  5913. * my:Directive
  5914. * my-directive
  5915. * x-my-directive
  5916. * data-my:directive
  5917. *
  5918. * Also there is special case for Moz prefix starting with upper case letter.
  5919. * @param name Name to normalize
  5920. */
  5921. function directiveNormalize(name) {
  5922. return camelCase(name.replace(PREFIX_REGEXP, ''));
  5923. }
  5924. /**
  5925. * @ngdoc object
  5926. * @name ng.$compile.directive.Attributes
  5927. *
  5928. * @description
  5929. * A shared object between directive compile / linking functions which contains normalized DOM
  5930. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  5931. * needed since all of these are treated as equivalent in Angular:
  5932. *
  5933. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  5934. */
  5935. /**
  5936. * @ngdoc property
  5937. * @name ng.$compile.directive.Attributes#$attr
  5938. * @propertyOf ng.$compile.directive.Attributes
  5939. * @returns {object} A map of DOM element attribute names to the normalized name. This is
  5940. * needed to do reverse lookup from normalized name back to actual name.
  5941. */
  5942. /**
  5943. * @ngdoc function
  5944. * @name ng.$compile.directive.Attributes#$set
  5945. * @methodOf ng.$compile.directive.Attributes
  5946. * @function
  5947. *
  5948. * @description
  5949. * Set DOM element attribute value.
  5950. *
  5951. *
  5952. * @param {string} name Normalized element attribute name of the property to modify. The name is
  5953. * revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  5954. * property to the original name.
  5955. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  5956. */
  5957. /**
  5958. * Closure compiler type information
  5959. */
  5960. function nodesetLinkingFn(
  5961. /* angular.Scope */ scope,
  5962. /* NodeList */ nodeList,
  5963. /* Element */ rootElement,
  5964. /* function(Function) */ boundTranscludeFn
  5965. ){}
  5966. function directiveLinkingFn(
  5967. /* nodesetLinkingFn */ nodesetLinkingFn,
  5968. /* angular.Scope */ scope,
  5969. /* Node */ node,
  5970. /* Element */ rootElement,
  5971. /* function(Function) */ boundTranscludeFn
  5972. ){}
  5973. function tokenDifference(str1, str2) {
  5974. var values = '',
  5975. tokens1 = str1.split(/\s+/),
  5976. tokens2 = str2.split(/\s+/);
  5977. outer:
  5978. for(var i = 0; i < tokens1.length; i++) {
  5979. var token = tokens1[i];
  5980. for(var j = 0; j < tokens2.length; j++) {
  5981. if(token == tokens2[j]) continue outer;
  5982. }
  5983. values += (values.length > 0 ? ' ' : '') + token;
  5984. }
  5985. return values;
  5986. }
  5987. /**
  5988. * @ngdoc object
  5989. * @name ng.$controllerProvider
  5990. * @description
  5991. * The {@link ng.$controller $controller service} is used by Angular to create new
  5992. * controllers.
  5993. *
  5994. * This provider allows controller registration via the
  5995. * {@link ng.$controllerProvider#methods_register register} method.
  5996. */
  5997. function $ControllerProvider() {
  5998. var controllers = {},
  5999. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  6000. /**
  6001. * @ngdoc function
  6002. * @name ng.$controllerProvider#register
  6003. * @methodOf ng.$controllerProvider
  6004. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  6005. * the names and the values are the constructors.
  6006. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  6007. * annotations in the array notation).
  6008. */
  6009. this.register = function(name, constructor) {
  6010. assertNotHasOwnProperty(name, 'controller');
  6011. if (isObject(name)) {
  6012. extend(controllers, name);
  6013. } else {
  6014. controllers[name] = constructor;
  6015. }
  6016. };
  6017. this.$get = ['$injector', '$window', function($injector, $window) {
  6018. /**
  6019. * @ngdoc function
  6020. * @name ng.$controller
  6021. * @requires $injector
  6022. *
  6023. * @param {Function|string} constructor If called with a function then it's considered to be the
  6024. * controller constructor function. Otherwise it's considered to be a string which is used
  6025. * to retrieve the controller constructor using the following steps:
  6026. *
  6027. * * check if a controller with given name is registered via `$controllerProvider`
  6028. * * check if evaluating the string on the current scope returns a constructor
  6029. * * check `window[constructor]` on the global `window` object
  6030. *
  6031. * @param {Object} locals Injection locals for Controller.
  6032. * @return {Object} Instance of given controller.
  6033. *
  6034. * @description
  6035. * `$controller` service is responsible for instantiating controllers.
  6036. *
  6037. * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
  6038. * a service, so that one can override this service with {@link https://gist.github.com/1649788
  6039. * BC version}.
  6040. */
  6041. return function(expression, locals) {
  6042. var instance, match, constructor, identifier;
  6043. if(isString(expression)) {
  6044. match = expression.match(CNTRL_REG),
  6045. constructor = match[1],
  6046. identifier = match[3];
  6047. expression = controllers.hasOwnProperty(constructor)
  6048. ? controllers[constructor]
  6049. : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
  6050. assertArgFn(expression, constructor, true);
  6051. }
  6052. instance = $injector.instantiate(expression, locals);
  6053. if (identifier) {
  6054. if (!(locals && typeof locals.$scope == 'object')) {
  6055. throw minErr('$controller')('noscp',
  6056. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  6057. constructor || expression.name, identifier);
  6058. }
  6059. locals.$scope[identifier] = instance;
  6060. }
  6061. return instance;
  6062. };
  6063. }];
  6064. }
  6065. /**
  6066. * @ngdoc object
  6067. * @name ng.$document
  6068. * @requires $window
  6069. *
  6070. * @description
  6071. * A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
  6072. * element.
  6073. */
  6074. function $DocumentProvider(){
  6075. this.$get = ['$window', function(window){
  6076. return jqLite(window.document);
  6077. }];
  6078. }
  6079. /**
  6080. * @ngdoc function
  6081. * @name ng.$exceptionHandler
  6082. * @requires $log
  6083. *
  6084. * @description
  6085. * Any uncaught exception in angular expressions is delegated to this service.
  6086. * The default implementation simply delegates to `$log.error` which logs it into
  6087. * the browser console.
  6088. *
  6089. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  6090. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  6091. *
  6092. * ## Example:
  6093. *
  6094. * <pre>
  6095. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  6096. * return function (exception, cause) {
  6097. * exception.message += ' (caused by "' + cause + '")';
  6098. * throw exception;
  6099. * };
  6100. * });
  6101. * </pre>
  6102. *
  6103. * This example will override the normal action of `$exceptionHandler`, to make angular
  6104. * exceptions fail hard when they happen, instead of just logging to the console.
  6105. *
  6106. * @param {Error} exception Exception associated with the error.
  6107. * @param {string=} cause optional information about the context in which
  6108. * the error was thrown.
  6109. *
  6110. */
  6111. function $ExceptionHandlerProvider() {
  6112. this.$get = ['$log', function($log) {
  6113. return function(exception, cause) {
  6114. $log.error.apply($log, arguments);
  6115. };
  6116. }];
  6117. }
  6118. /**
  6119. * Parse headers into key value object
  6120. *
  6121. * @param {string} headers Raw headers as a string
  6122. * @returns {Object} Parsed headers as key value object
  6123. */
  6124. function parseHeaders(headers) {
  6125. var parsed = {}, key, val, i;
  6126. if (!headers) return parsed;
  6127. forEach(headers.split('\n'), function(line) {
  6128. i = line.indexOf(':');
  6129. key = lowercase(trim(line.substr(0, i)));
  6130. val = trim(line.substr(i + 1));
  6131. if (key) {
  6132. if (parsed[key]) {
  6133. parsed[key] += ', ' + val;
  6134. } else {
  6135. parsed[key] = val;
  6136. }
  6137. }
  6138. });
  6139. return parsed;
  6140. }
  6141. /**
  6142. * Returns a function that provides access to parsed headers.
  6143. *
  6144. * Headers are lazy parsed when first requested.
  6145. * @see parseHeaders
  6146. *
  6147. * @param {(string|Object)} headers Headers to provide access to.
  6148. * @returns {function(string=)} Returns a getter function which if called with:
  6149. *
  6150. * - if called with single an argument returns a single header value or null
  6151. * - if called with no arguments returns an object containing all headers.
  6152. */
  6153. function headersGetter(headers) {
  6154. var headersObj = isObject(headers) ? headers : undefined;
  6155. return function(name) {
  6156. if (!headersObj) headersObj = parseHeaders(headers);
  6157. if (name) {
  6158. return headersObj[lowercase(name)] || null;
  6159. }
  6160. return headersObj;
  6161. };
  6162. }
  6163. /**
  6164. * Chain all given functions
  6165. *
  6166. * This function is used for both request and response transforming
  6167. *
  6168. * @param {*} data Data to transform.
  6169. * @param {function(string=)} headers Http headers getter fn.
  6170. * @param {(function|Array.<function>)} fns Function or an array of functions.
  6171. * @returns {*} Transformed data.
  6172. */
  6173. function transformData(data, headers, fns) {
  6174. if (isFunction(fns))
  6175. return fns(data, headers);
  6176. forEach(fns, function(fn) {
  6177. data = fn(data, headers);
  6178. });
  6179. return data;
  6180. }
  6181. function isSuccess(status) {
  6182. return 200 <= status && status < 300;
  6183. }
  6184. function $HttpProvider() {
  6185. var JSON_START = /^\s*(\[|\{[^\{])/,
  6186. JSON_END = /[\}\]]\s*$/,
  6187. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  6188. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
  6189. var defaults = this.defaults = {
  6190. // transform incoming response data
  6191. transformResponse: [function(data) {
  6192. if (isString(data)) {
  6193. // strip json vulnerability protection prefix
  6194. data = data.replace(PROTECTION_PREFIX, '');
  6195. if (JSON_START.test(data) && JSON_END.test(data))
  6196. data = fromJson(data);
  6197. }
  6198. return data;
  6199. }],
  6200. // transform outgoing request data
  6201. transformRequest: [function(d) {
  6202. return isObject(d) && !isFile(d) ? toJson(d) : d;
  6203. }],
  6204. // default headers
  6205. headers: {
  6206. common: {
  6207. 'Accept': 'application/json, text/plain, */*'
  6208. },
  6209. post: CONTENT_TYPE_APPLICATION_JSON,
  6210. put: CONTENT_TYPE_APPLICATION_JSON,
  6211. patch: CONTENT_TYPE_APPLICATION_JSON
  6212. },
  6213. xsrfCookieName: 'XSRF-TOKEN',
  6214. xsrfHeaderName: 'X-XSRF-TOKEN'
  6215. };
  6216. /**
  6217. * Are ordered by request, i.e. they are applied in the same order as the
  6218. * array, on request, but reverse order, on response.
  6219. */
  6220. var interceptorFactories = this.interceptors = [];
  6221. /**
  6222. * For historical reasons, response interceptors are ordered by the order in which
  6223. * they are applied to the response. (This is the opposite of interceptorFactories)
  6224. */
  6225. var responseInterceptorFactories = this.responseInterceptors = [];
  6226. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  6227. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  6228. var defaultCache = $cacheFactory('$http');
  6229. /**
  6230. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  6231. * The reversal is needed so that we can build up the interception chain around the
  6232. * server request.
  6233. */
  6234. var reversedInterceptors = [];
  6235. forEach(interceptorFactories, function(interceptorFactory) {
  6236. reversedInterceptors.unshift(isString(interceptorFactory)
  6237. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  6238. });
  6239. forEach(responseInterceptorFactories, function(interceptorFactory, index) {
  6240. var responseFn = isString(interceptorFactory)
  6241. ? $injector.get(interceptorFactory)
  6242. : $injector.invoke(interceptorFactory);
  6243. /**
  6244. * Response interceptors go before "around" interceptors (no real reason, just
  6245. * had to pick one.) But they are already reversed, so we can't use unshift, hence
  6246. * the splice.
  6247. */
  6248. reversedInterceptors.splice(index, 0, {
  6249. response: function(response) {
  6250. return responseFn($q.when(response));
  6251. },
  6252. responseError: function(response) {
  6253. return responseFn($q.reject(response));
  6254. }
  6255. });
  6256. });
  6257. /**
  6258. * @ngdoc function
  6259. * @name ng.$http
  6260. * @requires $httpBackend
  6261. * @requires $browser
  6262. * @requires $cacheFactory
  6263. * @requires $rootScope
  6264. * @requires $q
  6265. * @requires $injector
  6266. *
  6267. * @description
  6268. * The `$http` service is a core Angular service that facilitates communication with the remote
  6269. * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest
  6270. * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
  6271. *
  6272. * For unit testing applications that use `$http` service, see
  6273. * {@link ngMock.$httpBackend $httpBackend mock}.
  6274. *
  6275. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  6276. * $resource} service.
  6277. *
  6278. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  6279. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  6280. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  6281. *
  6282. *
  6283. * # General usage
  6284. * The `$http` service is a function which takes a single argument — a configuration object —
  6285. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  6286. * with two $http specific methods: `success` and `error`.
  6287. *
  6288. * <pre>
  6289. * $http({method: 'GET', url: '/someUrl'}).
  6290. * success(function(data, status, headers, config) {
  6291. * // this callback will be called asynchronously
  6292. * // when the response is available
  6293. * }).
  6294. * error(function(data, status, headers, config) {
  6295. * // called asynchronously if an error occurs
  6296. * // or server returns response with an error status.
  6297. * });
  6298. * </pre>
  6299. *
  6300. * Since the returned value of calling the $http function is a `promise`, you can also use
  6301. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  6302. * an object representing the response. See the API signature and type info below for more
  6303. * details.
  6304. *
  6305. * A response status code between 200 and 299 is considered a success status and
  6306. * will result in the success callback being called. Note that if the response is a redirect,
  6307. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  6308. * called for such responses.
  6309. *
  6310. * # Calling $http from outside AngularJS
  6311. * The `$http` service will not actually send the request until the next `$digest()` is
  6312. * executed. Normally this is not an issue, since almost all the time your call to `$http` will
  6313. * be from within a `$apply()` block.
  6314. * If you are calling `$http` from outside Angular, then you should wrap it in a call to
  6315. * `$apply` to cause a $digest to occur and also to handle errors in the block correctly.
  6316. *
  6317. * ```
  6318. * $scope.$apply(function() {
  6319. * $http(...);
  6320. * });
  6321. * ```
  6322. *
  6323. * # Writing Unit Tests that use $http
  6324. * When unit testing you are mostly responsible for scheduling the `$digest` cycle. If you do
  6325. * not trigger a `$digest` before calling `$httpBackend.flush()` then the request will not have
  6326. * been made and `$httpBackend.expect(...)` expectations will fail. The solution is to run the
  6327. * code that calls the `$http()` method inside a $apply block as explained in the previous
  6328. * section.
  6329. *
  6330. * ```
  6331. * $httpBackend.expectGET(...);
  6332. * $scope.$apply(function() {
  6333. * $http.get(...);
  6334. * });
  6335. * $httpBackend.flush();
  6336. * ```
  6337. *
  6338. * # Shortcut methods
  6339. *
  6340. * Since all invocations of the $http service require passing in an HTTP method and URL, and
  6341. * POST/PUT requests require request data to be provided as well, shortcut methods
  6342. * were created:
  6343. *
  6344. * <pre>
  6345. * $http.get('/someUrl').success(successCallback);
  6346. * $http.post('/someUrl', data).success(successCallback);
  6347. * </pre>
  6348. *
  6349. * Complete list of shortcut methods:
  6350. *
  6351. * - {@link ng.$http#methods_get $http.get}
  6352. * - {@link ng.$http#methods_head $http.head}
  6353. * - {@link ng.$http#methods_post $http.post}
  6354. * - {@link ng.$http#methods_put $http.put}
  6355. * - {@link ng.$http#methods_delete $http.delete}
  6356. * - {@link ng.$http#methods_jsonp $http.jsonp}
  6357. *
  6358. *
  6359. * # Setting HTTP Headers
  6360. *
  6361. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  6362. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  6363. * object, which currently contains this default configuration:
  6364. *
  6365. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  6366. * - `Accept: application/json, text/plain, * / *`
  6367. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  6368. * - `Content-Type: application/json`
  6369. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  6370. * - `Content-Type: application/json`
  6371. *
  6372. * To add or overwrite these defaults, simply add or remove a property from these configuration
  6373. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  6374. * with the lowercased HTTP method name as the key, e.g.
  6375. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  6376. *
  6377. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  6378. * fashion. In addition, you can supply a `headers` property in the config object passed when
  6379. * calling `$http(config)`, which overrides the defaults without changing them globally.
  6380. *
  6381. *
  6382. * # Transforming Requests and Responses
  6383. *
  6384. * Both requests and responses can be transformed using transform functions. By default, Angular
  6385. * applies these transformations:
  6386. *
  6387. * Request transformations:
  6388. *
  6389. * - If the `data` property of the request configuration object contains an object, serialize it
  6390. * into JSON format.
  6391. *
  6392. * Response transformations:
  6393. *
  6394. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  6395. * - If JSON response is detected, deserialize it using a JSON parser.
  6396. *
  6397. * To globally augment or override the default transforms, modify the
  6398. * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
  6399. * properties. These properties are by default an array of transform functions, which allows you
  6400. * to `push` or `unshift` a new transformation function into the transformation chain. You can
  6401. * also decide to completely override any default transformations by assigning your
  6402. * transformation functions to these properties directly without the array wrapper.
  6403. *
  6404. * Similarly, to locally override the request/response transforms, augment the
  6405. * `transformRequest` and/or `transformResponse` properties of the configuration object passed
  6406. * into `$http`.
  6407. *
  6408. *
  6409. * # Caching
  6410. *
  6411. * To enable caching, set the request configuration `cache` property to `true` (to use default
  6412. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  6413. * When the cache is enabled, `$http` stores the response from the server in the specified
  6414. * cache. The next time the same request is made, the response is served from the cache without
  6415. * sending a request to the server.
  6416. *
  6417. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  6418. * the same way that real requests are.
  6419. *
  6420. * If there are multiple GET requests for the same URL that should be cached using the same
  6421. * cache, but the cache is not populated yet, only one request to the server will be made and
  6422. * the remaining requests will be fulfilled using the response from the first request.
  6423. *
  6424. * You can change the default cache to a new object (built with
  6425. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  6426. * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
  6427. * their `cache` property to `true` will now use this cache object.
  6428. *
  6429. * If you set the default cache to `false` then only requests that specify their own custom
  6430. * cache object will be cached.
  6431. *
  6432. * # Interceptors
  6433. *
  6434. * Before you start creating interceptors, be sure to understand the
  6435. * {@link ng.$q $q and deferred/promise APIs}.
  6436. *
  6437. * For purposes of global error handling, authentication, or any kind of synchronous or
  6438. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  6439. * able to intercept requests before they are handed to the server and
  6440. * responses before they are handed over to the application code that
  6441. * initiated these requests. The interceptors leverage the {@link ng.$q
  6442. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  6443. *
  6444. * The interceptors are service factories that are registered with the `$httpProvider` by
  6445. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  6446. * injected with dependencies (if specified) and returns the interceptor.
  6447. *
  6448. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  6449. *
  6450. * * `request`: interceptors get called with http `config` object. The function is free to
  6451. * modify the `config` or create a new one. The function needs to return the `config`
  6452. * directly or as a promise.
  6453. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  6454. * resolved with a rejection.
  6455. * * `response`: interceptors get called with http `response` object. The function is free to
  6456. * modify the `response` or create a new one. The function needs to return the `response`
  6457. * directly or as a promise.
  6458. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  6459. * resolved with a rejection.
  6460. *
  6461. *
  6462. * <pre>
  6463. * // register the interceptor as a service
  6464. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6465. * return {
  6466. * // optional method
  6467. * 'request': function(config) {
  6468. * // do something on success
  6469. * return config || $q.when(config);
  6470. * },
  6471. *
  6472. * // optional method
  6473. * 'requestError': function(rejection) {
  6474. * // do something on error
  6475. * if (canRecover(rejection)) {
  6476. * return responseOrNewPromise
  6477. * }
  6478. * return $q.reject(rejection);
  6479. * },
  6480. *
  6481. *
  6482. *
  6483. * // optional method
  6484. * 'response': function(response) {
  6485. * // do something on success
  6486. * return response || $q.when(response);
  6487. * },
  6488. *
  6489. * // optional method
  6490. * 'responseError': function(rejection) {
  6491. * // do something on error
  6492. * if (canRecover(rejection)) {
  6493. * return responseOrNewPromise
  6494. * }
  6495. * return $q.reject(rejection);
  6496. * };
  6497. * }
  6498. * });
  6499. *
  6500. * $httpProvider.interceptors.push('myHttpInterceptor');
  6501. *
  6502. *
  6503. * // register the interceptor via an anonymous factory
  6504. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  6505. * return {
  6506. * 'request': function(config) {
  6507. * // same as above
  6508. * },
  6509. * 'response': function(response) {
  6510. * // same as above
  6511. * }
  6512. * };
  6513. * });
  6514. * </pre>
  6515. *
  6516. * # Response interceptors (DEPRECATED)
  6517. *
  6518. * Before you start creating interceptors, be sure to understand the
  6519. * {@link ng.$q $q and deferred/promise APIs}.
  6520. *
  6521. * For purposes of global error handling, authentication or any kind of synchronous or
  6522. * asynchronous preprocessing of received responses, it is desirable to be able to intercept
  6523. * responses for http requests before they are handed over to the application code that
  6524. * initiated these requests. The response interceptors leverage the {@link ng.$q
  6525. * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
  6526. *
  6527. * The interceptors are service factories that are registered with the $httpProvider by
  6528. * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
  6529. * injected with dependencies (if specified) and returns the interceptor — a function that
  6530. * takes a {@link ng.$q promise} and returns the original or a new promise.
  6531. *
  6532. * <pre>
  6533. * // register the interceptor as a service
  6534. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6535. * return function(promise) {
  6536. * return promise.then(function(response) {
  6537. * // do something on success
  6538. * return response;
  6539. * }, function(response) {
  6540. * // do something on error
  6541. * if (canRecover(response)) {
  6542. * return responseOrNewPromise
  6543. * }
  6544. * return $q.reject(response);
  6545. * });
  6546. * }
  6547. * });
  6548. *
  6549. * $httpProvider.responseInterceptors.push('myHttpInterceptor');
  6550. *
  6551. *
  6552. * // register the interceptor via an anonymous factory
  6553. * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
  6554. * return function(promise) {
  6555. * // same as above
  6556. * }
  6557. * });
  6558. * </pre>
  6559. *
  6560. *
  6561. * # Security Considerations
  6562. *
  6563. * When designing web applications, consider security threats from:
  6564. *
  6565. * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
  6566. * JSON vulnerability}
  6567. * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
  6568. *
  6569. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  6570. * pre-configured with strategies that address these issues, but for this to work backend server
  6571. * cooperation is required.
  6572. *
  6573. * ## JSON Vulnerability Protection
  6574. *
  6575. * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
  6576. * JSON vulnerability} allows third party website to turn your JSON resource URL into
  6577. * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To
  6578. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  6579. * Angular will automatically strip the prefix before processing it as JSON.
  6580. *
  6581. * For example if your server needs to return:
  6582. * <pre>
  6583. * ['one','two']
  6584. * </pre>
  6585. *
  6586. * which is vulnerable to attack, your server can return:
  6587. * <pre>
  6588. * )]}',
  6589. * ['one','two']
  6590. * </pre>
  6591. *
  6592. * Angular will strip the prefix, before processing the JSON.
  6593. *
  6594. *
  6595. * ## Cross Site Request Forgery (XSRF) Protection
  6596. *
  6597. * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
  6598. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  6599. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  6600. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  6601. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  6602. * the XHR came from JavaScript running on your domain. The header will not be set for
  6603. * cross-domain requests.
  6604. *
  6605. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  6606. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  6607. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  6608. * that only JavaScript running on your domain could have sent the request. The token must be
  6609. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  6610. * making up its own tokens). We recommend that the token is a digest of your site's
  6611. * authentication cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt}
  6612. * for added security.
  6613. *
  6614. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  6615. * properties of either $httpProvider.defaults, or the per-request config object.
  6616. *
  6617. *
  6618. * @param {object} config Object describing the request to be made and how it should be
  6619. * processed. The object has following properties:
  6620. *
  6621. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  6622. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  6623. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  6624. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  6625. * JSONified.
  6626. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  6627. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  6628. * HTTP headers to send to the server. If the return value of a function is null, the
  6629. * header will not be sent.
  6630. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  6631. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  6632. * - **transformRequest** –
  6633. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  6634. * transform function or an array of such functions. The transform function takes the http
  6635. * request body and headers and returns its transformed (typically serialized) version.
  6636. * - **transformResponse** –
  6637. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  6638. * transform function or an array of such functions. The transform function takes the http
  6639. * response body and headers and returns its transformed (typically deserialized) version.
  6640. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  6641. * GET request, otherwise if a cache instance built with
  6642. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  6643. * caching.
  6644. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  6645. * that should abort the request when resolved.
  6646. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
  6647. * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
  6648. * requests with credentials} for more information.
  6649. * - **responseType** - `{string}` - see {@link
  6650. * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}.
  6651. *
  6652. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  6653. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  6654. * method takes two arguments a success and an error callback which will be called with a
  6655. * response object. The `success` and `error` methods take a single argument - a function that
  6656. * will be called when the request succeeds or fails respectively. The arguments passed into
  6657. * these functions are destructured representation of the response object passed into the
  6658. * `then` method. The response object has these properties:
  6659. *
  6660. * - **data** – `{string|Object}` – The response body transformed with the transform
  6661. * functions.
  6662. * - **status** – `{number}` – HTTP status code of the response.
  6663. * - **headers** – `{function([headerName])}` – Header getter function.
  6664. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  6665. *
  6666. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  6667. * requests. This is primarily meant to be used for debugging purposes.
  6668. *
  6669. *
  6670. * @example
  6671. <example>
  6672. <file name="index.html">
  6673. <div ng-controller="FetchCtrl">
  6674. <select ng-model="method">
  6675. <option>GET</option>
  6676. <option>JSONP</option>
  6677. </select>
  6678. <input type="text" ng-model="url" size="80"/>
  6679. <button ng-click="fetch()">fetch</button><br>
  6680. <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  6681. <button
  6682. ng-click="updateModel('JSONP',
  6683. 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  6684. Sample JSONP
  6685. </button>
  6686. <button
  6687. ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  6688. Invalid JSONP
  6689. </button>
  6690. <pre>http status code: {{status}}</pre>
  6691. <pre>http response data: {{data}}</pre>
  6692. </div>
  6693. </file>
  6694. <file name="script.js">
  6695. function FetchCtrl($scope, $http, $templateCache) {
  6696. $scope.method = 'GET';
  6697. $scope.url = 'http-hello.html';
  6698. $scope.fetch = function() {
  6699. $scope.code = null;
  6700. $scope.response = null;
  6701. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  6702. success(function(data, status) {
  6703. $scope.status = status;
  6704. $scope.data = data;
  6705. }).
  6706. error(function(data, status) {
  6707. $scope.data = data || "Request failed";
  6708. $scope.status = status;
  6709. });
  6710. };
  6711. $scope.updateModel = function(method, url) {
  6712. $scope.method = method;
  6713. $scope.url = url;
  6714. };
  6715. }
  6716. </file>
  6717. <file name="http-hello.html">
  6718. Hello, $http!
  6719. </file>
  6720. <file name="scenario.js">
  6721. it('should make an xhr GET request', function() {
  6722. element(':button:contains("Sample GET")').click();
  6723. element(':button:contains("fetch")').click();
  6724. expect(binding('status')).toBe('200');
  6725. expect(binding('data')).toMatch(/Hello, \$http!/);
  6726. });
  6727. it('should make a JSONP request to angularjs.org', function() {
  6728. element(':button:contains("Sample JSONP")').click();
  6729. element(':button:contains("fetch")').click();
  6730. expect(binding('status')).toBe('200');
  6731. expect(binding('data')).toMatch(/Super Hero!/);
  6732. });
  6733. it('should make JSONP request to invalid URL and invoke the error handler',
  6734. function() {
  6735. element(':button:contains("Invalid JSONP")').click();
  6736. element(':button:contains("fetch")').click();
  6737. expect(binding('status')).toBe('0');
  6738. expect(binding('data')).toBe('Request failed');
  6739. });
  6740. </file>
  6741. </example>
  6742. */
  6743. function $http(requestConfig) {
  6744. var config = {
  6745. transformRequest: defaults.transformRequest,
  6746. transformResponse: defaults.transformResponse
  6747. };
  6748. var headers = mergeHeaders(requestConfig);
  6749. extend(config, requestConfig);
  6750. config.headers = headers;
  6751. config.method = uppercase(config.method);
  6752. var xsrfValue = urlIsSameOrigin(config.url)
  6753. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  6754. : undefined;
  6755. if (xsrfValue) {
  6756. headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  6757. }
  6758. var serverRequest = function(config) {
  6759. headers = config.headers;
  6760. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  6761. // strip content-type if data is undefined
  6762. if (isUndefined(config.data)) {
  6763. forEach(headers, function(value, header) {
  6764. if (lowercase(header) === 'content-type') {
  6765. delete headers[header];
  6766. }
  6767. });
  6768. }
  6769. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  6770. config.withCredentials = defaults.withCredentials;
  6771. }
  6772. // send request
  6773. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  6774. };
  6775. var chain = [serverRequest, undefined];
  6776. var promise = $q.when(config);
  6777. // apply interceptors
  6778. forEach(reversedInterceptors, function(interceptor) {
  6779. if (interceptor.request || interceptor.requestError) {
  6780. chain.unshift(interceptor.request, interceptor.requestError);
  6781. }
  6782. if (interceptor.response || interceptor.responseError) {
  6783. chain.push(interceptor.response, interceptor.responseError);
  6784. }
  6785. });
  6786. while(chain.length) {
  6787. var thenFn = chain.shift();
  6788. var rejectFn = chain.shift();
  6789. promise = promise.then(thenFn, rejectFn);
  6790. }
  6791. promise.success = function(fn) {
  6792. promise.then(function(response) {
  6793. fn(response.data, response.status, response.headers, config);
  6794. });
  6795. return promise;
  6796. };
  6797. promise.error = function(fn) {
  6798. promise.then(null, function(response) {
  6799. fn(response.data, response.status, response.headers, config);
  6800. });
  6801. return promise;
  6802. };
  6803. return promise;
  6804. function transformResponse(response) {
  6805. // make a copy since the response must be cacheable
  6806. var resp = extend({}, response, {
  6807. data: transformData(response.data, response.headers, config.transformResponse)
  6808. });
  6809. return (isSuccess(response.status))
  6810. ? resp
  6811. : $q.reject(resp);
  6812. }
  6813. function mergeHeaders(config) {
  6814. var defHeaders = defaults.headers,
  6815. reqHeaders = extend({}, config.headers),
  6816. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  6817. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  6818. // execute if header value is function
  6819. execHeaders(defHeaders);
  6820. execHeaders(reqHeaders);
  6821. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  6822. defaultHeadersIteration:
  6823. for (defHeaderName in defHeaders) {
  6824. lowercaseDefHeaderName = lowercase(defHeaderName);
  6825. for (reqHeaderName in reqHeaders) {
  6826. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  6827. continue defaultHeadersIteration;
  6828. }
  6829. }
  6830. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  6831. }
  6832. return reqHeaders;
  6833. function execHeaders(headers) {
  6834. var headerContent;
  6835. forEach(headers, function(headerFn, header) {
  6836. if (isFunction(headerFn)) {
  6837. headerContent = headerFn();
  6838. if (headerContent != null) {
  6839. headers[header] = headerContent;
  6840. } else {
  6841. delete headers[header];
  6842. }
  6843. }
  6844. });
  6845. }
  6846. }
  6847. }
  6848. $http.pendingRequests = [];
  6849. /**
  6850. * @ngdoc method
  6851. * @name ng.$http#get
  6852. * @methodOf ng.$http
  6853. *
  6854. * @description
  6855. * Shortcut method to perform `GET` request.
  6856. *
  6857. * @param {string} url Relative or absolute URL specifying the destination of the request
  6858. * @param {Object=} config Optional configuration object
  6859. * @returns {HttpPromise} Future object
  6860. */
  6861. /**
  6862. * @ngdoc method
  6863. * @name ng.$http#delete
  6864. * @methodOf ng.$http
  6865. *
  6866. * @description
  6867. * Shortcut method to perform `DELETE` request.
  6868. *
  6869. * @param {string} url Relative or absolute URL specifying the destination of the request
  6870. * @param {Object=} config Optional configuration object
  6871. * @returns {HttpPromise} Future object
  6872. */
  6873. /**
  6874. * @ngdoc method
  6875. * @name ng.$http#head
  6876. * @methodOf ng.$http
  6877. *
  6878. * @description
  6879. * Shortcut method to perform `HEAD` request.
  6880. *
  6881. * @param {string} url Relative or absolute URL specifying the destination of the request
  6882. * @param {Object=} config Optional configuration object
  6883. * @returns {HttpPromise} Future object
  6884. */
  6885. /**
  6886. * @ngdoc method
  6887. * @name ng.$http#jsonp
  6888. * @methodOf ng.$http
  6889. *
  6890. * @description
  6891. * Shortcut method to perform `JSONP` request.
  6892. *
  6893. * @param {string} url Relative or absolute URL specifying the destination of the request.
  6894. * Should contain `JSON_CALLBACK` string.
  6895. * @param {Object=} config Optional configuration object
  6896. * @returns {HttpPromise} Future object
  6897. */
  6898. createShortMethods('get', 'delete', 'head', 'jsonp');
  6899. /**
  6900. * @ngdoc method
  6901. * @name ng.$http#post
  6902. * @methodOf ng.$http
  6903. *
  6904. * @description
  6905. * Shortcut method to perform `POST` request.
  6906. *
  6907. * @param {string} url Relative or absolute URL specifying the destination of the request
  6908. * @param {*} data Request content
  6909. * @param {Object=} config Optional configuration object
  6910. * @returns {HttpPromise} Future object
  6911. */
  6912. /**
  6913. * @ngdoc method
  6914. * @name ng.$http#put
  6915. * @methodOf ng.$http
  6916. *
  6917. * @description
  6918. * Shortcut method to perform `PUT` request.
  6919. *
  6920. * @param {string} url Relative or absolute URL specifying the destination of the request
  6921. * @param {*} data Request content
  6922. * @param {Object=} config Optional configuration object
  6923. * @returns {HttpPromise} Future object
  6924. */
  6925. createShortMethodsWithData('post', 'put');
  6926. /**
  6927. * @ngdoc property
  6928. * @name ng.$http#defaults
  6929. * @propertyOf ng.$http
  6930. *
  6931. * @description
  6932. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  6933. * default headers, withCredentials as well as request and response transformations.
  6934. *
  6935. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  6936. */
  6937. $http.defaults = defaults;
  6938. return $http;
  6939. function createShortMethods(names) {
  6940. forEach(arguments, function(name) {
  6941. $http[name] = function(url, config) {
  6942. return $http(extend(config || {}, {
  6943. method: name,
  6944. url: url
  6945. }));
  6946. };
  6947. });
  6948. }
  6949. function createShortMethodsWithData(name) {
  6950. forEach(arguments, function(name) {
  6951. $http[name] = function(url, data, config) {
  6952. return $http(extend(config || {}, {
  6953. method: name,
  6954. url: url,
  6955. data: data
  6956. }));
  6957. };
  6958. });
  6959. }
  6960. /**
  6961. * Makes the request.
  6962. *
  6963. * !!! ACCESSES CLOSURE VARS:
  6964. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  6965. */
  6966. function sendReq(config, reqData, reqHeaders) {
  6967. var deferred = $q.defer(),
  6968. promise = deferred.promise,
  6969. cache,
  6970. cachedResp,
  6971. url = buildUrl(config.url, config.params);
  6972. $http.pendingRequests.push(config);
  6973. promise.then(removePendingReq, removePendingReq);
  6974. if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
  6975. cache = isObject(config.cache) ? config.cache
  6976. : isObject(defaults.cache) ? defaults.cache
  6977. : defaultCache;
  6978. }
  6979. if (cache) {
  6980. cachedResp = cache.get(url);
  6981. if (isDefined(cachedResp)) {
  6982. if (cachedResp.then) {
  6983. // cached request has already been sent, but there is no response yet
  6984. cachedResp.then(removePendingReq, removePendingReq);
  6985. return cachedResp;
  6986. } else {
  6987. // serving from cache
  6988. if (isArray(cachedResp)) {
  6989. resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
  6990. } else {
  6991. resolvePromise(cachedResp, 200, {});
  6992. }
  6993. }
  6994. } else {
  6995. // put the promise for the non-transformed response into cache as a placeholder
  6996. cache.put(url, promise);
  6997. }
  6998. }
  6999. // if we won't have the response in cache, send the request to the backend
  7000. if (isUndefined(cachedResp)) {
  7001. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  7002. config.withCredentials, config.responseType);
  7003. }
  7004. return promise;
  7005. /**
  7006. * Callback registered to $httpBackend():
  7007. * - caches the response if desired
  7008. * - resolves the raw $http promise
  7009. * - calls $apply
  7010. */
  7011. function done(status, response, headersString) {
  7012. if (cache) {
  7013. if (isSuccess(status)) {
  7014. cache.put(url, [status, response, parseHeaders(headersString)]);
  7015. } else {
  7016. // remove promise from the cache
  7017. cache.remove(url);
  7018. }
  7019. }
  7020. resolvePromise(response, status, headersString);
  7021. if (!$rootScope.$$phase) $rootScope.$apply();
  7022. }
  7023. /**
  7024. * Resolves the raw $http promise.
  7025. */
  7026. function resolvePromise(response, status, headers) {
  7027. // normalize internal statuses to 0
  7028. status = Math.max(status, 0);
  7029. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  7030. data: response,
  7031. status: status,
  7032. headers: headersGetter(headers),
  7033. config: config
  7034. });
  7035. }
  7036. function removePendingReq() {
  7037. var idx = indexOf($http.pendingRequests, config);
  7038. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  7039. }
  7040. }
  7041. function buildUrl(url, params) {
  7042. if (!params) return url;
  7043. var parts = [];
  7044. forEachSorted(params, function(value, key) {
  7045. if (value === null || isUndefined(value)) return;
  7046. if (!isArray(value)) value = [value];
  7047. forEach(value, function(v) {
  7048. if (isObject(v)) {
  7049. v = toJson(v);
  7050. }
  7051. parts.push(encodeUriQuery(key) + '=' +
  7052. encodeUriQuery(v));
  7053. });
  7054. });
  7055. return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  7056. }
  7057. }];
  7058. }
  7059. var XHR = window.XMLHttpRequest || function() {
  7060. /* global ActiveXObject */
  7061. try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
  7062. try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
  7063. try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
  7064. throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
  7065. };
  7066. /**
  7067. * @ngdoc object
  7068. * @name ng.$httpBackend
  7069. * @requires $browser
  7070. * @requires $window
  7071. * @requires $document
  7072. *
  7073. * @description
  7074. * HTTP backend used by the {@link ng.$http service} that delegates to
  7075. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  7076. *
  7077. * You should never need to use this service directly, instead use the higher-level abstractions:
  7078. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  7079. *
  7080. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  7081. * $httpBackend} which can be trained with responses.
  7082. */
  7083. function $HttpBackendProvider() {
  7084. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  7085. return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks, $document[0]);
  7086. }];
  7087. }
  7088. function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument) {
  7089. var ABORTED = -1;
  7090. // TODO(vojta): fix the signature
  7091. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  7092. var status;
  7093. $browser.$$incOutstandingRequestCount();
  7094. url = url || $browser.url();
  7095. if (lowercase(method) == 'jsonp') {
  7096. var callbackId = '_' + (callbacks.counter++).toString(36);
  7097. callbacks[callbackId] = function(data) {
  7098. callbacks[callbackId].data = data;
  7099. };
  7100. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  7101. function() {
  7102. if (callbacks[callbackId].data) {
  7103. completeRequest(callback, 200, callbacks[callbackId].data);
  7104. } else {
  7105. completeRequest(callback, status || -2);
  7106. }
  7107. delete callbacks[callbackId];
  7108. });
  7109. } else {
  7110. var xhr = new XHR();
  7111. xhr.open(method, url, true);
  7112. forEach(headers, function(value, key) {
  7113. if (isDefined(value)) {
  7114. xhr.setRequestHeader(key, value);
  7115. }
  7116. });
  7117. // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
  7118. // response is in the cache. the promise api will ensure that to the app code the api is
  7119. // always async
  7120. xhr.onreadystatechange = function() {
  7121. if (xhr.readyState == 4) {
  7122. var responseHeaders = null,
  7123. response = null;
  7124. if(status !== ABORTED) {
  7125. responseHeaders = xhr.getAllResponseHeaders();
  7126. response = xhr.responseType ? xhr.response : xhr.responseText;
  7127. }
  7128. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  7129. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  7130. completeRequest(callback,
  7131. status || xhr.status,
  7132. response,
  7133. responseHeaders);
  7134. }
  7135. };
  7136. if (withCredentials) {
  7137. xhr.withCredentials = true;
  7138. }
  7139. if (responseType) {
  7140. xhr.responseType = responseType;
  7141. }
  7142. xhr.send(post || null);
  7143. }
  7144. if (timeout > 0) {
  7145. var timeoutId = $browserDefer(timeoutRequest, timeout);
  7146. } else if (timeout && timeout.then) {
  7147. timeout.then(timeoutRequest);
  7148. }
  7149. function timeoutRequest() {
  7150. status = ABORTED;
  7151. jsonpDone && jsonpDone();
  7152. xhr && xhr.abort();
  7153. }
  7154. function completeRequest(callback, status, response, headersString) {
  7155. var protocol = urlResolve(url).protocol;
  7156. // cancel timeout and subsequent timeout promise resolution
  7157. timeoutId && $browserDefer.cancel(timeoutId);
  7158. jsonpDone = xhr = null;
  7159. // fix status code for file protocol (it's always 0)
  7160. status = (protocol == 'file' && status === 0) ? (response ? 200 : 404) : status;
  7161. // normalize IE bug (http://bugs.jquery.com/ticket/1450)
  7162. status = status == 1223 ? 204 : status;
  7163. callback(status, response, headersString);
  7164. $browser.$$completeOutstandingRequest(noop);
  7165. }
  7166. };
  7167. function jsonpReq(url, done) {
  7168. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  7169. // - fetches local scripts via XHR and evals them
  7170. // - adds and immediately removes script elements from the document
  7171. var script = rawDocument.createElement('script'),
  7172. doneWrapper = function() {
  7173. script.onreadystatechange = script.onload = script.onerror = null;
  7174. rawDocument.body.removeChild(script);
  7175. if (done) done();
  7176. };
  7177. script.type = 'text/javascript';
  7178. script.src = url;
  7179. if (msie && msie <= 8) {
  7180. script.onreadystatechange = function() {
  7181. if (/loaded|complete/.test(script.readyState)) {
  7182. doneWrapper();
  7183. }
  7184. };
  7185. } else {
  7186. script.onload = script.onerror = function() {
  7187. doneWrapper();
  7188. };
  7189. }
  7190. rawDocument.body.appendChild(script);
  7191. return doneWrapper;
  7192. }
  7193. }
  7194. var $interpolateMinErr = minErr('$interpolate');
  7195. /**
  7196. * @ngdoc object
  7197. * @name ng.$interpolateProvider
  7198. * @function
  7199. *
  7200. * @description
  7201. *
  7202. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  7203. *
  7204. * @example
  7205. <doc:example module="customInterpolationApp">
  7206. <doc:source>
  7207. <script>
  7208. var customInterpolationApp = angular.module('customInterpolationApp', []);
  7209. customInterpolationApp.config(function($interpolateProvider) {
  7210. $interpolateProvider.startSymbol('//');
  7211. $interpolateProvider.endSymbol('//');
  7212. });
  7213. customInterpolationApp.controller('DemoController', function DemoController() {
  7214. this.label = "This binding is brought you by // interpolation symbols.";
  7215. });
  7216. </script>
  7217. <div ng-app="App" ng-controller="DemoController as demo">
  7218. //demo.label//
  7219. </div>
  7220. </doc:source>
  7221. <doc:scenario>
  7222. it('should interpolate binding with custom symbols', function() {
  7223. expect(binding('demo.label')).toBe('This binding is brought you by // interpolation symbols.');
  7224. });
  7225. </doc:scenario>
  7226. </doc:example>
  7227. */
  7228. function $InterpolateProvider() {
  7229. var startSymbol = '{{';
  7230. var endSymbol = '}}';
  7231. /**
  7232. * @ngdoc method
  7233. * @name ng.$interpolateProvider#startSymbol
  7234. * @methodOf ng.$interpolateProvider
  7235. * @description
  7236. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  7237. *
  7238. * @param {string=} value new value to set the starting symbol to.
  7239. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7240. */
  7241. this.startSymbol = function(value){
  7242. if (value) {
  7243. startSymbol = value;
  7244. return this;
  7245. } else {
  7246. return startSymbol;
  7247. }
  7248. };
  7249. /**
  7250. * @ngdoc method
  7251. * @name ng.$interpolateProvider#endSymbol
  7252. * @methodOf ng.$interpolateProvider
  7253. * @description
  7254. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7255. *
  7256. * @param {string=} value new value to set the ending symbol to.
  7257. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7258. */
  7259. this.endSymbol = function(value){
  7260. if (value) {
  7261. endSymbol = value;
  7262. return this;
  7263. } else {
  7264. return endSymbol;
  7265. }
  7266. };
  7267. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  7268. var startSymbolLength = startSymbol.length,
  7269. endSymbolLength = endSymbol.length;
  7270. /**
  7271. * @ngdoc function
  7272. * @name ng.$interpolate
  7273. * @function
  7274. *
  7275. * @requires $parse
  7276. * @requires $sce
  7277. *
  7278. * @description
  7279. *
  7280. * Compiles a string with markup into an interpolation function. This service is used by the
  7281. * HTML {@link ng.$compile $compile} service for data binding. See
  7282. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  7283. * interpolation markup.
  7284. *
  7285. *
  7286. <pre>
  7287. var $interpolate = ...; // injected
  7288. var exp = $interpolate('Hello {{name | uppercase}}!');
  7289. expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  7290. </pre>
  7291. *
  7292. *
  7293. * @param {string} text The text with markup to interpolate.
  7294. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  7295. * embedded expression in order to return an interpolation function. Strings with no
  7296. * embedded expression will return null for the interpolation function.
  7297. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  7298. * result through {@link ng.$sce#methods_getTrusted $sce.getTrusted(interpolatedResult,
  7299. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  7300. * provides Strict Contextual Escaping for details.
  7301. * @returns {function(context)} an interpolation function which is used to compute the
  7302. * interpolated string. The function has these parameters:
  7303. *
  7304. * * `context`: an object against which any expressions embedded in the strings are evaluated
  7305. * against.
  7306. *
  7307. */
  7308. function $interpolate(text, mustHaveExpression, trustedContext) {
  7309. var startIndex,
  7310. endIndex,
  7311. index = 0,
  7312. parts = [],
  7313. length = text.length,
  7314. hasInterpolation = false,
  7315. fn,
  7316. exp,
  7317. concat = [];
  7318. while(index < length) {
  7319. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  7320. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  7321. (index != startIndex) && parts.push(text.substring(index, startIndex));
  7322. parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
  7323. fn.exp = exp;
  7324. index = endIndex + endSymbolLength;
  7325. hasInterpolation = true;
  7326. } else {
  7327. // we did not find anything, so we have to add the remainder to the parts array
  7328. (index != length) && parts.push(text.substring(index));
  7329. index = length;
  7330. }
  7331. }
  7332. if (!(length = parts.length)) {
  7333. // we added, nothing, must have been an empty string.
  7334. parts.push('');
  7335. length = 1;
  7336. }
  7337. // Concatenating expressions makes it hard to reason about whether some combination of
  7338. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  7339. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  7340. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  7341. // make it obvious that you bound the value to some user controlled value. This helps reduce
  7342. // the load when auditing for XSS issues.
  7343. if (trustedContext && parts.length > 1) {
  7344. throw $interpolateMinErr('noconcat',
  7345. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  7346. "interpolations that concatenate multiple expressions when a trusted value is " +
  7347. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  7348. }
  7349. if (!mustHaveExpression || hasInterpolation) {
  7350. concat.length = length;
  7351. fn = function(context) {
  7352. try {
  7353. for(var i = 0, ii = length, part; i<ii; i++) {
  7354. if (typeof (part = parts[i]) == 'function') {
  7355. part = part(context);
  7356. if (trustedContext) {
  7357. part = $sce.getTrusted(trustedContext, part);
  7358. } else {
  7359. part = $sce.valueOf(part);
  7360. }
  7361. if (part === null || isUndefined(part)) {
  7362. part = '';
  7363. } else if (typeof part != 'string') {
  7364. part = toJson(part);
  7365. }
  7366. }
  7367. concat[i] = part;
  7368. }
  7369. return concat.join('');
  7370. }
  7371. catch(err) {
  7372. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  7373. err.toString());
  7374. $exceptionHandler(newErr);
  7375. }
  7376. };
  7377. fn.exp = text;
  7378. fn.parts = parts;
  7379. return fn;
  7380. }
  7381. }
  7382. /**
  7383. * @ngdoc method
  7384. * @name ng.$interpolate#startSymbol
  7385. * @methodOf ng.$interpolate
  7386. * @description
  7387. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  7388. *
  7389. * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
  7390. * the symbol.
  7391. *
  7392. * @returns {string} start symbol.
  7393. */
  7394. $interpolate.startSymbol = function() {
  7395. return startSymbol;
  7396. };
  7397. /**
  7398. * @ngdoc method
  7399. * @name ng.$interpolate#endSymbol
  7400. * @methodOf ng.$interpolate
  7401. * @description
  7402. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7403. *
  7404. * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
  7405. * the symbol.
  7406. *
  7407. * @returns {string} start symbol.
  7408. */
  7409. $interpolate.endSymbol = function() {
  7410. return endSymbol;
  7411. };
  7412. return $interpolate;
  7413. }];
  7414. }
  7415. function $IntervalProvider() {
  7416. this.$get = ['$rootScope', '$window', '$q',
  7417. function($rootScope, $window, $q) {
  7418. var intervals = {};
  7419. /**
  7420. * @ngdoc function
  7421. * @name ng.$interval
  7422. *
  7423. * @description
  7424. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  7425. * milliseconds.
  7426. *
  7427. * The return value of registering an interval function is a promise. This promise will be
  7428. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  7429. * run indefinitely if `count` is not defined. The value of the notification will be the
  7430. * number of iterations that have run.
  7431. * To cancel an interval, call `$interval.cancel(promise)`.
  7432. *
  7433. * In tests you can use {@link ngMock.$interval#methods_flush `$interval.flush(millis)`} to
  7434. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  7435. * time.
  7436. *
  7437. * @param {function()} fn A function that should be called repeatedly.
  7438. * @param {number} delay Number of milliseconds between each function call.
  7439. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  7440. * indefinitely.
  7441. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  7442. * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
  7443. * @returns {promise} A promise which will be notified on each iteration.
  7444. */
  7445. function interval(fn, delay, count, invokeApply) {
  7446. var setInterval = $window.setInterval,
  7447. clearInterval = $window.clearInterval,
  7448. deferred = $q.defer(),
  7449. promise = deferred.promise,
  7450. iteration = 0,
  7451. skipApply = (isDefined(invokeApply) && !invokeApply);
  7452. count = isDefined(count) ? count : 0,
  7453. promise.then(null, null, fn);
  7454. promise.$$intervalId = setInterval(function tick() {
  7455. deferred.notify(iteration++);
  7456. if (count > 0 && iteration >= count) {
  7457. deferred.resolve(iteration);
  7458. clearInterval(promise.$$intervalId);
  7459. delete intervals[promise.$$intervalId];
  7460. }
  7461. if (!skipApply) $rootScope.$apply();
  7462. }, delay);
  7463. intervals[promise.$$intervalId] = deferred;
  7464. return promise;
  7465. }
  7466. /**
  7467. * @ngdoc function
  7468. * @name ng.$interval#cancel
  7469. * @methodOf ng.$interval
  7470. *
  7471. * @description
  7472. * Cancels a task associated with the `promise`.
  7473. *
  7474. * @param {number} promise Promise returned by the `$interval` function.
  7475. * @returns {boolean} Returns `true` if the task was successfully canceled.
  7476. */
  7477. interval.cancel = function(promise) {
  7478. if (promise && promise.$$intervalId in intervals) {
  7479. intervals[promise.$$intervalId].reject('canceled');
  7480. clearInterval(promise.$$intervalId);
  7481. delete intervals[promise.$$intervalId];
  7482. return true;
  7483. }
  7484. return false;
  7485. };
  7486. return interval;
  7487. }];
  7488. }
  7489. /**
  7490. * @ngdoc object
  7491. * @name ng.$locale
  7492. *
  7493. * @description
  7494. * $locale service provides localization rules for various Angular components. As of right now the
  7495. * only public api is:
  7496. *
  7497. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  7498. */
  7499. function $LocaleProvider(){
  7500. this.$get = function() {
  7501. return {
  7502. id: 'en-us',
  7503. NUMBER_FORMATS: {
  7504. DECIMAL_SEP: '.',
  7505. GROUP_SEP: ',',
  7506. PATTERNS: [
  7507. { // Decimal Pattern
  7508. minInt: 1,
  7509. minFrac: 0,
  7510. maxFrac: 3,
  7511. posPre: '',
  7512. posSuf: '',
  7513. negPre: '-',
  7514. negSuf: '',
  7515. gSize: 3,
  7516. lgSize: 3
  7517. },{ //Currency Pattern
  7518. minInt: 1,
  7519. minFrac: 2,
  7520. maxFrac: 2,
  7521. posPre: '\u00A4',
  7522. posSuf: '',
  7523. negPre: '(\u00A4',
  7524. negSuf: ')',
  7525. gSize: 3,
  7526. lgSize: 3
  7527. }
  7528. ],
  7529. CURRENCY_SYM: '$'
  7530. },
  7531. DATETIME_FORMATS: {
  7532. MONTH:
  7533. 'January,February,March,April,May,June,July,August,September,October,November,December'
  7534. .split(','),
  7535. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  7536. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  7537. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  7538. AMPMS: ['AM','PM'],
  7539. medium: 'MMM d, y h:mm:ss a',
  7540. short: 'M/d/yy h:mm a',
  7541. fullDate: 'EEEE, MMMM d, y',
  7542. longDate: 'MMMM d, y',
  7543. mediumDate: 'MMM d, y',
  7544. shortDate: 'M/d/yy',
  7545. mediumTime: 'h:mm:ss a',
  7546. shortTime: 'h:mm a'
  7547. },
  7548. pluralCat: function(num) {
  7549. if (num === 1) {
  7550. return 'one';
  7551. }
  7552. return 'other';
  7553. }
  7554. };
  7555. };
  7556. }
  7557. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  7558. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  7559. var $locationMinErr = minErr('$location');
  7560. /**
  7561. * Encode path using encodeUriSegment, ignoring forward slashes
  7562. *
  7563. * @param {string} path Path to encode
  7564. * @returns {string}
  7565. */
  7566. function encodePath(path) {
  7567. var segments = path.split('/'),
  7568. i = segments.length;
  7569. while (i--) {
  7570. segments[i] = encodeUriSegment(segments[i]);
  7571. }
  7572. return segments.join('/');
  7573. }
  7574. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  7575. var parsedUrl = urlResolve(absoluteUrl, appBase);
  7576. locationObj.$$protocol = parsedUrl.protocol;
  7577. locationObj.$$host = parsedUrl.hostname;
  7578. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  7579. }
  7580. function parseAppUrl(relativeUrl, locationObj, appBase) {
  7581. var prefixed = (relativeUrl.charAt(0) !== '/');
  7582. if (prefixed) {
  7583. relativeUrl = '/' + relativeUrl;
  7584. }
  7585. var match = urlResolve(relativeUrl, appBase);
  7586. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  7587. match.pathname.substring(1) : match.pathname);
  7588. locationObj.$$search = parseKeyValue(match.search);
  7589. locationObj.$$hash = decodeURIComponent(match.hash);
  7590. // make sure path starts with '/';
  7591. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  7592. locationObj.$$path = '/' + locationObj.$$path;
  7593. }
  7594. }
  7595. /**
  7596. *
  7597. * @param {string} begin
  7598. * @param {string} whole
  7599. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  7600. * expected string.
  7601. */
  7602. function beginsWith(begin, whole) {
  7603. if (whole.indexOf(begin) === 0) {
  7604. return whole.substr(begin.length);
  7605. }
  7606. }
  7607. function stripHash(url) {
  7608. var index = url.indexOf('#');
  7609. return index == -1 ? url : url.substr(0, index);
  7610. }
  7611. function stripFile(url) {
  7612. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  7613. }
  7614. /* return the server only (scheme://host:port) */
  7615. function serverBase(url) {
  7616. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  7617. }
  7618. /**
  7619. * LocationHtml5Url represents an url
  7620. * This object is exposed as $location service when HTML5 mode is enabled and supported
  7621. *
  7622. * @constructor
  7623. * @param {string} appBase application base URL
  7624. * @param {string} basePrefix url path prefix
  7625. */
  7626. function LocationHtml5Url(appBase, basePrefix) {
  7627. this.$$html5 = true;
  7628. basePrefix = basePrefix || '';
  7629. var appBaseNoFile = stripFile(appBase);
  7630. parseAbsoluteUrl(appBase, this, appBase);
  7631. /**
  7632. * Parse given html5 (regular) url string into properties
  7633. * @param {string} newAbsoluteUrl HTML5 url
  7634. * @private
  7635. */
  7636. this.$$parse = function(url) {
  7637. var pathUrl = beginsWith(appBaseNoFile, url);
  7638. if (!isString(pathUrl)) {
  7639. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  7640. appBaseNoFile);
  7641. }
  7642. parseAppUrl(pathUrl, this, appBase);
  7643. if (!this.$$path) {
  7644. this.$$path = '/';
  7645. }
  7646. this.$$compose();
  7647. };
  7648. /**
  7649. * Compose url and update `absUrl` property
  7650. * @private
  7651. */
  7652. this.$$compose = function() {
  7653. var search = toKeyValue(this.$$search),
  7654. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  7655. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  7656. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  7657. };
  7658. this.$$rewrite = function(url) {
  7659. var appUrl, prevAppUrl;
  7660. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  7661. prevAppUrl = appUrl;
  7662. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  7663. return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  7664. } else {
  7665. return appBase + prevAppUrl;
  7666. }
  7667. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  7668. return appBaseNoFile + appUrl;
  7669. } else if (appBaseNoFile == url + '/') {
  7670. return appBaseNoFile;
  7671. }
  7672. };
  7673. }
  7674. /**
  7675. * LocationHashbangUrl represents url
  7676. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  7677. * It also serves as the base class for html5 mode fallback on legacy browsers.
  7678. *
  7679. * @constructor
  7680. * @param {string} appBase application base URL
  7681. * @param {string} hashPrefix hashbang prefix
  7682. */
  7683. function LocationHashbangUrl(appBase, hashPrefix) {
  7684. var appBaseNoFile = stripFile(appBase);
  7685. parseAbsoluteUrl(appBase, this, appBase);
  7686. /**
  7687. * Parse given hashbang url into properties
  7688. * @param {string} url Hashbang url
  7689. * @private
  7690. */
  7691. this.$$parse = function(url) {
  7692. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  7693. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  7694. ? beginsWith(hashPrefix, withoutBaseUrl)
  7695. : (this.$$html5)
  7696. ? withoutBaseUrl
  7697. : '';
  7698. if (!isString(withoutHashUrl)) {
  7699. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  7700. hashPrefix);
  7701. }
  7702. parseAppUrl(withoutHashUrl, this, appBase);
  7703. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  7704. this.$$compose();
  7705. /*
  7706. * In Windows, on an anchor node on documents loaded from
  7707. * the filesystem, the browser will return a pathname
  7708. * prefixed with the drive name ('/C:/path') when a
  7709. * pathname without a drive is set:
  7710. * * a.setAttribute('href', '/foo')
  7711. * * a.pathname === '/C:/foo' //true
  7712. *
  7713. * Inside of Angular, we're always using pathnames that
  7714. * do not include drive names for routing.
  7715. */
  7716. function removeWindowsDriveName (path, url, base) {
  7717. /*
  7718. Matches paths for file protocol on windows,
  7719. such as /C:/foo/bar, and captures only /foo/bar.
  7720. */
  7721. var windowsFilePathExp = /^\/?.*?:(\/.*)/;
  7722. var firstPathSegmentMatch;
  7723. //Get the relative path from the input URL.
  7724. if (url.indexOf(base) === 0) {
  7725. url = url.replace(base, '');
  7726. }
  7727. /*
  7728. * The input URL intentionally contains a
  7729. * first path segment that ends with a colon.
  7730. */
  7731. if (windowsFilePathExp.exec(url)) {
  7732. return path;
  7733. }
  7734. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  7735. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  7736. }
  7737. };
  7738. /**
  7739. * Compose hashbang url and update `absUrl` property
  7740. * @private
  7741. */
  7742. this.$$compose = function() {
  7743. var search = toKeyValue(this.$$search),
  7744. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  7745. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  7746. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  7747. };
  7748. this.$$rewrite = function(url) {
  7749. if(stripHash(appBase) == stripHash(url)) {
  7750. return url;
  7751. }
  7752. };
  7753. }
  7754. /**
  7755. * LocationHashbangUrl represents url
  7756. * This object is exposed as $location service when html5 history api is enabled but the browser
  7757. * does not support it.
  7758. *
  7759. * @constructor
  7760. * @param {string} appBase application base URL
  7761. * @param {string} hashPrefix hashbang prefix
  7762. */
  7763. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  7764. this.$$html5 = true;
  7765. LocationHashbangUrl.apply(this, arguments);
  7766. var appBaseNoFile = stripFile(appBase);
  7767. this.$$rewrite = function(url) {
  7768. var appUrl;
  7769. if ( appBase == stripHash(url) ) {
  7770. return url;
  7771. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  7772. return appBase + hashPrefix + appUrl;
  7773. } else if ( appBaseNoFile === url + '/') {
  7774. return appBaseNoFile;
  7775. }
  7776. };
  7777. }
  7778. LocationHashbangInHtml5Url.prototype =
  7779. LocationHashbangUrl.prototype =
  7780. LocationHtml5Url.prototype = {
  7781. /**
  7782. * Are we in html5 mode?
  7783. * @private
  7784. */
  7785. $$html5: false,
  7786. /**
  7787. * Has any change been replacing ?
  7788. * @private
  7789. */
  7790. $$replace: false,
  7791. /**
  7792. * @ngdoc method
  7793. * @name ng.$location#absUrl
  7794. * @methodOf ng.$location
  7795. *
  7796. * @description
  7797. * This method is getter only.
  7798. *
  7799. * Return full url representation with all segments encoded according to rules specified in
  7800. * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
  7801. *
  7802. * @return {string} full url
  7803. */
  7804. absUrl: locationGetter('$$absUrl'),
  7805. /**
  7806. * @ngdoc method
  7807. * @name ng.$location#url
  7808. * @methodOf ng.$location
  7809. *
  7810. * @description
  7811. * This method is getter / setter.
  7812. *
  7813. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  7814. *
  7815. * Change path, search and hash, when called with parameter and return `$location`.
  7816. *
  7817. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  7818. * @param {string=} replace The path that will be changed
  7819. * @return {string} url
  7820. */
  7821. url: function(url, replace) {
  7822. if (isUndefined(url))
  7823. return this.$$url;
  7824. var match = PATH_MATCH.exec(url);
  7825. if (match[1]) this.path(decodeURIComponent(match[1]));
  7826. if (match[2] || match[1]) this.search(match[3] || '');
  7827. this.hash(match[5] || '', replace);
  7828. return this;
  7829. },
  7830. /**
  7831. * @ngdoc method
  7832. * @name ng.$location#protocol
  7833. * @methodOf ng.$location
  7834. *
  7835. * @description
  7836. * This method is getter only.
  7837. *
  7838. * Return protocol of current url.
  7839. *
  7840. * @return {string} protocol of current url
  7841. */
  7842. protocol: locationGetter('$$protocol'),
  7843. /**
  7844. * @ngdoc method
  7845. * @name ng.$location#host
  7846. * @methodOf ng.$location
  7847. *
  7848. * @description
  7849. * This method is getter only.
  7850. *
  7851. * Return host of current url.
  7852. *
  7853. * @return {string} host of current url.
  7854. */
  7855. host: locationGetter('$$host'),
  7856. /**
  7857. * @ngdoc method
  7858. * @name ng.$location#port
  7859. * @methodOf ng.$location
  7860. *
  7861. * @description
  7862. * This method is getter only.
  7863. *
  7864. * Return port of current url.
  7865. *
  7866. * @return {Number} port
  7867. */
  7868. port: locationGetter('$$port'),
  7869. /**
  7870. * @ngdoc method
  7871. * @name ng.$location#path
  7872. * @methodOf ng.$location
  7873. *
  7874. * @description
  7875. * This method is getter / setter.
  7876. *
  7877. * Return path of current url when called without any parameter.
  7878. *
  7879. * Change path when called with parameter and return `$location`.
  7880. *
  7881. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  7882. * if it is missing.
  7883. *
  7884. * @param {string=} path New path
  7885. * @return {string} path
  7886. */
  7887. path: locationGetterSetter('$$path', function(path) {
  7888. return path.charAt(0) == '/' ? path : '/' + path;
  7889. }),
  7890. /**
  7891. * @ngdoc method
  7892. * @name ng.$location#search
  7893. * @methodOf ng.$location
  7894. *
  7895. * @description
  7896. * This method is getter / setter.
  7897. *
  7898. * Return search part (as object) of current url when called without any parameter.
  7899. *
  7900. * Change search part when called with parameter and return `$location`.
  7901. *
  7902. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  7903. * hash object. Hash object may contain an array of values, which will be decoded as duplicates in
  7904. * the url.
  7905. *
  7906. * @param {(string|Array<string>)=} paramValue If `search` is a string, then `paramValue` will override only a
  7907. * single search parameter. If `paramValue` is an array, it will set the parameter as a
  7908. * comma-separated value. If `paramValue` is `null`, the parameter will be deleted.
  7909. *
  7910. * @return {string} search
  7911. */
  7912. search: function(search, paramValue) {
  7913. switch (arguments.length) {
  7914. case 0:
  7915. return this.$$search;
  7916. case 1:
  7917. if (isString(search)) {
  7918. this.$$search = parseKeyValue(search);
  7919. } else if (isObject(search)) {
  7920. this.$$search = search;
  7921. } else {
  7922. throw $locationMinErr('isrcharg',
  7923. 'The first argument of the `$location#search()` call must be a string or an object.');
  7924. }
  7925. break;
  7926. default:
  7927. if (isUndefined(paramValue) || paramValue === null) {
  7928. delete this.$$search[search];
  7929. } else {
  7930. this.$$search[search] = paramValue;
  7931. }
  7932. }
  7933. this.$$compose();
  7934. return this;
  7935. },
  7936. /**
  7937. * @ngdoc method
  7938. * @name ng.$location#hash
  7939. * @methodOf ng.$location
  7940. *
  7941. * @description
  7942. * This method is getter / setter.
  7943. *
  7944. * Return hash fragment when called without any parameter.
  7945. *
  7946. * Change hash fragment when called with parameter and return `$location`.
  7947. *
  7948. * @param {string=} hash New hash fragment
  7949. * @return {string} hash
  7950. */
  7951. hash: locationGetterSetter('$$hash', identity),
  7952. /**
  7953. * @ngdoc method
  7954. * @name ng.$location#replace
  7955. * @methodOf ng.$location
  7956. *
  7957. * @description
  7958. * If called, all changes to $location during current `$digest` will be replacing current history
  7959. * record, instead of adding new one.
  7960. */
  7961. replace: function() {
  7962. this.$$replace = true;
  7963. return this;
  7964. }
  7965. };
  7966. function locationGetter(property) {
  7967. return function() {
  7968. return this[property];
  7969. };
  7970. }
  7971. function locationGetterSetter(property, preprocess) {
  7972. return function(value) {
  7973. if (isUndefined(value))
  7974. return this[property];
  7975. this[property] = preprocess(value);
  7976. this.$$compose();
  7977. return this;
  7978. };
  7979. }
  7980. /**
  7981. * @ngdoc object
  7982. * @name ng.$location
  7983. *
  7984. * @requires $browser
  7985. * @requires $sniffer
  7986. * @requires $rootElement
  7987. *
  7988. * @description
  7989. * The $location service parses the URL in the browser address bar (based on the
  7990. * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
  7991. * available to your application. Changes to the URL in the address bar are reflected into
  7992. * $location service and changes to $location are reflected into the browser address bar.
  7993. *
  7994. * **The $location service:**
  7995. *
  7996. * - Exposes the current URL in the browser address bar, so you can
  7997. * - Watch and observe the URL.
  7998. * - Change the URL.
  7999. * - Synchronizes the URL with the browser when the user
  8000. * - Changes the address bar.
  8001. * - Clicks the back or forward button (or clicks a History link).
  8002. * - Clicks on a link.
  8003. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  8004. *
  8005. * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
  8006. * Services: Using $location}
  8007. */
  8008. /**
  8009. * @ngdoc object
  8010. * @name ng.$locationProvider
  8011. * @description
  8012. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  8013. */
  8014. function $LocationProvider(){
  8015. var hashPrefix = '',
  8016. html5Mode = false;
  8017. /**
  8018. * @ngdoc property
  8019. * @name ng.$locationProvider#hashPrefix
  8020. * @methodOf ng.$locationProvider
  8021. * @description
  8022. * @param {string=} prefix Prefix for hash part (containing path and search)
  8023. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8024. */
  8025. this.hashPrefix = function(prefix) {
  8026. if (isDefined(prefix)) {
  8027. hashPrefix = prefix;
  8028. return this;
  8029. } else {
  8030. return hashPrefix;
  8031. }
  8032. };
  8033. /**
  8034. * @ngdoc property
  8035. * @name ng.$locationProvider#html5Mode
  8036. * @methodOf ng.$locationProvider
  8037. * @description
  8038. * @param {boolean=} mode Use HTML5 strategy if available.
  8039. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8040. */
  8041. this.html5Mode = function(mode) {
  8042. if (isDefined(mode)) {
  8043. html5Mode = mode;
  8044. return this;
  8045. } else {
  8046. return html5Mode;
  8047. }
  8048. };
  8049. /**
  8050. * @ngdoc event
  8051. * @name ng.$location#$locationChangeStart
  8052. * @eventOf ng.$location
  8053. * @eventType broadcast on root scope
  8054. * @description
  8055. * Broadcasted before a URL will change. This change can be prevented by calling
  8056. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  8057. * details about event object. Upon successful change
  8058. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  8059. *
  8060. * @param {Object} angularEvent Synthetic event object.
  8061. * @param {string} newUrl New URL
  8062. * @param {string=} oldUrl URL that was before it was changed.
  8063. */
  8064. /**
  8065. * @ngdoc event
  8066. * @name ng.$location#$locationChangeSuccess
  8067. * @eventOf ng.$location
  8068. * @eventType broadcast on root scope
  8069. * @description
  8070. * Broadcasted after a URL was changed.
  8071. *
  8072. * @param {Object} angularEvent Synthetic event object.
  8073. * @param {string} newUrl New URL
  8074. * @param {string=} oldUrl URL that was before it was changed.
  8075. */
  8076. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  8077. function( $rootScope, $browser, $sniffer, $rootElement) {
  8078. var $location,
  8079. LocationMode,
  8080. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  8081. initialUrl = $browser.url(),
  8082. appBase;
  8083. if (html5Mode) {
  8084. appBase = serverBase(initialUrl) + (baseHref || '/');
  8085. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  8086. } else {
  8087. appBase = stripHash(initialUrl);
  8088. LocationMode = LocationHashbangUrl;
  8089. }
  8090. $location = new LocationMode(appBase, '#' + hashPrefix);
  8091. $location.$$parse($location.$$rewrite(initialUrl));
  8092. $rootElement.on('click', function(event) {
  8093. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  8094. // currently we open nice url link and redirect then
  8095. if (event.ctrlKey || event.metaKey || event.which == 2) return;
  8096. var elm = jqLite(event.target);
  8097. // traverse the DOM up to find first A tag
  8098. while (lowercase(elm[0].nodeName) !== 'a') {
  8099. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  8100. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  8101. }
  8102. var absHref = elm.prop('href');
  8103. var rewrittenUrl = $location.$$rewrite(absHref);
  8104. if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
  8105. event.preventDefault();
  8106. if (rewrittenUrl != $browser.url()) {
  8107. // update location manually
  8108. $location.$$parse(rewrittenUrl);
  8109. $rootScope.$apply();
  8110. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  8111. window.angular['ff-684208-preventDefault'] = true;
  8112. }
  8113. }
  8114. });
  8115. // rewrite hashbang url <> html5 url
  8116. if ($location.absUrl() != initialUrl) {
  8117. $browser.url($location.absUrl(), true);
  8118. }
  8119. // update $location when $browser url changes
  8120. $browser.onUrlChange(function(newUrl) {
  8121. if ($location.absUrl() != newUrl) {
  8122. if ($rootScope.$broadcast('$locationChangeStart', newUrl,
  8123. $location.absUrl()).defaultPrevented) {
  8124. $browser.url($location.absUrl());
  8125. return;
  8126. }
  8127. $rootScope.$evalAsync(function() {
  8128. var oldUrl = $location.absUrl();
  8129. $location.$$parse(newUrl);
  8130. afterLocationChange(oldUrl);
  8131. });
  8132. if (!$rootScope.$$phase) $rootScope.$digest();
  8133. }
  8134. });
  8135. // update browser
  8136. var changeCounter = 0;
  8137. $rootScope.$watch(function $locationWatch() {
  8138. var oldUrl = $browser.url();
  8139. var currentReplace = $location.$$replace;
  8140. if (!changeCounter || oldUrl != $location.absUrl()) {
  8141. changeCounter++;
  8142. $rootScope.$evalAsync(function() {
  8143. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
  8144. defaultPrevented) {
  8145. $location.$$parse(oldUrl);
  8146. } else {
  8147. $browser.url($location.absUrl(), currentReplace);
  8148. afterLocationChange(oldUrl);
  8149. }
  8150. });
  8151. }
  8152. $location.$$replace = false;
  8153. return changeCounter;
  8154. });
  8155. return $location;
  8156. function afterLocationChange(oldUrl) {
  8157. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
  8158. }
  8159. }];
  8160. }
  8161. /**
  8162. * @ngdoc object
  8163. * @name ng.$log
  8164. * @requires $window
  8165. *
  8166. * @description
  8167. * Simple service for logging. Default implementation safely writes the message
  8168. * into the browser's console (if present).
  8169. *
  8170. * The main purpose of this service is to simplify debugging and troubleshooting.
  8171. *
  8172. * The default is to log `debug` messages. You can use
  8173. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  8174. *
  8175. * @example
  8176. <example>
  8177. <file name="script.js">
  8178. function LogCtrl($scope, $log) {
  8179. $scope.$log = $log;
  8180. $scope.message = 'Hello World!';
  8181. }
  8182. </file>
  8183. <file name="index.html">
  8184. <div ng-controller="LogCtrl">
  8185. <p>Reload this page with open console, enter text and hit the log button...</p>
  8186. Message:
  8187. <input type="text" ng-model="message"/>
  8188. <button ng-click="$log.log(message)">log</button>
  8189. <button ng-click="$log.warn(message)">warn</button>
  8190. <button ng-click="$log.info(message)">info</button>
  8191. <button ng-click="$log.error(message)">error</button>
  8192. </div>
  8193. </file>
  8194. </example>
  8195. */
  8196. /**
  8197. * @ngdoc object
  8198. * @name ng.$logProvider
  8199. * @description
  8200. * Use the `$logProvider` to configure how the application logs messages
  8201. */
  8202. function $LogProvider(){
  8203. var debug = true,
  8204. self = this;
  8205. /**
  8206. * @ngdoc property
  8207. * @name ng.$logProvider#debugEnabled
  8208. * @methodOf ng.$logProvider
  8209. * @description
  8210. * @param {string=} flag enable or disable debug level messages
  8211. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8212. */
  8213. this.debugEnabled = function(flag) {
  8214. if (isDefined(flag)) {
  8215. debug = flag;
  8216. return this;
  8217. } else {
  8218. return debug;
  8219. }
  8220. };
  8221. this.$get = ['$window', function($window){
  8222. return {
  8223. /**
  8224. * @ngdoc method
  8225. * @name ng.$log#log
  8226. * @methodOf ng.$log
  8227. *
  8228. * @description
  8229. * Write a log message
  8230. */
  8231. log: consoleLog('log'),
  8232. /**
  8233. * @ngdoc method
  8234. * @name ng.$log#info
  8235. * @methodOf ng.$log
  8236. *
  8237. * @description
  8238. * Write an information message
  8239. */
  8240. info: consoleLog('info'),
  8241. /**
  8242. * @ngdoc method
  8243. * @name ng.$log#warn
  8244. * @methodOf ng.$log
  8245. *
  8246. * @description
  8247. * Write a warning message
  8248. */
  8249. warn: consoleLog('warn'),
  8250. /**
  8251. * @ngdoc method
  8252. * @name ng.$log#error
  8253. * @methodOf ng.$log
  8254. *
  8255. * @description
  8256. * Write an error message
  8257. */
  8258. error: consoleLog('error'),
  8259. /**
  8260. * @ngdoc method
  8261. * @name ng.$log#debug
  8262. * @methodOf ng.$log
  8263. *
  8264. * @description
  8265. * Write a debug message
  8266. */
  8267. debug: (function () {
  8268. var fn = consoleLog('debug');
  8269. return function() {
  8270. if (debug) {
  8271. fn.apply(self, arguments);
  8272. }
  8273. };
  8274. }())
  8275. };
  8276. function formatError(arg) {
  8277. if (arg instanceof Error) {
  8278. if (arg.stack) {
  8279. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  8280. ? 'Error: ' + arg.message + '\n' + arg.stack
  8281. : arg.stack;
  8282. } else if (arg.sourceURL) {
  8283. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  8284. }
  8285. }
  8286. return arg;
  8287. }
  8288. function consoleLog(type) {
  8289. var console = $window.console || {},
  8290. logFn = console[type] || console.log || noop;
  8291. if (logFn.apply) {
  8292. return function() {
  8293. var args = [];
  8294. forEach(arguments, function(arg) {
  8295. args.push(formatError(arg));
  8296. });
  8297. return logFn.apply(console, args);
  8298. };
  8299. }
  8300. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  8301. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  8302. return function(arg1, arg2) {
  8303. logFn(arg1, arg2 == null ? '' : arg2);
  8304. };
  8305. }
  8306. }];
  8307. }
  8308. var $parseMinErr = minErr('$parse');
  8309. var promiseWarningCache = {};
  8310. var promiseWarning;
  8311. // Sandboxing Angular Expressions
  8312. // ------------------------------
  8313. // Angular expressions are generally considered safe because these expressions only have direct
  8314. // access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
  8315. // obtaining a reference to native JS functions such as the Function constructor.
  8316. //
  8317. // As an example, consider the following Angular expression:
  8318. //
  8319. // {}.toString.constructor(alert("evil JS code"))
  8320. //
  8321. // We want to prevent this type of access. For the sake of performance, during the lexing phase we
  8322. // disallow any "dotted" access to any member named "constructor".
  8323. //
  8324. // For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor
  8325. // while evaluating the expression, which is a stronger but more expensive test. Since reflective
  8326. // calls are expensive anyway, this is not such a big deal compared to static dereferencing.
  8327. //
  8328. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  8329. // against the expression language, but not to prevent exploits that were enabled by exposing
  8330. // sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
  8331. // practice and therefore we are not even trying to protect against interaction with an object
  8332. // explicitly exposed in this way.
  8333. //
  8334. // A developer could foil the name check by aliasing the Function constructor under a different
  8335. // name on the scope.
  8336. //
  8337. // In general, it is not possible to access a Window object from an angular expression unless a
  8338. // window or some DOM object that has a reference to window is published onto a Scope.
  8339. function ensureSafeMemberName(name, fullExpression) {
  8340. if (name === "constructor") {
  8341. throw $parseMinErr('isecfld',
  8342. 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',
  8343. fullExpression);
  8344. }
  8345. return name;
  8346. }
  8347. function ensureSafeObject(obj, fullExpression) {
  8348. // nifty check if obj is Function that is fast and works across iframes and other contexts
  8349. if (obj) {
  8350. if (obj.constructor === obj) {
  8351. throw $parseMinErr('isecfn',
  8352. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  8353. fullExpression);
  8354. } else if (// isWindow(obj)
  8355. obj.document && obj.location && obj.alert && obj.setInterval) {
  8356. throw $parseMinErr('isecwindow',
  8357. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  8358. fullExpression);
  8359. } else if (// isElement(obj)
  8360. obj.children && (obj.nodeName || (obj.on && obj.find))) {
  8361. throw $parseMinErr('isecdom',
  8362. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  8363. fullExpression);
  8364. }
  8365. }
  8366. return obj;
  8367. }
  8368. var OPERATORS = {
  8369. /* jshint bitwise : false */
  8370. 'null':function(){return null;},
  8371. 'true':function(){return true;},
  8372. 'false':function(){return false;},
  8373. undefined:noop,
  8374. '+':function(self, locals, a,b){
  8375. a=a(self, locals); b=b(self, locals);
  8376. if (isDefined(a)) {
  8377. if (isDefined(b)) {
  8378. return a + b;
  8379. }
  8380. return a;
  8381. }
  8382. return isDefined(b)?b:undefined;},
  8383. '-':function(self, locals, a,b){
  8384. a=a(self, locals); b=b(self, locals);
  8385. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  8386. },
  8387. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  8388. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  8389. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  8390. '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
  8391. '=':noop,
  8392. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  8393. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  8394. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  8395. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  8396. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  8397. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  8398. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  8399. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  8400. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  8401. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  8402. '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
  8403. // '|':function(self, locals, a,b){return a|b;},
  8404. '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
  8405. '!':function(self, locals, a){return !a(self, locals);}
  8406. };
  8407. /* jshint bitwise: true */
  8408. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  8409. /////////////////////////////////////////
  8410. /**
  8411. * @constructor
  8412. */
  8413. var Lexer = function (options) {
  8414. this.options = options;
  8415. };
  8416. Lexer.prototype = {
  8417. constructor: Lexer,
  8418. lex: function (text) {
  8419. this.text = text;
  8420. this.index = 0;
  8421. this.ch = undefined;
  8422. this.lastCh = ':'; // can start regexp
  8423. this.tokens = [];
  8424. var token;
  8425. var json = [];
  8426. while (this.index < this.text.length) {
  8427. this.ch = this.text.charAt(this.index);
  8428. if (this.is('"\'')) {
  8429. this.readString(this.ch);
  8430. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  8431. this.readNumber();
  8432. } else if (this.isIdent(this.ch)) {
  8433. this.readIdent();
  8434. // identifiers can only be if the preceding char was a { or ,
  8435. if (this.was('{,') && json[0] === '{' &&
  8436. (token = this.tokens[this.tokens.length - 1])) {
  8437. token.json = token.text.indexOf('.') === -1;
  8438. }
  8439. } else if (this.is('(){}[].,;:?')) {
  8440. this.tokens.push({
  8441. index: this.index,
  8442. text: this.ch,
  8443. json: (this.was(':[,') && this.is('{[')) || this.is('}]:,')
  8444. });
  8445. if (this.is('{[')) json.unshift(this.ch);
  8446. if (this.is('}]')) json.shift();
  8447. this.index++;
  8448. } else if (this.isWhitespace(this.ch)) {
  8449. this.index++;
  8450. continue;
  8451. } else {
  8452. var ch2 = this.ch + this.peek();
  8453. var ch3 = ch2 + this.peek(2);
  8454. var fn = OPERATORS[this.ch];
  8455. var fn2 = OPERATORS[ch2];
  8456. var fn3 = OPERATORS[ch3];
  8457. if (fn3) {
  8458. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  8459. this.index += 3;
  8460. } else if (fn2) {
  8461. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  8462. this.index += 2;
  8463. } else if (fn) {
  8464. this.tokens.push({
  8465. index: this.index,
  8466. text: this.ch,
  8467. fn: fn,
  8468. json: (this.was('[,:') && this.is('+-'))
  8469. });
  8470. this.index += 1;
  8471. } else {
  8472. this.throwError('Unexpected next character ', this.index, this.index + 1);
  8473. }
  8474. }
  8475. this.lastCh = this.ch;
  8476. }
  8477. return this.tokens;
  8478. },
  8479. is: function(chars) {
  8480. return chars.indexOf(this.ch) !== -1;
  8481. },
  8482. was: function(chars) {
  8483. return chars.indexOf(this.lastCh) !== -1;
  8484. },
  8485. peek: function(i) {
  8486. var num = i || 1;
  8487. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  8488. },
  8489. isNumber: function(ch) {
  8490. return ('0' <= ch && ch <= '9');
  8491. },
  8492. isWhitespace: function(ch) {
  8493. // IE treats non-breaking space as \u00A0
  8494. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  8495. ch === '\n' || ch === '\v' || ch === '\u00A0');
  8496. },
  8497. isIdent: function(ch) {
  8498. return ('a' <= ch && ch <= 'z' ||
  8499. 'A' <= ch && ch <= 'Z' ||
  8500. '_' === ch || ch === '$');
  8501. },
  8502. isExpOperator: function(ch) {
  8503. return (ch === '-' || ch === '+' || this.isNumber(ch));
  8504. },
  8505. throwError: function(error, start, end) {
  8506. end = end || this.index;
  8507. var colStr = (isDefined(start)
  8508. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  8509. : ' ' + end);
  8510. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  8511. error, colStr, this.text);
  8512. },
  8513. readNumber: function() {
  8514. var number = '';
  8515. var start = this.index;
  8516. while (this.index < this.text.length) {
  8517. var ch = lowercase(this.text.charAt(this.index));
  8518. if (ch == '.' || this.isNumber(ch)) {
  8519. number += ch;
  8520. } else {
  8521. var peekCh = this.peek();
  8522. if (ch == 'e' && this.isExpOperator(peekCh)) {
  8523. number += ch;
  8524. } else if (this.isExpOperator(ch) &&
  8525. peekCh && this.isNumber(peekCh) &&
  8526. number.charAt(number.length - 1) == 'e') {
  8527. number += ch;
  8528. } else if (this.isExpOperator(ch) &&
  8529. (!peekCh || !this.isNumber(peekCh)) &&
  8530. number.charAt(number.length - 1) == 'e') {
  8531. this.throwError('Invalid exponent');
  8532. } else {
  8533. break;
  8534. }
  8535. }
  8536. this.index++;
  8537. }
  8538. number = 1 * number;
  8539. this.tokens.push({
  8540. index: start,
  8541. text: number,
  8542. json: true,
  8543. fn: function() { return number; }
  8544. });
  8545. },
  8546. readIdent: function() {
  8547. var parser = this;
  8548. var ident = '';
  8549. var start = this.index;
  8550. var lastDot, peekIndex, methodName, ch;
  8551. while (this.index < this.text.length) {
  8552. ch = this.text.charAt(this.index);
  8553. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  8554. if (ch === '.') lastDot = this.index;
  8555. ident += ch;
  8556. } else {
  8557. break;
  8558. }
  8559. this.index++;
  8560. }
  8561. //check if this is not a method invocation and if it is back out to last dot
  8562. if (lastDot) {
  8563. peekIndex = this.index;
  8564. while (peekIndex < this.text.length) {
  8565. ch = this.text.charAt(peekIndex);
  8566. if (ch === '(') {
  8567. methodName = ident.substr(lastDot - start + 1);
  8568. ident = ident.substr(0, lastDot - start);
  8569. this.index = peekIndex;
  8570. break;
  8571. }
  8572. if (this.isWhitespace(ch)) {
  8573. peekIndex++;
  8574. } else {
  8575. break;
  8576. }
  8577. }
  8578. }
  8579. var token = {
  8580. index: start,
  8581. text: ident
  8582. };
  8583. // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
  8584. if (OPERATORS.hasOwnProperty(ident)) {
  8585. token.fn = OPERATORS[ident];
  8586. token.json = OPERATORS[ident];
  8587. } else {
  8588. var getter = getterFn(ident, this.options, this.text);
  8589. token.fn = extend(function(self, locals) {
  8590. return (getter(self, locals));
  8591. }, {
  8592. assign: function(self, value) {
  8593. return setter(self, ident, value, parser.text, parser.options);
  8594. }
  8595. });
  8596. }
  8597. this.tokens.push(token);
  8598. if (methodName) {
  8599. this.tokens.push({
  8600. index:lastDot,
  8601. text: '.',
  8602. json: false
  8603. });
  8604. this.tokens.push({
  8605. index: lastDot + 1,
  8606. text: methodName,
  8607. json: false
  8608. });
  8609. }
  8610. },
  8611. readString: function(quote) {
  8612. var start = this.index;
  8613. this.index++;
  8614. var string = '';
  8615. var rawString = quote;
  8616. var escape = false;
  8617. while (this.index < this.text.length) {
  8618. var ch = this.text.charAt(this.index);
  8619. rawString += ch;
  8620. if (escape) {
  8621. if (ch === 'u') {
  8622. var hex = this.text.substring(this.index + 1, this.index + 5);
  8623. if (!hex.match(/[\da-f]{4}/i))
  8624. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  8625. this.index += 4;
  8626. string += String.fromCharCode(parseInt(hex, 16));
  8627. } else {
  8628. var rep = ESCAPE[ch];
  8629. if (rep) {
  8630. string += rep;
  8631. } else {
  8632. string += ch;
  8633. }
  8634. }
  8635. escape = false;
  8636. } else if (ch === '\\') {
  8637. escape = true;
  8638. } else if (ch === quote) {
  8639. this.index++;
  8640. this.tokens.push({
  8641. index: start,
  8642. text: rawString,
  8643. string: string,
  8644. json: true,
  8645. fn: function() { return string; }
  8646. });
  8647. return;
  8648. } else {
  8649. string += ch;
  8650. }
  8651. this.index++;
  8652. }
  8653. this.throwError('Unterminated quote', start);
  8654. }
  8655. };
  8656. /**
  8657. * @constructor
  8658. */
  8659. var Parser = function (lexer, $filter, options) {
  8660. this.lexer = lexer;
  8661. this.$filter = $filter;
  8662. this.options = options;
  8663. };
  8664. Parser.ZERO = function () { return 0; };
  8665. Parser.prototype = {
  8666. constructor: Parser,
  8667. parse: function (text, json) {
  8668. this.text = text;
  8669. //TODO(i): strip all the obsolte json stuff from this file
  8670. this.json = json;
  8671. this.tokens = this.lexer.lex(text);
  8672. if (json) {
  8673. // The extra level of aliasing is here, just in case the lexer misses something, so that
  8674. // we prevent any accidental execution in JSON.
  8675. this.assignment = this.logicalOR;
  8676. this.functionCall =
  8677. this.fieldAccess =
  8678. this.objectIndex =
  8679. this.filterChain = function() {
  8680. this.throwError('is not valid json', {text: text, index: 0});
  8681. };
  8682. }
  8683. var value = json ? this.primary() : this.statements();
  8684. if (this.tokens.length !== 0) {
  8685. this.throwError('is an unexpected token', this.tokens[0]);
  8686. }
  8687. value.literal = !!value.literal;
  8688. value.constant = !!value.constant;
  8689. return value;
  8690. },
  8691. primary: function () {
  8692. var primary;
  8693. if (this.expect('(')) {
  8694. primary = this.filterChain();
  8695. this.consume(')');
  8696. } else if (this.expect('[')) {
  8697. primary = this.arrayDeclaration();
  8698. } else if (this.expect('{')) {
  8699. primary = this.object();
  8700. } else {
  8701. var token = this.expect();
  8702. primary = token.fn;
  8703. if (!primary) {
  8704. this.throwError('not a primary expression', token);
  8705. }
  8706. if (token.json) {
  8707. primary.constant = true;
  8708. primary.literal = true;
  8709. }
  8710. }
  8711. var next, context;
  8712. while ((next = this.expect('(', '[', '.'))) {
  8713. if (next.text === '(') {
  8714. primary = this.functionCall(primary, context);
  8715. context = null;
  8716. } else if (next.text === '[') {
  8717. context = primary;
  8718. primary = this.objectIndex(primary);
  8719. } else if (next.text === '.') {
  8720. context = primary;
  8721. primary = this.fieldAccess(primary);
  8722. } else {
  8723. this.throwError('IMPOSSIBLE');
  8724. }
  8725. }
  8726. return primary;
  8727. },
  8728. throwError: function(msg, token) {
  8729. throw $parseMinErr('syntax',
  8730. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  8731. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  8732. },
  8733. peekToken: function() {
  8734. if (this.tokens.length === 0)
  8735. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  8736. return this.tokens[0];
  8737. },
  8738. peek: function(e1, e2, e3, e4) {
  8739. if (this.tokens.length > 0) {
  8740. var token = this.tokens[0];
  8741. var t = token.text;
  8742. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  8743. (!e1 && !e2 && !e3 && !e4)) {
  8744. return token;
  8745. }
  8746. }
  8747. return false;
  8748. },
  8749. expect: function(e1, e2, e3, e4){
  8750. var token = this.peek(e1, e2, e3, e4);
  8751. if (token) {
  8752. if (this.json && !token.json) {
  8753. this.throwError('is not valid json', token);
  8754. }
  8755. this.tokens.shift();
  8756. return token;
  8757. }
  8758. return false;
  8759. },
  8760. consume: function(e1){
  8761. if (!this.expect(e1)) {
  8762. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  8763. }
  8764. },
  8765. unaryFn: function(fn, right) {
  8766. return extend(function(self, locals) {
  8767. return fn(self, locals, right);
  8768. }, {
  8769. constant:right.constant
  8770. });
  8771. },
  8772. ternaryFn: function(left, middle, right){
  8773. return extend(function(self, locals){
  8774. return left(self, locals) ? middle(self, locals) : right(self, locals);
  8775. }, {
  8776. constant: left.constant && middle.constant && right.constant
  8777. });
  8778. },
  8779. binaryFn: function(left, fn, right) {
  8780. return extend(function(self, locals) {
  8781. return fn(self, locals, left, right);
  8782. }, {
  8783. constant:left.constant && right.constant
  8784. });
  8785. },
  8786. statements: function() {
  8787. var statements = [];
  8788. while (true) {
  8789. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  8790. statements.push(this.filterChain());
  8791. if (!this.expect(';')) {
  8792. // optimize for the common case where there is only one statement.
  8793. // TODO(size): maybe we should not support multiple statements?
  8794. return (statements.length === 1)
  8795. ? statements[0]
  8796. : function(self, locals) {
  8797. var value;
  8798. for (var i = 0; i < statements.length; i++) {
  8799. var statement = statements[i];
  8800. if (statement) {
  8801. value = statement(self, locals);
  8802. }
  8803. }
  8804. return value;
  8805. };
  8806. }
  8807. }
  8808. },
  8809. filterChain: function() {
  8810. var left = this.expression();
  8811. var token;
  8812. while (true) {
  8813. if ((token = this.expect('|'))) {
  8814. left = this.binaryFn(left, token.fn, this.filter());
  8815. } else {
  8816. return left;
  8817. }
  8818. }
  8819. },
  8820. filter: function() {
  8821. var token = this.expect();
  8822. var fn = this.$filter(token.text);
  8823. var argsFn = [];
  8824. while (true) {
  8825. if ((token = this.expect(':'))) {
  8826. argsFn.push(this.expression());
  8827. } else {
  8828. var fnInvoke = function(self, locals, input) {
  8829. var args = [input];
  8830. for (var i = 0; i < argsFn.length; i++) {
  8831. args.push(argsFn[i](self, locals));
  8832. }
  8833. return fn.apply(self, args);
  8834. };
  8835. return function() {
  8836. return fnInvoke;
  8837. };
  8838. }
  8839. }
  8840. },
  8841. expression: function() {
  8842. return this.assignment();
  8843. },
  8844. assignment: function() {
  8845. var left = this.ternary();
  8846. var right;
  8847. var token;
  8848. if ((token = this.expect('='))) {
  8849. if (!left.assign) {
  8850. this.throwError('implies assignment but [' +
  8851. this.text.substring(0, token.index) + '] can not be assigned to', token);
  8852. }
  8853. right = this.ternary();
  8854. return function(scope, locals) {
  8855. return left.assign(scope, right(scope, locals), locals);
  8856. };
  8857. }
  8858. return left;
  8859. },
  8860. ternary: function() {
  8861. var left = this.logicalOR();
  8862. var middle;
  8863. var token;
  8864. if ((token = this.expect('?'))) {
  8865. middle = this.ternary();
  8866. if ((token = this.expect(':'))) {
  8867. return this.ternaryFn(left, middle, this.ternary());
  8868. } else {
  8869. this.throwError('expected :', token);
  8870. }
  8871. } else {
  8872. return left;
  8873. }
  8874. },
  8875. logicalOR: function() {
  8876. var left = this.logicalAND();
  8877. var token;
  8878. while (true) {
  8879. if ((token = this.expect('||'))) {
  8880. left = this.binaryFn(left, token.fn, this.logicalAND());
  8881. } else {
  8882. return left;
  8883. }
  8884. }
  8885. },
  8886. logicalAND: function() {
  8887. var left = this.equality();
  8888. var token;
  8889. if ((token = this.expect('&&'))) {
  8890. left = this.binaryFn(left, token.fn, this.logicalAND());
  8891. }
  8892. return left;
  8893. },
  8894. equality: function() {
  8895. var left = this.relational();
  8896. var token;
  8897. if ((token = this.expect('==','!=','===','!=='))) {
  8898. left = this.binaryFn(left, token.fn, this.equality());
  8899. }
  8900. return left;
  8901. },
  8902. relational: function() {
  8903. var left = this.additive();
  8904. var token;
  8905. if ((token = this.expect('<', '>', '<=', '>='))) {
  8906. left = this.binaryFn(left, token.fn, this.relational());
  8907. }
  8908. return left;
  8909. },
  8910. additive: function() {
  8911. var left = this.multiplicative();
  8912. var token;
  8913. while ((token = this.expect('+','-'))) {
  8914. left = this.binaryFn(left, token.fn, this.multiplicative());
  8915. }
  8916. return left;
  8917. },
  8918. multiplicative: function() {
  8919. var left = this.unary();
  8920. var token;
  8921. while ((token = this.expect('*','/','%'))) {
  8922. left = this.binaryFn(left, token.fn, this.unary());
  8923. }
  8924. return left;
  8925. },
  8926. unary: function() {
  8927. var token;
  8928. if (this.expect('+')) {
  8929. return this.primary();
  8930. } else if ((token = this.expect('-'))) {
  8931. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  8932. } else if ((token = this.expect('!'))) {
  8933. return this.unaryFn(token.fn, this.unary());
  8934. } else {
  8935. return this.primary();
  8936. }
  8937. },
  8938. fieldAccess: function(object) {
  8939. var parser = this;
  8940. var field = this.expect().text;
  8941. var getter = getterFn(field, this.options, this.text);
  8942. return extend(function(scope, locals, self) {
  8943. return getter(self || object(scope, locals), locals);
  8944. }, {
  8945. assign: function(scope, value, locals) {
  8946. return setter(object(scope, locals), field, value, parser.text, parser.options);
  8947. }
  8948. });
  8949. },
  8950. objectIndex: function(obj) {
  8951. var parser = this;
  8952. var indexFn = this.expression();
  8953. this.consume(']');
  8954. return extend(function(self, locals) {
  8955. var o = obj(self, locals),
  8956. i = indexFn(self, locals),
  8957. v, p;
  8958. if (!o) return undefined;
  8959. v = ensureSafeObject(o[i], parser.text);
  8960. if (v && v.then && parser.options.unwrapPromises) {
  8961. p = v;
  8962. if (!('$$v' in v)) {
  8963. p.$$v = undefined;
  8964. p.then(function(val) { p.$$v = val; });
  8965. }
  8966. v = v.$$v;
  8967. }
  8968. return v;
  8969. }, {
  8970. assign: function(self, value, locals) {
  8971. var key = indexFn(self, locals);
  8972. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  8973. var safe = ensureSafeObject(obj(self, locals), parser.text);
  8974. return safe[key] = value;
  8975. }
  8976. });
  8977. },
  8978. functionCall: function(fn, contextGetter) {
  8979. var argsFn = [];
  8980. if (this.peekToken().text !== ')') {
  8981. do {
  8982. argsFn.push(this.expression());
  8983. } while (this.expect(','));
  8984. }
  8985. this.consume(')');
  8986. var parser = this;
  8987. return function(scope, locals) {
  8988. var args = [];
  8989. var context = contextGetter ? contextGetter(scope, locals) : scope;
  8990. for (var i = 0; i < argsFn.length; i++) {
  8991. args.push(argsFn[i](scope, locals));
  8992. }
  8993. var fnPtr = fn(scope, locals, context) || noop;
  8994. ensureSafeObject(context, parser.text);
  8995. ensureSafeObject(fnPtr, parser.text);
  8996. // IE stupidity! (IE doesn't have apply for some native functions)
  8997. var v = fnPtr.apply
  8998. ? fnPtr.apply(context, args)
  8999. : fnPtr(args[0], args[1], args[2], args[3], args[4]);
  9000. return ensureSafeObject(v, parser.text);
  9001. };
  9002. },
  9003. // This is used with json array declaration
  9004. arrayDeclaration: function () {
  9005. var elementFns = [];
  9006. var allConstant = true;
  9007. if (this.peekToken().text !== ']') {
  9008. do {
  9009. var elementFn = this.expression();
  9010. elementFns.push(elementFn);
  9011. if (!elementFn.constant) {
  9012. allConstant = false;
  9013. }
  9014. } while (this.expect(','));
  9015. }
  9016. this.consume(']');
  9017. return extend(function(self, locals) {
  9018. var array = [];
  9019. for (var i = 0; i < elementFns.length; i++) {
  9020. array.push(elementFns[i](self, locals));
  9021. }
  9022. return array;
  9023. }, {
  9024. literal: true,
  9025. constant: allConstant
  9026. });
  9027. },
  9028. object: function () {
  9029. var keyValues = [];
  9030. var allConstant = true;
  9031. if (this.peekToken().text !== '}') {
  9032. do {
  9033. var token = this.expect(),
  9034. key = token.string || token.text;
  9035. this.consume(':');
  9036. var value = this.expression();
  9037. keyValues.push({key: key, value: value});
  9038. if (!value.constant) {
  9039. allConstant = false;
  9040. }
  9041. } while (this.expect(','));
  9042. }
  9043. this.consume('}');
  9044. return extend(function(self, locals) {
  9045. var object = {};
  9046. for (var i = 0; i < keyValues.length; i++) {
  9047. var keyValue = keyValues[i];
  9048. object[keyValue.key] = keyValue.value(self, locals);
  9049. }
  9050. return object;
  9051. }, {
  9052. literal: true,
  9053. constant: allConstant
  9054. });
  9055. }
  9056. };
  9057. //////////////////////////////////////////////////
  9058. // Parser helper functions
  9059. //////////////////////////////////////////////////
  9060. function setter(obj, path, setValue, fullExp, options) {
  9061. //needed?
  9062. options = options || {};
  9063. var element = path.split('.'), key;
  9064. for (var i = 0; element.length > 1; i++) {
  9065. key = ensureSafeMemberName(element.shift(), fullExp);
  9066. var propertyObj = obj[key];
  9067. if (!propertyObj) {
  9068. propertyObj = {};
  9069. obj[key] = propertyObj;
  9070. }
  9071. obj = propertyObj;
  9072. if (obj.then && options.unwrapPromises) {
  9073. promiseWarning(fullExp);
  9074. if (!("$$v" in obj)) {
  9075. (function(promise) {
  9076. promise.then(function(val) { promise.$$v = val; }); }
  9077. )(obj);
  9078. }
  9079. if (obj.$$v === undefined) {
  9080. obj.$$v = {};
  9081. }
  9082. obj = obj.$$v;
  9083. }
  9084. }
  9085. key = ensureSafeMemberName(element.shift(), fullExp);
  9086. obj[key] = setValue;
  9087. return setValue;
  9088. }
  9089. var getterFnCache = {};
  9090. /**
  9091. * Implementation of the "Black Hole" variant from:
  9092. * - http://jsperf.com/angularjs-parse-getter/4
  9093. * - http://jsperf.com/path-evaluation-simplified/7
  9094. */
  9095. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  9096. ensureSafeMemberName(key0, fullExp);
  9097. ensureSafeMemberName(key1, fullExp);
  9098. ensureSafeMemberName(key2, fullExp);
  9099. ensureSafeMemberName(key3, fullExp);
  9100. ensureSafeMemberName(key4, fullExp);
  9101. return !options.unwrapPromises
  9102. ? function cspSafeGetter(scope, locals) {
  9103. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  9104. if (pathVal === null || pathVal === undefined) return pathVal;
  9105. pathVal = pathVal[key0];
  9106. if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
  9107. pathVal = pathVal[key1];
  9108. if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
  9109. pathVal = pathVal[key2];
  9110. if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
  9111. pathVal = pathVal[key3];
  9112. if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
  9113. pathVal = pathVal[key4];
  9114. return pathVal;
  9115. }
  9116. : function cspSafePromiseEnabledGetter(scope, locals) {
  9117. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
  9118. promise;
  9119. if (pathVal === null || pathVal === undefined) return pathVal;
  9120. pathVal = pathVal[key0];
  9121. if (pathVal && pathVal.then) {
  9122. promiseWarning(fullExp);
  9123. if (!("$$v" in pathVal)) {
  9124. promise = pathVal;
  9125. promise.$$v = undefined;
  9126. promise.then(function(val) { promise.$$v = val; });
  9127. }
  9128. pathVal = pathVal.$$v;
  9129. }
  9130. if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
  9131. pathVal = pathVal[key1];
  9132. if (pathVal && pathVal.then) {
  9133. promiseWarning(fullExp);
  9134. if (!("$$v" in pathVal)) {
  9135. promise = pathVal;
  9136. promise.$$v = undefined;
  9137. promise.then(function(val) { promise.$$v = val; });
  9138. }
  9139. pathVal = pathVal.$$v;
  9140. }
  9141. if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
  9142. pathVal = pathVal[key2];
  9143. if (pathVal && pathVal.then) {
  9144. promiseWarning(fullExp);
  9145. if (!("$$v" in pathVal)) {
  9146. promise = pathVal;
  9147. promise.$$v = undefined;
  9148. promise.then(function(val) { promise.$$v = val; });
  9149. }
  9150. pathVal = pathVal.$$v;
  9151. }
  9152. if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
  9153. pathVal = pathVal[key3];
  9154. if (pathVal && pathVal.then) {
  9155. promiseWarning(fullExp);
  9156. if (!("$$v" in pathVal)) {
  9157. promise = pathVal;
  9158. promise.$$v = undefined;
  9159. promise.then(function(val) { promise.$$v = val; });
  9160. }
  9161. pathVal = pathVal.$$v;
  9162. }
  9163. if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
  9164. pathVal = pathVal[key4];
  9165. if (pathVal && pathVal.then) {
  9166. promiseWarning(fullExp);
  9167. if (!("$$v" in pathVal)) {
  9168. promise = pathVal;
  9169. promise.$$v = undefined;
  9170. promise.then(function(val) { promise.$$v = val; });
  9171. }
  9172. pathVal = pathVal.$$v;
  9173. }
  9174. return pathVal;
  9175. };
  9176. }
  9177. function getterFn(path, options, fullExp) {
  9178. // Check whether the cache has this getter already.
  9179. // We can use hasOwnProperty directly on the cache because we ensure,
  9180. // see below, that the cache never stores a path called 'hasOwnProperty'
  9181. if (getterFnCache.hasOwnProperty(path)) {
  9182. return getterFnCache[path];
  9183. }
  9184. var pathKeys = path.split('.'),
  9185. pathKeysLength = pathKeys.length,
  9186. fn;
  9187. if (options.csp) {
  9188. if (pathKeysLength < 6) {
  9189. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
  9190. options);
  9191. } else {
  9192. fn = function(scope, locals) {
  9193. var i = 0, val;
  9194. do {
  9195. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  9196. pathKeys[i++], fullExp, options)(scope, locals);
  9197. locals = undefined; // clear after first iteration
  9198. scope = val;
  9199. } while (i < pathKeysLength);
  9200. return val;
  9201. };
  9202. }
  9203. } else {
  9204. var code = 'var l, fn, p;\n';
  9205. forEach(pathKeys, function(key, index) {
  9206. ensureSafeMemberName(key, fullExp);
  9207. code += 'if(s === null || s === undefined) return s;\n' +
  9208. 'l=s;\n' +
  9209. 's='+ (index
  9210. // we simply dereference 's' on any .dot notation
  9211. ? 's'
  9212. // but if we are first then we check locals first, and if so read it first
  9213. : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
  9214. (options.unwrapPromises
  9215. ? 'if (s && s.then) {\n' +
  9216. ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
  9217. ' if (!("$$v" in s)) {\n' +
  9218. ' p=s;\n' +
  9219. ' p.$$v = undefined;\n' +
  9220. ' p.then(function(v) {p.$$v=v;});\n' +
  9221. '}\n' +
  9222. ' s=s.$$v\n' +
  9223. '}\n'
  9224. : '');
  9225. });
  9226. code += 'return s;';
  9227. /* jshint -W054 */
  9228. var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
  9229. /* jshint +W054 */
  9230. evaledFnGetter.toString = function() { return code; };
  9231. fn = function(scope, locals) {
  9232. return evaledFnGetter(scope, locals, promiseWarning);
  9233. };
  9234. }
  9235. // Only cache the value if it's not going to mess up the cache object
  9236. // This is more performant that using Object.prototype.hasOwnProperty.call
  9237. if (path !== 'hasOwnProperty') {
  9238. getterFnCache[path] = fn;
  9239. }
  9240. return fn;
  9241. }
  9242. ///////////////////////////////////
  9243. /**
  9244. * @ngdoc function
  9245. * @name ng.$parse
  9246. * @function
  9247. *
  9248. * @description
  9249. *
  9250. * Converts Angular {@link guide/expression expression} into a function.
  9251. *
  9252. * <pre>
  9253. * var getter = $parse('user.name');
  9254. * var setter = getter.assign;
  9255. * var context = {user:{name:'angular'}};
  9256. * var locals = {user:{name:'local'}};
  9257. *
  9258. * expect(getter(context)).toEqual('angular');
  9259. * setter(context, 'newValue');
  9260. * expect(context.user.name).toEqual('newValue');
  9261. * expect(getter(context, locals)).toEqual('local');
  9262. * </pre>
  9263. *
  9264. *
  9265. * @param {string} expression String expression to compile.
  9266. * @returns {function(context, locals)} a function which represents the compiled expression:
  9267. *
  9268. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  9269. * are evaluated against (typically a scope object).
  9270. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  9271. * `context`.
  9272. *
  9273. * The returned function also has the following properties:
  9274. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  9275. * literal.
  9276. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  9277. * constant literals.
  9278. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  9279. * set to a function to change its value on the given context.
  9280. *
  9281. */
  9282. /**
  9283. * @ngdoc object
  9284. * @name ng.$parseProvider
  9285. * @function
  9286. *
  9287. * @description
  9288. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  9289. * service.
  9290. */
  9291. function $ParseProvider() {
  9292. var cache = {};
  9293. var $parseOptions = {
  9294. csp: false,
  9295. unwrapPromises: false,
  9296. logPromiseWarnings: true
  9297. };
  9298. /**
  9299. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  9300. *
  9301. * @ngdoc method
  9302. * @name ng.$parseProvider#unwrapPromises
  9303. * @methodOf ng.$parseProvider
  9304. * @description
  9305. *
  9306. * **This feature is deprecated, see deprecation notes below for more info**
  9307. *
  9308. * If set to true (default is false), $parse will unwrap promises automatically when a promise is
  9309. * found at any part of the expression. In other words, if set to true, the expression will always
  9310. * result in a non-promise value.
  9311. *
  9312. * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
  9313. * the fulfillment value is used in place of the promise while evaluating the expression.
  9314. *
  9315. * **Deprecation notice**
  9316. *
  9317. * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
  9318. * dichotomy between data access in templates (accessed as raw values) and controller code
  9319. * (accessed as promises).
  9320. *
  9321. * In most code we ended up resolving promises manually in controllers anyway and thus unifying
  9322. * the model access there.
  9323. *
  9324. * Other downsides of automatic promise unwrapping:
  9325. *
  9326. * - when building components it's often desirable to receive the raw promises
  9327. * - adds complexity and slows down expression evaluation
  9328. * - makes expression code pre-generation unattractive due to the amount of code that needs to be
  9329. * generated
  9330. * - makes IDE auto-completion and tool support hard
  9331. *
  9332. * **Warning Logs**
  9333. *
  9334. * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
  9335. * promise (to reduce the noise, each expression is logged only once). To disable this logging use
  9336. * `$parseProvider.logPromiseWarnings(false)` api.
  9337. *
  9338. *
  9339. * @param {boolean=} value New value.
  9340. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  9341. * setter.
  9342. */
  9343. this.unwrapPromises = function(value) {
  9344. if (isDefined(value)) {
  9345. $parseOptions.unwrapPromises = !!value;
  9346. return this;
  9347. } else {
  9348. return $parseOptions.unwrapPromises;
  9349. }
  9350. };
  9351. /**
  9352. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  9353. *
  9354. * @ngdoc method
  9355. * @name ng.$parseProvider#logPromiseWarnings
  9356. * @methodOf ng.$parseProvider
  9357. * @description
  9358. *
  9359. * Controls whether Angular should log a warning on any encounter of a promise in an expression.
  9360. *
  9361. * The default is set to `true`.
  9362. *
  9363. * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
  9364. *
  9365. * @param {boolean=} value New value.
  9366. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  9367. * setter.
  9368. */
  9369. this.logPromiseWarnings = function(value) {
  9370. if (isDefined(value)) {
  9371. $parseOptions.logPromiseWarnings = value;
  9372. return this;
  9373. } else {
  9374. return $parseOptions.logPromiseWarnings;
  9375. }
  9376. };
  9377. this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
  9378. $parseOptions.csp = $sniffer.csp;
  9379. promiseWarning = function promiseWarningFn(fullExp) {
  9380. if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
  9381. promiseWarningCache[fullExp] = true;
  9382. $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
  9383. 'Automatic unwrapping of promises in Angular expressions is deprecated.');
  9384. };
  9385. return function(exp) {
  9386. var parsedExpression;
  9387. switch (typeof exp) {
  9388. case 'string':
  9389. if (cache.hasOwnProperty(exp)) {
  9390. return cache[exp];
  9391. }
  9392. var lexer = new Lexer($parseOptions);
  9393. var parser = new Parser(lexer, $filter, $parseOptions);
  9394. parsedExpression = parser.parse(exp, false);
  9395. if (exp !== 'hasOwnProperty') {
  9396. // Only cache the value if it's not going to mess up the cache object
  9397. // This is more performant that using Object.prototype.hasOwnProperty.call
  9398. cache[exp] = parsedExpression;
  9399. }
  9400. return parsedExpression;
  9401. case 'function':
  9402. return exp;
  9403. default:
  9404. return noop;
  9405. }
  9406. };
  9407. }];
  9408. }
  9409. /**
  9410. * @ngdoc service
  9411. * @name ng.$q
  9412. * @requires $rootScope
  9413. *
  9414. * @description
  9415. * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  9416. *
  9417. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  9418. * interface for interacting with an object that represents the result of an action that is
  9419. * performed asynchronously, and may or may not be finished at any given point in time.
  9420. *
  9421. * From the perspective of dealing with error handling, deferred and promise APIs are to
  9422. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  9423. *
  9424. * <pre>
  9425. * // for the purpose of this example let's assume that variables `$q` and `scope` are
  9426. * // available in the current lexical scope (they could have been injected or passed in).
  9427. *
  9428. * function asyncGreet(name) {
  9429. * var deferred = $q.defer();
  9430. *
  9431. * setTimeout(function() {
  9432. * // since this fn executes async in a future turn of the event loop, we need to wrap
  9433. * // our code into an $apply call so that the model changes are properly observed.
  9434. * scope.$apply(function() {
  9435. * deferred.notify('About to greet ' + name + '.');
  9436. *
  9437. * if (okToGreet(name)) {
  9438. * deferred.resolve('Hello, ' + name + '!');
  9439. * } else {
  9440. * deferred.reject('Greeting ' + name + ' is not allowed.');
  9441. * }
  9442. * });
  9443. * }, 1000);
  9444. *
  9445. * return deferred.promise;
  9446. * }
  9447. *
  9448. * var promise = asyncGreet('Robin Hood');
  9449. * promise.then(function(greeting) {
  9450. * alert('Success: ' + greeting);
  9451. * }, function(reason) {
  9452. * alert('Failed: ' + reason);
  9453. * }, function(update) {
  9454. * alert('Got notification: ' + update);
  9455. * });
  9456. * </pre>
  9457. *
  9458. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  9459. * comes in the way of guarantees that promise and deferred APIs make, see
  9460. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  9461. *
  9462. * Additionally the promise api allows for composition that is very hard to do with the
  9463. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  9464. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  9465. * section on serial or parallel joining of promises.
  9466. *
  9467. *
  9468. * # The Deferred API
  9469. *
  9470. * A new instance of deferred is constructed by calling `$q.defer()`.
  9471. *
  9472. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  9473. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  9474. * of the task.
  9475. *
  9476. * **Methods**
  9477. *
  9478. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  9479. * constructed via `$q.reject`, the promise will be rejected instead.
  9480. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  9481. * resolving it with a rejection constructed via `$q.reject`.
  9482. * - `notify(value)` - provides updates on the status of the promises execution. This may be called
  9483. * multiple times before the promise is either resolved or rejected.
  9484. *
  9485. * **Properties**
  9486. *
  9487. * - promise – `{Promise}` – promise object associated with this deferred.
  9488. *
  9489. *
  9490. * # The Promise API
  9491. *
  9492. * A new promise instance is created when a deferred instance is created and can be retrieved by
  9493. * calling `deferred.promise`.
  9494. *
  9495. * The purpose of the promise object is to allow for interested parties to get access to the result
  9496. * of the deferred task when it completes.
  9497. *
  9498. * **Methods**
  9499. *
  9500. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  9501. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  9502. * as soon as the result is available. The callbacks are called with a single argument: the result
  9503. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  9504. * provide a progress indication, before the promise is resolved or rejected.
  9505. *
  9506. * This method *returns a new promise* which is resolved or rejected via the return value of the
  9507. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  9508. * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
  9509. * method.
  9510. *
  9511. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  9512. *
  9513. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  9514. * but to do so without modifying the final value. This is useful to release resources or do some
  9515. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  9516. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  9517. * more information.
  9518. *
  9519. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  9520. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  9521. * make your code IE8 compatible.
  9522. *
  9523. * # Chaining promises
  9524. *
  9525. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  9526. * possible to create a chain of promises:
  9527. *
  9528. * <pre>
  9529. * promiseB = promiseA.then(function(result) {
  9530. * return result + 1;
  9531. * });
  9532. *
  9533. * // promiseB will be resolved immediately after promiseA is resolved and its value
  9534. * // will be the result of promiseA incremented by 1
  9535. * </pre>
  9536. *
  9537. * It is possible to create chains of any length and since a promise can be resolved with another
  9538. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  9539. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  9540. * $http's response interceptors.
  9541. *
  9542. *
  9543. * # Differences between Kris Kowal's Q and $q
  9544. *
  9545. * There are two main differences:
  9546. *
  9547. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  9548. * mechanism in angular, which means faster propagation of resolution or rejection into your
  9549. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  9550. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  9551. * all the important functionality needed for common async tasks.
  9552. *
  9553. * # Testing
  9554. *
  9555. * <pre>
  9556. * it('should simulate promise', inject(function($q, $rootScope) {
  9557. * var deferred = $q.defer();
  9558. * var promise = deferred.promise;
  9559. * var resolvedValue;
  9560. *
  9561. * promise.then(function(value) { resolvedValue = value; });
  9562. * expect(resolvedValue).toBeUndefined();
  9563. *
  9564. * // Simulate resolving of promise
  9565. * deferred.resolve(123);
  9566. * // Note that the 'then' function does not get called synchronously.
  9567. * // This is because we want the promise API to always be async, whether or not
  9568. * // it got called synchronously or asynchronously.
  9569. * expect(resolvedValue).toBeUndefined();
  9570. *
  9571. * // Propagate promise resolution to 'then' functions using $apply().
  9572. * $rootScope.$apply();
  9573. * expect(resolvedValue).toEqual(123);
  9574. * }));
  9575. * </pre>
  9576. */
  9577. function $QProvider() {
  9578. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  9579. return qFactory(function(callback) {
  9580. $rootScope.$evalAsync(callback);
  9581. }, $exceptionHandler);
  9582. }];
  9583. }
  9584. /**
  9585. * Constructs a promise manager.
  9586. *
  9587. * @param {function(function)} nextTick Function for executing functions in the next turn.
  9588. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  9589. * debugging purposes.
  9590. * @returns {object} Promise manager.
  9591. */
  9592. function qFactory(nextTick, exceptionHandler) {
  9593. /**
  9594. * @ngdoc
  9595. * @name ng.$q#defer
  9596. * @methodOf ng.$q
  9597. * @description
  9598. * Creates a `Deferred` object which represents a task which will finish in the future.
  9599. *
  9600. * @returns {Deferred} Returns a new instance of deferred.
  9601. */
  9602. var defer = function() {
  9603. var pending = [],
  9604. value, deferred;
  9605. deferred = {
  9606. resolve: function(val) {
  9607. if (pending) {
  9608. var callbacks = pending;
  9609. pending = undefined;
  9610. value = ref(val);
  9611. if (callbacks.length) {
  9612. nextTick(function() {
  9613. var callback;
  9614. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  9615. callback = callbacks[i];
  9616. value.then(callback[0], callback[1], callback[2]);
  9617. }
  9618. });
  9619. }
  9620. }
  9621. },
  9622. reject: function(reason) {
  9623. deferred.resolve(reject(reason));
  9624. },
  9625. notify: function(progress) {
  9626. if (pending) {
  9627. var callbacks = pending;
  9628. if (pending.length) {
  9629. nextTick(function() {
  9630. var callback;
  9631. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  9632. callback = callbacks[i];
  9633. callback[2](progress);
  9634. }
  9635. });
  9636. }
  9637. }
  9638. },
  9639. promise: {
  9640. then: function(callback, errback, progressback) {
  9641. var result = defer();
  9642. var wrappedCallback = function(value) {
  9643. try {
  9644. result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
  9645. } catch(e) {
  9646. result.reject(e);
  9647. exceptionHandler(e);
  9648. }
  9649. };
  9650. var wrappedErrback = function(reason) {
  9651. try {
  9652. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  9653. } catch(e) {
  9654. result.reject(e);
  9655. exceptionHandler(e);
  9656. }
  9657. };
  9658. var wrappedProgressback = function(progress) {
  9659. try {
  9660. result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
  9661. } catch(e) {
  9662. exceptionHandler(e);
  9663. }
  9664. };
  9665. if (pending) {
  9666. pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
  9667. } else {
  9668. value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
  9669. }
  9670. return result.promise;
  9671. },
  9672. "catch": function(callback) {
  9673. return this.then(null, callback);
  9674. },
  9675. "finally": function(callback) {
  9676. function makePromise(value, resolved) {
  9677. var result = defer();
  9678. if (resolved) {
  9679. result.resolve(value);
  9680. } else {
  9681. result.reject(value);
  9682. }
  9683. return result.promise;
  9684. }
  9685. function handleCallback(value, isResolved) {
  9686. var callbackOutput = null;
  9687. try {
  9688. callbackOutput = (callback ||defaultCallback)();
  9689. } catch(e) {
  9690. return makePromise(e, false);
  9691. }
  9692. if (callbackOutput && isFunction(callbackOutput.then)) {
  9693. return callbackOutput.then(function() {
  9694. return makePromise(value, isResolved);
  9695. }, function(error) {
  9696. return makePromise(error, false);
  9697. });
  9698. } else {
  9699. return makePromise(value, isResolved);
  9700. }
  9701. }
  9702. return this.then(function(value) {
  9703. return handleCallback(value, true);
  9704. }, function(error) {
  9705. return handleCallback(error, false);
  9706. });
  9707. }
  9708. }
  9709. };
  9710. return deferred;
  9711. };
  9712. var ref = function(value) {
  9713. if (value && isFunction(value.then)) return value;
  9714. return {
  9715. then: function(callback) {
  9716. var result = defer();
  9717. nextTick(function() {
  9718. result.resolve(callback(value));
  9719. });
  9720. return result.promise;
  9721. }
  9722. };
  9723. };
  9724. /**
  9725. * @ngdoc
  9726. * @name ng.$q#reject
  9727. * @methodOf ng.$q
  9728. * @description
  9729. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  9730. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  9731. * a promise chain, you don't need to worry about it.
  9732. *
  9733. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  9734. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  9735. * a promise error callback and you want to forward the error to the promise derived from the
  9736. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  9737. * `reject`.
  9738. *
  9739. * <pre>
  9740. * promiseB = promiseA.then(function(result) {
  9741. * // success: do something and resolve promiseB
  9742. * // with the old or a new result
  9743. * return result;
  9744. * }, function(reason) {
  9745. * // error: handle the error if possible and
  9746. * // resolve promiseB with newPromiseOrValue,
  9747. * // otherwise forward the rejection to promiseB
  9748. * if (canHandle(reason)) {
  9749. * // handle the error and recover
  9750. * return newPromiseOrValue;
  9751. * }
  9752. * return $q.reject(reason);
  9753. * });
  9754. * </pre>
  9755. *
  9756. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  9757. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  9758. */
  9759. var reject = function(reason) {
  9760. return {
  9761. then: function(callback, errback) {
  9762. var result = defer();
  9763. nextTick(function() {
  9764. try {
  9765. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  9766. } catch(e) {
  9767. result.reject(e);
  9768. exceptionHandler(e);
  9769. }
  9770. });
  9771. return result.promise;
  9772. }
  9773. };
  9774. };
  9775. /**
  9776. * @ngdoc
  9777. * @name ng.$q#when
  9778. * @methodOf ng.$q
  9779. * @description
  9780. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  9781. * This is useful when you are dealing with an object that might or might not be a promise, or if
  9782. * the promise comes from a source that can't be trusted.
  9783. *
  9784. * @param {*} value Value or a promise
  9785. * @returns {Promise} Returns a promise of the passed value or promise
  9786. */
  9787. var when = function(value, callback, errback, progressback) {
  9788. var result = defer(),
  9789. done;
  9790. var wrappedCallback = function(value) {
  9791. try {
  9792. return (isFunction(callback) ? callback : defaultCallback)(value);
  9793. } catch (e) {
  9794. exceptionHandler(e);
  9795. return reject(e);
  9796. }
  9797. };
  9798. var wrappedErrback = function(reason) {
  9799. try {
  9800. return (isFunction(errback) ? errback : defaultErrback)(reason);
  9801. } catch (e) {
  9802. exceptionHandler(e);
  9803. return reject(e);
  9804. }
  9805. };
  9806. var wrappedProgressback = function(progress) {
  9807. try {
  9808. return (isFunction(progressback) ? progressback : defaultCallback)(progress);
  9809. } catch (e) {
  9810. exceptionHandler(e);
  9811. }
  9812. };
  9813. nextTick(function() {
  9814. ref(value).then(function(value) {
  9815. if (done) return;
  9816. done = true;
  9817. result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
  9818. }, function(reason) {
  9819. if (done) return;
  9820. done = true;
  9821. result.resolve(wrappedErrback(reason));
  9822. }, function(progress) {
  9823. if (done) return;
  9824. result.notify(wrappedProgressback(progress));
  9825. });
  9826. });
  9827. return result.promise;
  9828. };
  9829. function defaultCallback(value) {
  9830. return value;
  9831. }
  9832. function defaultErrback(reason) {
  9833. return reject(reason);
  9834. }
  9835. /**
  9836. * @ngdoc
  9837. * @name ng.$q#all
  9838. * @methodOf ng.$q
  9839. * @description
  9840. * Combines multiple promises into a single promise that is resolved when all of the input
  9841. * promises are resolved.
  9842. *
  9843. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  9844. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  9845. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  9846. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  9847. * with the same rejection value.
  9848. */
  9849. function all(promises) {
  9850. var deferred = defer(),
  9851. counter = 0,
  9852. results = isArray(promises) ? [] : {};
  9853. forEach(promises, function(promise, key) {
  9854. counter++;
  9855. ref(promise).then(function(value) {
  9856. if (results.hasOwnProperty(key)) return;
  9857. results[key] = value;
  9858. if (!(--counter)) deferred.resolve(results);
  9859. }, function(reason) {
  9860. if (results.hasOwnProperty(key)) return;
  9861. deferred.reject(reason);
  9862. });
  9863. });
  9864. if (counter === 0) {
  9865. deferred.resolve(results);
  9866. }
  9867. return deferred.promise;
  9868. }
  9869. return {
  9870. defer: defer,
  9871. reject: reject,
  9872. when: when,
  9873. all: all
  9874. };
  9875. }
  9876. /**
  9877. * DESIGN NOTES
  9878. *
  9879. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  9880. *
  9881. * The typical use of scope is to watch the expressions, which most of the time return the same
  9882. * value as last time so we optimize the operation.
  9883. *
  9884. * Closures construction is expensive in terms of speed as well as memory:
  9885. * - No closures, instead use prototypical inheritance for API
  9886. * - Internal state needs to be stored on scope directly, which means that private state is
  9887. * exposed as $$____ properties
  9888. *
  9889. * Loop operations are optimized by using while(count--) { ... }
  9890. * - this means that in order to keep the same order of execution as addition we have to add
  9891. * items to the array at the beginning (shift) instead of at the end (push)
  9892. *
  9893. * Child scopes are created and removed often
  9894. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  9895. *
  9896. * There are few watches then a lot of observers. This is why you don't want the observer to be
  9897. * implemented in the same way as watch. Watch requires return of initialization function which
  9898. * are expensive to construct.
  9899. */
  9900. /**
  9901. * @ngdoc object
  9902. * @name ng.$rootScopeProvider
  9903. * @description
  9904. *
  9905. * Provider for the $rootScope service.
  9906. */
  9907. /**
  9908. * @ngdoc function
  9909. * @name ng.$rootScopeProvider#digestTtl
  9910. * @methodOf ng.$rootScopeProvider
  9911. * @description
  9912. *
  9913. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  9914. * assuming that the model is unstable.
  9915. *
  9916. * The current default is 10 iterations.
  9917. *
  9918. * In complex applications it's possible that the dependencies between `$watch`s will result in
  9919. * several digest iterations. However if an application needs more than the default 10 digest
  9920. * iterations for its model to stabilize then you should investigate what is causing the model to
  9921. * continuously change during the digest.
  9922. *
  9923. * Increasing the TTL could have performance implications, so you should not change it without
  9924. * proper justification.
  9925. *
  9926. * @param {number} limit The number of digest iterations.
  9927. */
  9928. /**
  9929. * @ngdoc object
  9930. * @name ng.$rootScope
  9931. * @description
  9932. *
  9933. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  9934. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  9935. * between the model and the view, via a mechanism for watching the model for changes.
  9936. * They also provide an event emission/broadcast and subscription facility. See the
  9937. * {@link guide/scope developer guide on scopes}.
  9938. */
  9939. function $RootScopeProvider(){
  9940. var TTL = 10;
  9941. var $rootScopeMinErr = minErr('$rootScope');
  9942. var lastDirtyWatch = null;
  9943. this.digestTtl = function(value) {
  9944. if (arguments.length) {
  9945. TTL = value;
  9946. }
  9947. return TTL;
  9948. };
  9949. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  9950. function( $injector, $exceptionHandler, $parse, $browser) {
  9951. /**
  9952. * @ngdoc function
  9953. * @name ng.$rootScope.Scope
  9954. *
  9955. * @description
  9956. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  9957. * {@link AUTO.$injector $injector}. Child scopes are created using the
  9958. * {@link ng.$rootScope.Scope#methods_$new $new()} method. (Most scopes are created automatically when
  9959. * compiled HTML template is executed.)
  9960. *
  9961. * Here is a simple scope snippet to show how you can interact with the scope.
  9962. * <pre>
  9963. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  9964. * </pre>
  9965. *
  9966. * # Inheritance
  9967. * A scope can inherit from a parent scope, as in this example:
  9968. * <pre>
  9969. var parent = $rootScope;
  9970. var child = parent.$new();
  9971. parent.salutation = "Hello";
  9972. child.name = "World";
  9973. expect(child.salutation).toEqual('Hello');
  9974. child.salutation = "Welcome";
  9975. expect(child.salutation).toEqual('Welcome');
  9976. expect(parent.salutation).toEqual('Hello');
  9977. * </pre>
  9978. *
  9979. *
  9980. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  9981. * provided for the current scope. Defaults to {@link ng}.
  9982. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  9983. * append/override services provided by `providers`. This is handy
  9984. * when unit-testing and having the need to override a default
  9985. * service.
  9986. * @returns {Object} Newly created scope.
  9987. *
  9988. */
  9989. function Scope() {
  9990. this.$id = nextUid();
  9991. this.$$phase = this.$parent = this.$$watchers =
  9992. this.$$nextSibling = this.$$prevSibling =
  9993. this.$$childHead = this.$$childTail = null;
  9994. this['this'] = this.$root = this;
  9995. this.$$destroyed = false;
  9996. this.$$asyncQueue = [];
  9997. this.$$postDigestQueue = [];
  9998. this.$$listeners = {};
  9999. this.$$isolateBindings = {};
  10000. }
  10001. /**
  10002. * @ngdoc property
  10003. * @name ng.$rootScope.Scope#$id
  10004. * @propertyOf ng.$rootScope.Scope
  10005. * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
  10006. * debugging.
  10007. */
  10008. Scope.prototype = {
  10009. constructor: Scope,
  10010. /**
  10011. * @ngdoc function
  10012. * @name ng.$rootScope.Scope#$new
  10013. * @methodOf ng.$rootScope.Scope
  10014. * @function
  10015. *
  10016. * @description
  10017. * Creates a new child {@link ng.$rootScope.Scope scope}.
  10018. *
  10019. * The parent scope will propagate the {@link ng.$rootScope.Scope#methods_$digest $digest()} and
  10020. * {@link ng.$rootScope.Scope#methods_$digest $digest()} events. The scope can be removed from the
  10021. * scope hierarchy using {@link ng.$rootScope.Scope#methods_$destroy $destroy()}.
  10022. *
  10023. * {@link ng.$rootScope.Scope#methods_$destroy $destroy()} must be called on a scope when it is
  10024. * desired for the scope and its child scopes to be permanently detached from the parent and
  10025. * thus stop participating in model change detection and listener notification by invoking.
  10026. *
  10027. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  10028. * parent scope. The scope is isolated, as it can not see parent scope properties.
  10029. * When creating widgets, it is useful for the widget to not accidentally read parent
  10030. * state.
  10031. *
  10032. * @returns {Object} The newly created child scope.
  10033. *
  10034. */
  10035. $new: function(isolate) {
  10036. var ChildScope,
  10037. child;
  10038. if (isolate) {
  10039. child = new Scope();
  10040. child.$root = this.$root;
  10041. // ensure that there is just one async queue per $rootScope and its children
  10042. child.$$asyncQueue = this.$$asyncQueue;
  10043. child.$$postDigestQueue = this.$$postDigestQueue;
  10044. } else {
  10045. ChildScope = function() {}; // should be anonymous; This is so that when the minifier munges
  10046. // the name it does not become random set of chars. This will then show up as class
  10047. // name in the debugger.
  10048. ChildScope.prototype = this;
  10049. child = new ChildScope();
  10050. child.$id = nextUid();
  10051. }
  10052. child['this'] = child;
  10053. child.$$listeners = {};
  10054. child.$parent = this;
  10055. child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
  10056. child.$$prevSibling = this.$$childTail;
  10057. if (this.$$childHead) {
  10058. this.$$childTail.$$nextSibling = child;
  10059. this.$$childTail = child;
  10060. } else {
  10061. this.$$childHead = this.$$childTail = child;
  10062. }
  10063. return child;
  10064. },
  10065. /**
  10066. * @ngdoc function
  10067. * @name ng.$rootScope.Scope#$watch
  10068. * @methodOf ng.$rootScope.Scope
  10069. * @function
  10070. *
  10071. * @description
  10072. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  10073. *
  10074. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#methods_$digest
  10075. * $digest()} and should return the value that will be watched. (Since
  10076. * {@link ng.$rootScope.Scope#methods_$digest $digest()} reruns when it detects changes the
  10077. * `watchExpression` can execute multiple times per
  10078. * {@link ng.$rootScope.Scope#methods_$digest $digest()} and should be idempotent.)
  10079. * - The `listener` is called only when the value from the current `watchExpression` and the
  10080. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  10081. * see below). The inequality is determined according to
  10082. * {@link angular.equals} function. To save the value of the object for later comparison,
  10083. * the {@link angular.copy} function is used. It also means that watching complex options
  10084. * will have adverse memory and performance implications.
  10085. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  10086. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  10087. * iteration limit is 10 to prevent an infinite loop deadlock.
  10088. *
  10089. *
  10090. * If you want to be notified whenever {@link ng.$rootScope.Scope#methods_$digest $digest} is called,
  10091. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  10092. * can execute multiple times per {@link ng.$rootScope.Scope#methods_$digest $digest} cycle when a
  10093. * change is detected, be prepared for multiple calls to your listener.)
  10094. *
  10095. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  10096. * (via {@link ng.$rootScope.Scope#methods_$evalAsync $evalAsync}) to initialize the
  10097. * watcher. In rare cases, this is undesirable because the listener is called when the result
  10098. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  10099. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  10100. * listener was called due to initialization.
  10101. *
  10102. * The example below contains an illustration of using a function as your $watch listener
  10103. *
  10104. *
  10105. * # Example
  10106. * <pre>
  10107. // let's assume that scope was dependency injected as the $rootScope
  10108. var scope = $rootScope;
  10109. scope.name = 'misko';
  10110. scope.counter = 0;
  10111. expect(scope.counter).toEqual(0);
  10112. scope.$watch('name', function(newValue, oldValue) {
  10113. scope.counter = scope.counter + 1;
  10114. });
  10115. expect(scope.counter).toEqual(0);
  10116. scope.$digest();
  10117. // no variable change
  10118. expect(scope.counter).toEqual(0);
  10119. scope.name = 'adam';
  10120. scope.$digest();
  10121. expect(scope.counter).toEqual(1);
  10122. // Using a listener function
  10123. var food;
  10124. scope.foodCounter = 0;
  10125. expect(scope.foodCounter).toEqual(0);
  10126. scope.$watch(
  10127. // This is the listener function
  10128. function() { return food; },
  10129. // This is the change handler
  10130. function(newValue, oldValue) {
  10131. if ( newValue !== oldValue ) {
  10132. // Only increment the counter if the value changed
  10133. scope.foodCounter = scope.foodCounter + 1;
  10134. }
  10135. }
  10136. );
  10137. // No digest has been run so the counter will be zero
  10138. expect(scope.foodCounter).toEqual(0);
  10139. // Run the digest but since food has not changed cout will still be zero
  10140. scope.$digest();
  10141. expect(scope.foodCounter).toEqual(0);
  10142. // Update food and run digest. Now the counter will increment
  10143. food = 'cheeseburger';
  10144. scope.$digest();
  10145. expect(scope.foodCounter).toEqual(1);
  10146. * </pre>
  10147. *
  10148. *
  10149. *
  10150. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  10151. * {@link ng.$rootScope.Scope#methods_$digest $digest} cycle. A change in the return value triggers
  10152. * a call to the `listener`.
  10153. *
  10154. * - `string`: Evaluated as {@link guide/expression expression}
  10155. * - `function(scope)`: called with current `scope` as a parameter.
  10156. * @param {(function()|string)=} listener Callback called whenever the return value of
  10157. * the `watchExpression` changes.
  10158. *
  10159. * - `string`: Evaluated as {@link guide/expression expression}
  10160. * - `function(newValue, oldValue, scope)`: called with current and previous values as
  10161. * parameters.
  10162. *
  10163. * @param {boolean=} objectEquality Compare object for equality rather than for reference.
  10164. * @returns {function()} Returns a deregistration function for this listener.
  10165. */
  10166. $watch: function(watchExp, listener, objectEquality) {
  10167. var scope = this,
  10168. get = compileToFn(watchExp, 'watch'),
  10169. array = scope.$$watchers,
  10170. watcher = {
  10171. fn: listener,
  10172. last: initWatchVal,
  10173. get: get,
  10174. exp: watchExp,
  10175. eq: !!objectEquality
  10176. };
  10177. lastDirtyWatch = null;
  10178. // in the case user pass string, we need to compile it, do we really need this ?
  10179. if (!isFunction(listener)) {
  10180. var listenFn = compileToFn(listener || noop, 'listener');
  10181. watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
  10182. }
  10183. if (typeof watchExp == 'string' && get.constant) {
  10184. var originalFn = watcher.fn;
  10185. watcher.fn = function(newVal, oldVal, scope) {
  10186. originalFn.call(this, newVal, oldVal, scope);
  10187. arrayRemove(array, watcher);
  10188. };
  10189. }
  10190. if (!array) {
  10191. array = scope.$$watchers = [];
  10192. }
  10193. // we use unshift since we use a while loop in $digest for speed.
  10194. // the while loop reads in reverse order.
  10195. array.unshift(watcher);
  10196. return function() {
  10197. arrayRemove(array, watcher);
  10198. };
  10199. },
  10200. /**
  10201. * @ngdoc function
  10202. * @name ng.$rootScope.Scope#$watchCollection
  10203. * @methodOf ng.$rootScope.Scope
  10204. * @function
  10205. *
  10206. * @description
  10207. * Shallow watches the properties of an object and fires whenever any of the properties change
  10208. * (for arrays, this implies watching the array items; for object maps, this implies watching
  10209. * the properties). If a change is detected, the `listener` callback is fired.
  10210. *
  10211. * - The `obj` collection is observed via standard $watch operation and is examined on every
  10212. * call to $digest() to see if any items have been added, removed, or moved.
  10213. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  10214. * adding, removing, and moving items belonging to an object or array.
  10215. *
  10216. *
  10217. * # Example
  10218. * <pre>
  10219. $scope.names = ['igor', 'matias', 'misko', 'james'];
  10220. $scope.dataCount = 4;
  10221. $scope.$watchCollection('names', function(newNames, oldNames) {
  10222. $scope.dataCount = newNames.length;
  10223. });
  10224. expect($scope.dataCount).toEqual(4);
  10225. $scope.$digest();
  10226. //still at 4 ... no changes
  10227. expect($scope.dataCount).toEqual(4);
  10228. $scope.names.pop();
  10229. $scope.$digest();
  10230. //now there's been a change
  10231. expect($scope.dataCount).toEqual(3);
  10232. * </pre>
  10233. *
  10234. *
  10235. * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The
  10236. * expression value should evaluate to an object or an array which is observed on each
  10237. * {@link ng.$rootScope.Scope#methods_$digest $digest} cycle. Any shallow change within the
  10238. * collection will trigger a call to the `listener`.
  10239. *
  10240. * @param {function(newCollection, oldCollection, scope)} listener a callback function that is
  10241. * fired with both the `newCollection` and `oldCollection` as parameters.
  10242. * The `newCollection` object is the newly modified data obtained from the `obj` expression
  10243. * and the `oldCollection` object is a copy of the former collection data.
  10244. * The `scope` refers to the current scope.
  10245. *
  10246. * @returns {function()} Returns a de-registration function for this listener. When the
  10247. * de-registration function is executed, the internal watch operation is terminated.
  10248. */
  10249. $watchCollection: function(obj, listener) {
  10250. var self = this;
  10251. var oldValue;
  10252. var newValue;
  10253. var changeDetected = 0;
  10254. var objGetter = $parse(obj);
  10255. var internalArray = [];
  10256. var internalObject = {};
  10257. var oldLength = 0;
  10258. function $watchCollectionWatch() {
  10259. newValue = objGetter(self);
  10260. var newLength, key;
  10261. if (!isObject(newValue)) {
  10262. if (oldValue !== newValue) {
  10263. oldValue = newValue;
  10264. changeDetected++;
  10265. }
  10266. } else if (isArrayLike(newValue)) {
  10267. if (oldValue !== internalArray) {
  10268. // we are transitioning from something which was not an array into array.
  10269. oldValue = internalArray;
  10270. oldLength = oldValue.length = 0;
  10271. changeDetected++;
  10272. }
  10273. newLength = newValue.length;
  10274. if (oldLength !== newLength) {
  10275. // if lengths do not match we need to trigger change notification
  10276. changeDetected++;
  10277. oldValue.length = oldLength = newLength;
  10278. }
  10279. // copy the items to oldValue and look for changes.
  10280. for (var i = 0; i < newLength; i++) {
  10281. if (oldValue[i] !== newValue[i]) {
  10282. changeDetected++;
  10283. oldValue[i] = newValue[i];
  10284. }
  10285. }
  10286. } else {
  10287. if (oldValue !== internalObject) {
  10288. // we are transitioning from something which was not an object into object.
  10289. oldValue = internalObject = {};
  10290. oldLength = 0;
  10291. changeDetected++;
  10292. }
  10293. // copy the items to oldValue and look for changes.
  10294. newLength = 0;
  10295. for (key in newValue) {
  10296. if (newValue.hasOwnProperty(key)) {
  10297. newLength++;
  10298. if (oldValue.hasOwnProperty(key)) {
  10299. if (oldValue[key] !== newValue[key]) {
  10300. changeDetected++;
  10301. oldValue[key] = newValue[key];
  10302. }
  10303. } else {
  10304. oldLength++;
  10305. oldValue[key] = newValue[key];
  10306. changeDetected++;
  10307. }
  10308. }
  10309. }
  10310. if (oldLength > newLength) {
  10311. // we used to have more keys, need to find them and destroy them.
  10312. changeDetected++;
  10313. for(key in oldValue) {
  10314. if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
  10315. oldLength--;
  10316. delete oldValue[key];
  10317. }
  10318. }
  10319. }
  10320. }
  10321. return changeDetected;
  10322. }
  10323. function $watchCollectionAction() {
  10324. listener(newValue, oldValue, self);
  10325. }
  10326. return this.$watch($watchCollectionWatch, $watchCollectionAction);
  10327. },
  10328. /**
  10329. * @ngdoc function
  10330. * @name ng.$rootScope.Scope#$digest
  10331. * @methodOf ng.$rootScope.Scope
  10332. * @function
  10333. *
  10334. * @description
  10335. * Processes all of the {@link ng.$rootScope.Scope#methods_$watch watchers} of the current scope and
  10336. * its children. Because a {@link ng.$rootScope.Scope#methods_$watch watcher}'s listener can change
  10337. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#methods_$watch watchers}
  10338. * until no more listeners are firing. This means that it is possible to get into an infinite
  10339. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  10340. * iterations exceeds 10.
  10341. *
  10342. * Usually, you don't call `$digest()` directly in
  10343. * {@link ng.directive:ngController controllers} or in
  10344. * {@link ng.$compileProvider#methods_directive directives}.
  10345. * Instead, you should call {@link ng.$rootScope.Scope#methods_$apply $apply()} (typically from within
  10346. * a {@link ng.$compileProvider#methods_directive directives}), which will force a `$digest()`.
  10347. *
  10348. * If you want to be notified whenever `$digest()` is called,
  10349. * you can register a `watchExpression` function with
  10350. * {@link ng.$rootScope.Scope#methods_$watch $watch()} with no `listener`.
  10351. *
  10352. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  10353. *
  10354. * # Example
  10355. * <pre>
  10356. var scope = ...;
  10357. scope.name = 'misko';
  10358. scope.counter = 0;
  10359. expect(scope.counter).toEqual(0);
  10360. scope.$watch('name', function(newValue, oldValue) {
  10361. scope.counter = scope.counter + 1;
  10362. });
  10363. expect(scope.counter).toEqual(0);
  10364. scope.$digest();
  10365. // no variable change
  10366. expect(scope.counter).toEqual(0);
  10367. scope.name = 'adam';
  10368. scope.$digest();
  10369. expect(scope.counter).toEqual(1);
  10370. * </pre>
  10371. *
  10372. */
  10373. $digest: function() {
  10374. var watch, value, last,
  10375. watchers,
  10376. asyncQueue = this.$$asyncQueue,
  10377. postDigestQueue = this.$$postDigestQueue,
  10378. length,
  10379. dirty, ttl = TTL,
  10380. next, current, target = this,
  10381. watchLog = [],
  10382. logIdx, logMsg, asyncTask;
  10383. beginPhase('$digest');
  10384. lastDirtyWatch = null;
  10385. do { // "while dirty" loop
  10386. dirty = false;
  10387. current = target;
  10388. while(asyncQueue.length) {
  10389. try {
  10390. asyncTask = asyncQueue.shift();
  10391. asyncTask.scope.$eval(asyncTask.expression);
  10392. } catch (e) {
  10393. clearPhase();
  10394. $exceptionHandler(e);
  10395. }
  10396. lastDirtyWatch = null;
  10397. }
  10398. traverseScopesLoop:
  10399. do { // "traverse the scopes" loop
  10400. if ((watchers = current.$$watchers)) {
  10401. // process our watches
  10402. length = watchers.length;
  10403. while (length--) {
  10404. try {
  10405. watch = watchers[length];
  10406. // Most common watches are on primitives, in which case we can short
  10407. // circuit it with === operator, only when === fails do we use .equals
  10408. if (watch) {
  10409. if ((value = watch.get(current)) !== (last = watch.last) &&
  10410. !(watch.eq
  10411. ? equals(value, last)
  10412. : (typeof value == 'number' && typeof last == 'number'
  10413. && isNaN(value) && isNaN(last)))) {
  10414. dirty = true;
  10415. lastDirtyWatch = watch;
  10416. watch.last = watch.eq ? copy(value) : value;
  10417. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  10418. if (ttl < 5) {
  10419. logIdx = 4 - ttl;
  10420. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  10421. logMsg = (isFunction(watch.exp))
  10422. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  10423. : watch.exp;
  10424. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  10425. watchLog[logIdx].push(logMsg);
  10426. }
  10427. } else if (watch === lastDirtyWatch) {
  10428. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  10429. // have already been tested.
  10430. dirty = false;
  10431. break traverseScopesLoop;
  10432. }
  10433. }
  10434. } catch (e) {
  10435. clearPhase();
  10436. $exceptionHandler(e);
  10437. }
  10438. }
  10439. }
  10440. // Insanity Warning: scope depth-first traversal
  10441. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  10442. // this piece should be kept in sync with the traversal in $broadcast
  10443. if (!(next = (current.$$childHead ||
  10444. (current !== target && current.$$nextSibling)))) {
  10445. while(current !== target && !(next = current.$$nextSibling)) {
  10446. current = current.$parent;
  10447. }
  10448. }
  10449. } while ((current = next));
  10450. // `break traverseScopesLoop;` takes us to here
  10451. if(dirty && !(ttl--)) {
  10452. clearPhase();
  10453. throw $rootScopeMinErr('infdig',
  10454. '{0} $digest() iterations reached. Aborting!\n' +
  10455. 'Watchers fired in the last 5 iterations: {1}',
  10456. TTL, toJson(watchLog));
  10457. }
  10458. } while (dirty || asyncQueue.length);
  10459. clearPhase();
  10460. while(postDigestQueue.length) {
  10461. try {
  10462. postDigestQueue.shift()();
  10463. } catch (e) {
  10464. $exceptionHandler(e);
  10465. }
  10466. }
  10467. },
  10468. /**
  10469. * @ngdoc event
  10470. * @name ng.$rootScope.Scope#$destroy
  10471. * @eventOf ng.$rootScope.Scope
  10472. * @eventType broadcast on scope being destroyed
  10473. *
  10474. * @description
  10475. * Broadcasted when a scope and its children are being destroyed.
  10476. *
  10477. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  10478. * clean up DOM bindings before an element is removed from the DOM.
  10479. */
  10480. /**
  10481. * @ngdoc function
  10482. * @name ng.$rootScope.Scope#$destroy
  10483. * @methodOf ng.$rootScope.Scope
  10484. * @function
  10485. *
  10486. * @description
  10487. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  10488. * that calls to {@link ng.$rootScope.Scope#methods_$digest $digest()} will no longer
  10489. * propagate to the current scope and its children. Removal also implies that the current
  10490. * scope is eligible for garbage collection.
  10491. *
  10492. * The `$destroy()` is usually used by directives such as
  10493. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  10494. * unrolling of the loop.
  10495. *
  10496. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  10497. * Application code can register a `$destroy` event handler that will give it a chance to
  10498. * perform any necessary cleanup.
  10499. *
  10500. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  10501. * clean up DOM bindings before an element is removed from the DOM.
  10502. */
  10503. $destroy: function() {
  10504. // we can't destroy the root scope or a scope that has been already destroyed
  10505. if (this.$$destroyed) return;
  10506. var parent = this.$parent;
  10507. this.$broadcast('$destroy');
  10508. this.$$destroyed = true;
  10509. if (this === $rootScope) return;
  10510. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  10511. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  10512. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  10513. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  10514. // This is bogus code that works around Chrome's GC leak
  10515. // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  10516. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  10517. this.$$childTail = null;
  10518. },
  10519. /**
  10520. * @ngdoc function
  10521. * @name ng.$rootScope.Scope#$eval
  10522. * @methodOf ng.$rootScope.Scope
  10523. * @function
  10524. *
  10525. * @description
  10526. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  10527. * the expression are propagated (uncaught). This is useful when evaluating Angular
  10528. * expressions.
  10529. *
  10530. * # Example
  10531. * <pre>
  10532. var scope = ng.$rootScope.Scope();
  10533. scope.a = 1;
  10534. scope.b = 2;
  10535. expect(scope.$eval('a+b')).toEqual(3);
  10536. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  10537. * </pre>
  10538. *
  10539. * @param {(string|function())=} expression An angular expression to be executed.
  10540. *
  10541. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  10542. * - `function(scope)`: execute the function with the current `scope` parameter.
  10543. *
  10544. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  10545. * @returns {*} The result of evaluating the expression.
  10546. */
  10547. $eval: function(expr, locals) {
  10548. return $parse(expr)(this, locals);
  10549. },
  10550. /**
  10551. * @ngdoc function
  10552. * @name ng.$rootScope.Scope#$evalAsync
  10553. * @methodOf ng.$rootScope.Scope
  10554. * @function
  10555. *
  10556. * @description
  10557. * Executes the expression on the current scope at a later point in time.
  10558. *
  10559. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  10560. * that:
  10561. *
  10562. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  10563. * rendering).
  10564. * - at least one {@link ng.$rootScope.Scope#methods_$digest $digest cycle} will be performed after
  10565. * `expression` execution.
  10566. *
  10567. * Any exceptions from the execution of the expression are forwarded to the
  10568. * {@link ng.$exceptionHandler $exceptionHandler} service.
  10569. *
  10570. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  10571. * will be scheduled. However, it is encouraged to always call code that changes the model
  10572. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  10573. *
  10574. * @param {(string|function())=} expression An angular expression to be executed.
  10575. *
  10576. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  10577. * - `function(scope)`: execute the function with the current `scope` parameter.
  10578. *
  10579. */
  10580. $evalAsync: function(expr) {
  10581. // if we are outside of an $digest loop and this is the first time we are scheduling async
  10582. // task also schedule async auto-flush
  10583. if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
  10584. $browser.defer(function() {
  10585. if ($rootScope.$$asyncQueue.length) {
  10586. $rootScope.$digest();
  10587. }
  10588. });
  10589. }
  10590. this.$$asyncQueue.push({scope: this, expression: expr});
  10591. },
  10592. $$postDigest : function(fn) {
  10593. this.$$postDigestQueue.push(fn);
  10594. },
  10595. /**
  10596. * @ngdoc function
  10597. * @name ng.$rootScope.Scope#$apply
  10598. * @methodOf ng.$rootScope.Scope
  10599. * @function
  10600. *
  10601. * @description
  10602. * `$apply()` is used to execute an expression in angular from outside of the angular
  10603. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  10604. * Because we are calling into the angular framework we need to perform proper scope life
  10605. * cycle of {@link ng.$exceptionHandler exception handling},
  10606. * {@link ng.$rootScope.Scope#methods_$digest executing watches}.
  10607. *
  10608. * ## Life cycle
  10609. *
  10610. * # Pseudo-Code of `$apply()`
  10611. * <pre>
  10612. function $apply(expr) {
  10613. try {
  10614. return $eval(expr);
  10615. } catch (e) {
  10616. $exceptionHandler(e);
  10617. } finally {
  10618. $root.$digest();
  10619. }
  10620. }
  10621. * </pre>
  10622. *
  10623. *
  10624. * Scope's `$apply()` method transitions through the following stages:
  10625. *
  10626. * 1. The {@link guide/expression expression} is executed using the
  10627. * {@link ng.$rootScope.Scope#methods_$eval $eval()} method.
  10628. * 2. Any exceptions from the execution of the expression are forwarded to the
  10629. * {@link ng.$exceptionHandler $exceptionHandler} service.
  10630. * 3. The {@link ng.$rootScope.Scope#methods_$watch watch} listeners are fired immediately after the
  10631. * expression was executed using the {@link ng.$rootScope.Scope#methods_$digest $digest()} method.
  10632. *
  10633. *
  10634. * @param {(string|function())=} exp An angular expression to be executed.
  10635. *
  10636. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  10637. * - `function(scope)`: execute the function with current `scope` parameter.
  10638. *
  10639. * @returns {*} The result of evaluating the expression.
  10640. */
  10641. $apply: function(expr) {
  10642. try {
  10643. beginPhase('$apply');
  10644. return this.$eval(expr);
  10645. } catch (e) {
  10646. $exceptionHandler(e);
  10647. } finally {
  10648. clearPhase();
  10649. try {
  10650. $rootScope.$digest();
  10651. } catch (e) {
  10652. $exceptionHandler(e);
  10653. throw e;
  10654. }
  10655. }
  10656. },
  10657. /**
  10658. * @ngdoc function
  10659. * @name ng.$rootScope.Scope#$on
  10660. * @methodOf ng.$rootScope.Scope
  10661. * @function
  10662. *
  10663. * @description
  10664. * Listens on events of a given type. See {@link ng.$rootScope.Scope#methods_$emit $emit} for
  10665. * discussion of event life cycle.
  10666. *
  10667. * The event listener function format is: `function(event, args...)`. The `event` object
  10668. * passed into the listener has the following attributes:
  10669. *
  10670. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  10671. * `$broadcast`-ed.
  10672. * - `currentScope` - `{Scope}`: the current scope which is handling the event.
  10673. * - `name` - `{string}`: name of the event.
  10674. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  10675. * further event propagation (available only for events that were `$emit`-ed).
  10676. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  10677. * to true.
  10678. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  10679. *
  10680. * @param {string} name Event name to listen on.
  10681. * @param {function(event, args...)} listener Function to call when the event is emitted.
  10682. * @returns {function()} Returns a deregistration function for this listener.
  10683. */
  10684. $on: function(name, listener) {
  10685. var namedListeners = this.$$listeners[name];
  10686. if (!namedListeners) {
  10687. this.$$listeners[name] = namedListeners = [];
  10688. }
  10689. namedListeners.push(listener);
  10690. return function() {
  10691. namedListeners[indexOf(namedListeners, listener)] = null;
  10692. };
  10693. },
  10694. /**
  10695. * @ngdoc function
  10696. * @name ng.$rootScope.Scope#$emit
  10697. * @methodOf ng.$rootScope.Scope
  10698. * @function
  10699. *
  10700. * @description
  10701. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  10702. * registered {@link ng.$rootScope.Scope#methods_$on} listeners.
  10703. *
  10704. * The event life cycle starts at the scope on which `$emit` was called. All
  10705. * {@link ng.$rootScope.Scope#methods_$on listeners} listening for `name` event on this scope get
  10706. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  10707. * registered listeners along the way. The event will stop propagating if one of the listeners
  10708. * cancels it.
  10709. *
  10710. * Any exception emitted from the {@link ng.$rootScope.Scope#methods_$on listeners} will be passed
  10711. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  10712. *
  10713. * @param {string} name Event name to emit.
  10714. * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
  10715. * @return {Object} Event object (see {@link ng.$rootScope.Scope#methods_$on}).
  10716. */
  10717. $emit: function(name, args) {
  10718. var empty = [],
  10719. namedListeners,
  10720. scope = this,
  10721. stopPropagation = false,
  10722. event = {
  10723. name: name,
  10724. targetScope: scope,
  10725. stopPropagation: function() {stopPropagation = true;},
  10726. preventDefault: function() {
  10727. event.defaultPrevented = true;
  10728. },
  10729. defaultPrevented: false
  10730. },
  10731. listenerArgs = concat([event], arguments, 1),
  10732. i, length;
  10733. do {
  10734. namedListeners = scope.$$listeners[name] || empty;
  10735. event.currentScope = scope;
  10736. for (i=0, length=namedListeners.length; i<length; i++) {
  10737. // if listeners were deregistered, defragment the array
  10738. if (!namedListeners[i]) {
  10739. namedListeners.splice(i, 1);
  10740. i--;
  10741. length--;
  10742. continue;
  10743. }
  10744. try {
  10745. //allow all listeners attached to the current scope to run
  10746. namedListeners[i].apply(null, listenerArgs);
  10747. } catch (e) {
  10748. $exceptionHandler(e);
  10749. }
  10750. }
  10751. //if any listener on the current scope stops propagation, prevent bubbling
  10752. if (stopPropagation) return event;
  10753. //traverse upwards
  10754. scope = scope.$parent;
  10755. } while (scope);
  10756. return event;
  10757. },
  10758. /**
  10759. * @ngdoc function
  10760. * @name ng.$rootScope.Scope#$broadcast
  10761. * @methodOf ng.$rootScope.Scope
  10762. * @function
  10763. *
  10764. * @description
  10765. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  10766. * registered {@link ng.$rootScope.Scope#methods_$on} listeners.
  10767. *
  10768. * The event life cycle starts at the scope on which `$broadcast` was called. All
  10769. * {@link ng.$rootScope.Scope#methods_$on listeners} listening for `name` event on this scope get
  10770. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  10771. * scope and calls all registered listeners along the way. The event cannot be canceled.
  10772. *
  10773. * Any exception emitted from the {@link ng.$rootScope.Scope#methods_$on listeners} will be passed
  10774. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  10775. *
  10776. * @param {string} name Event name to broadcast.
  10777. * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
  10778. * @return {Object} Event object, see {@link ng.$rootScope.Scope#methods_$on}
  10779. */
  10780. $broadcast: function(name, args) {
  10781. var target = this,
  10782. current = target,
  10783. next = target,
  10784. event = {
  10785. name: name,
  10786. targetScope: target,
  10787. preventDefault: function() {
  10788. event.defaultPrevented = true;
  10789. },
  10790. defaultPrevented: false
  10791. },
  10792. listenerArgs = concat([event], arguments, 1),
  10793. listeners, i, length;
  10794. //down while you can, then up and next sibling or up and next sibling until back at root
  10795. do {
  10796. current = next;
  10797. event.currentScope = current;
  10798. listeners = current.$$listeners[name] || [];
  10799. for (i=0, length = listeners.length; i<length; i++) {
  10800. // if listeners were deregistered, defragment the array
  10801. if (!listeners[i]) {
  10802. listeners.splice(i, 1);
  10803. i--;
  10804. length--;
  10805. continue;
  10806. }
  10807. try {
  10808. listeners[i].apply(null, listenerArgs);
  10809. } catch(e) {
  10810. $exceptionHandler(e);
  10811. }
  10812. }
  10813. // Insanity Warning: scope depth-first traversal
  10814. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  10815. // this piece should be kept in sync with the traversal in $digest
  10816. if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
  10817. while(current !== target && !(next = current.$$nextSibling)) {
  10818. current = current.$parent;
  10819. }
  10820. }
  10821. } while ((current = next));
  10822. return event;
  10823. }
  10824. };
  10825. var $rootScope = new Scope();
  10826. return $rootScope;
  10827. function beginPhase(phase) {
  10828. if ($rootScope.$$phase) {
  10829. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  10830. }
  10831. $rootScope.$$phase = phase;
  10832. }
  10833. function clearPhase() {
  10834. $rootScope.$$phase = null;
  10835. }
  10836. function compileToFn(exp, name) {
  10837. var fn = $parse(exp);
  10838. assertArgFn(fn, name);
  10839. return fn;
  10840. }
  10841. /**
  10842. * function used as an initial value for watchers.
  10843. * because it's unique we can easily tell it apart from other values
  10844. */
  10845. function initWatchVal() {}
  10846. }];
  10847. }
  10848. /**
  10849. * @description
  10850. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  10851. */
  10852. function $$SanitizeUriProvider() {
  10853. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  10854. imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
  10855. /**
  10856. * @description
  10857. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  10858. * urls during a[href] sanitization.
  10859. *
  10860. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  10861. *
  10862. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  10863. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  10864. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  10865. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  10866. *
  10867. * @param {RegExp=} regexp New regexp to whitelist urls with.
  10868. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  10869. * chaining otherwise.
  10870. */
  10871. this.aHrefSanitizationWhitelist = function(regexp) {
  10872. if (isDefined(regexp)) {
  10873. aHrefSanitizationWhitelist = regexp;
  10874. return this;
  10875. }
  10876. return aHrefSanitizationWhitelist;
  10877. };
  10878. /**
  10879. * @description
  10880. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  10881. * urls during img[src] sanitization.
  10882. *
  10883. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  10884. *
  10885. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  10886. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  10887. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  10888. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  10889. *
  10890. * @param {RegExp=} regexp New regexp to whitelist urls with.
  10891. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  10892. * chaining otherwise.
  10893. */
  10894. this.imgSrcSanitizationWhitelist = function(regexp) {
  10895. if (isDefined(regexp)) {
  10896. imgSrcSanitizationWhitelist = regexp;
  10897. return this;
  10898. }
  10899. return imgSrcSanitizationWhitelist;
  10900. };
  10901. this.$get = function() {
  10902. return function sanitizeUri(uri, isImage) {
  10903. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  10904. var normalizedVal;
  10905. // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
  10906. if (!msie || msie >= 8 ) {
  10907. normalizedVal = urlResolve(uri).href;
  10908. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  10909. return 'unsafe:'+normalizedVal;
  10910. }
  10911. }
  10912. return uri;
  10913. };
  10914. };
  10915. }
  10916. var $sceMinErr = minErr('$sce');
  10917. var SCE_CONTEXTS = {
  10918. HTML: 'html',
  10919. CSS: 'css',
  10920. URL: 'url',
  10921. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  10922. // url. (e.g. ng-include, script src, templateUrl)
  10923. RESOURCE_URL: 'resourceUrl',
  10924. JS: 'js'
  10925. };
  10926. // Helper functions follow.
  10927. // Copied from:
  10928. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  10929. // Prereq: s is a string.
  10930. function escapeForRegexp(s) {
  10931. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  10932. replace(/\x08/g, '\\x08');
  10933. }
  10934. function adjustMatcher(matcher) {
  10935. if (matcher === 'self') {
  10936. return matcher;
  10937. } else if (isString(matcher)) {
  10938. // Strings match exactly except for 2 wildcards - '*' and '**'.
  10939. // '*' matches any character except those from the set ':/.?&'.
  10940. // '**' matches any character (like .* in a RegExp).
  10941. // More than 2 *'s raises an error as it's ill defined.
  10942. if (matcher.indexOf('***') > -1) {
  10943. throw $sceMinErr('iwcard',
  10944. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  10945. }
  10946. matcher = escapeForRegexp(matcher).
  10947. replace('\\*\\*', '.*').
  10948. replace('\\*', '[^:/.?&;]*');
  10949. return new RegExp('^' + matcher + '$');
  10950. } else if (isRegExp(matcher)) {
  10951. // The only other type of matcher allowed is a Regexp.
  10952. // Match entire URL / disallow partial matches.
  10953. // Flags are reset (i.e. no global, ignoreCase or multiline)
  10954. return new RegExp('^' + matcher.source + '$');
  10955. } else {
  10956. throw $sceMinErr('imatcher',
  10957. 'Matchers may only be "self", string patterns or RegExp objects');
  10958. }
  10959. }
  10960. function adjustMatchers(matchers) {
  10961. var adjustedMatchers = [];
  10962. if (isDefined(matchers)) {
  10963. forEach(matchers, function(matcher) {
  10964. adjustedMatchers.push(adjustMatcher(matcher));
  10965. });
  10966. }
  10967. return adjustedMatchers;
  10968. }
  10969. /**
  10970. * @ngdoc service
  10971. * @name ng.$sceDelegate
  10972. * @function
  10973. *
  10974. * @description
  10975. *
  10976. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  10977. * Contextual Escaping (SCE)} services to AngularJS.
  10978. *
  10979. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  10980. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  10981. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  10982. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  10983. * work because `$sce` delegates to `$sceDelegate` for these operations.
  10984. *
  10985. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  10986. *
  10987. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  10988. * can override it completely to change the behavior of `$sce`, the common case would
  10989. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  10990. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  10991. * templates. Refer {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist
  10992. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  10993. * ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  10994. */
  10995. /**
  10996. * @ngdoc object
  10997. * @name ng.$sceDelegateProvider
  10998. * @description
  10999. *
  11000. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  11001. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  11002. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  11003. * ng.$sceDelegateProvider#methods_resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  11004. * {@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11005. *
  11006. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  11007. * Strict Contextual Escaping (SCE)}.
  11008. *
  11009. * **Example**: Consider the following case. <a name="example"></a>
  11010. *
  11011. * - your app is hosted at url `http://myapp.example.com/`
  11012. * - but some of your templates are hosted on other domains you control such as
  11013. * `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
  11014. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  11015. *
  11016. * Here is what a secure configuration for this scenario might look like:
  11017. *
  11018. * <pre class="prettyprint">
  11019. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  11020. * $sceDelegateProvider.resourceUrlWhitelist([
  11021. * // Allow same origin resource loads.
  11022. * 'self',
  11023. * // Allow loading from our assets domain. Notice the difference between * and **.
  11024. * 'http://srv*.assets.example.com/**']);
  11025. *
  11026. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  11027. * $sceDelegateProvider.resourceUrlBlacklist([
  11028. * 'http://myapp.example.com/clickThru**']);
  11029. * });
  11030. * </pre>
  11031. */
  11032. function $SceDelegateProvider() {
  11033. this.SCE_CONTEXTS = SCE_CONTEXTS;
  11034. // Resource URLs can also be trusted by policy.
  11035. var resourceUrlWhitelist = ['self'],
  11036. resourceUrlBlacklist = [];
  11037. /**
  11038. * @ngdoc function
  11039. * @name ng.sceDelegateProvider#resourceUrlWhitelist
  11040. * @methodOf ng.$sceDelegateProvider
  11041. * @function
  11042. *
  11043. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  11044. * provided. This must be an array or null. A snapshot of this array is used so further
  11045. * changes to the array are ignored.
  11046. *
  11047. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11048. * allowed in this array.
  11049. *
  11050. * Note: **an empty whitelist array will block all URLs**!
  11051. *
  11052. * @return {Array} the currently set whitelist array.
  11053. *
  11054. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  11055. * same origin resource requests.
  11056. *
  11057. * @description
  11058. * Sets/Gets the whitelist of trusted resource URLs.
  11059. */
  11060. this.resourceUrlWhitelist = function (value) {
  11061. if (arguments.length) {
  11062. resourceUrlWhitelist = adjustMatchers(value);
  11063. }
  11064. return resourceUrlWhitelist;
  11065. };
  11066. /**
  11067. * @ngdoc function
  11068. * @name ng.sceDelegateProvider#resourceUrlBlacklist
  11069. * @methodOf ng.$sceDelegateProvider
  11070. * @function
  11071. *
  11072. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  11073. * provided. This must be an array or null. A snapshot of this array is used so further
  11074. * changes to the array are ignored.
  11075. *
  11076. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11077. * allowed in this array.
  11078. *
  11079. * The typical usage for the blacklist is to **block
  11080. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  11081. * these would otherwise be trusted but actually return content from the redirected domain.
  11082. *
  11083. * Finally, **the blacklist overrides the whitelist** and has the final say.
  11084. *
  11085. * @return {Array} the currently set blacklist array.
  11086. *
  11087. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  11088. * is no blacklist.)
  11089. *
  11090. * @description
  11091. * Sets/Gets the blacklist of trusted resource URLs.
  11092. */
  11093. this.resourceUrlBlacklist = function (value) {
  11094. if (arguments.length) {
  11095. resourceUrlBlacklist = adjustMatchers(value);
  11096. }
  11097. return resourceUrlBlacklist;
  11098. };
  11099. this.$get = ['$injector', function($injector) {
  11100. var htmlSanitizer = function htmlSanitizer(html) {
  11101. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11102. };
  11103. if ($injector.has('$sanitize')) {
  11104. htmlSanitizer = $injector.get('$sanitize');
  11105. }
  11106. function matchUrl(matcher, parsedUrl) {
  11107. if (matcher === 'self') {
  11108. return urlIsSameOrigin(parsedUrl);
  11109. } else {
  11110. // definitely a regex. See adjustMatchers()
  11111. return !!matcher.exec(parsedUrl.href);
  11112. }
  11113. }
  11114. function isResourceUrlAllowedByPolicy(url) {
  11115. var parsedUrl = urlResolve(url.toString());
  11116. var i, n, allowed = false;
  11117. // Ensure that at least one item from the whitelist allows this url.
  11118. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  11119. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  11120. allowed = true;
  11121. break;
  11122. }
  11123. }
  11124. if (allowed) {
  11125. // Ensure that no item from the blacklist blocked this url.
  11126. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  11127. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  11128. allowed = false;
  11129. break;
  11130. }
  11131. }
  11132. }
  11133. return allowed;
  11134. }
  11135. function generateHolderType(Base) {
  11136. var holderType = function TrustedValueHolderType(trustedValue) {
  11137. this.$$unwrapTrustedValue = function() {
  11138. return trustedValue;
  11139. };
  11140. };
  11141. if (Base) {
  11142. holderType.prototype = new Base();
  11143. }
  11144. holderType.prototype.valueOf = function sceValueOf() {
  11145. return this.$$unwrapTrustedValue();
  11146. };
  11147. holderType.prototype.toString = function sceToString() {
  11148. return this.$$unwrapTrustedValue().toString();
  11149. };
  11150. return holderType;
  11151. }
  11152. var trustedValueHolderBase = generateHolderType(),
  11153. byType = {};
  11154. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  11155. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  11156. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  11157. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  11158. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  11159. /**
  11160. * @ngdoc method
  11161. * @name ng.$sceDelegate#trustAs
  11162. * @methodOf ng.$sceDelegate
  11163. *
  11164. * @description
  11165. * Returns an object that is trusted by angular for use in specified strict
  11166. * contextual escaping contexts (such as ng-html-bind-unsafe, ng-include, any src
  11167. * attribute interpolation, any dom event binding attribute interpolation
  11168. * such as for onclick, etc.) that uses the provided value.
  11169. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  11170. *
  11171. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  11172. * resourceUrl, html, js and css.
  11173. * @param {*} value The value that that should be considered trusted/safe.
  11174. * @returns {*} A value that can be used to stand in for the provided `value` in places
  11175. * where Angular expects a $sce.trustAs() return value.
  11176. */
  11177. function trustAs(type, trustedValue) {
  11178. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  11179. if (!Constructor) {
  11180. throw $sceMinErr('icontext',
  11181. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  11182. type, trustedValue);
  11183. }
  11184. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  11185. return trustedValue;
  11186. }
  11187. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  11188. // mutable objects, we ensure here that the value passed in is actually a string.
  11189. if (typeof trustedValue !== 'string') {
  11190. throw $sceMinErr('itype',
  11191. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  11192. type);
  11193. }
  11194. return new Constructor(trustedValue);
  11195. }
  11196. /**
  11197. * @ngdoc method
  11198. * @name ng.$sceDelegate#valueOf
  11199. * @methodOf ng.$sceDelegate
  11200. *
  11201. * @description
  11202. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#methods_trustAs
  11203. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  11204. * ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}.
  11205. *
  11206. * If the passed parameter is not a value that had been returned by {@link
  11207. * ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}, returns it as-is.
  11208. *
  11209. * @param {*} value The result of a prior {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}
  11210. * call or anything else.
  11211. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#methods_trustAs
  11212. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  11213. * `value` unchanged.
  11214. */
  11215. function valueOf(maybeTrusted) {
  11216. if (maybeTrusted instanceof trustedValueHolderBase) {
  11217. return maybeTrusted.$$unwrapTrustedValue();
  11218. } else {
  11219. return maybeTrusted;
  11220. }
  11221. }
  11222. /**
  11223. * @ngdoc method
  11224. * @name ng.$sceDelegate#getTrusted
  11225. * @methodOf ng.$sceDelegate
  11226. *
  11227. * @description
  11228. * Takes the result of a {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`} call and
  11229. * returns the originally supplied value if the queried context type is a supertype of the
  11230. * created type. If this condition isn't satisfied, throws an exception.
  11231. *
  11232. * @param {string} type The kind of context in which this value is to be used.
  11233. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#methods_trustAs
  11234. * `$sceDelegate.trustAs`} call.
  11235. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#methods_trustAs
  11236. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  11237. */
  11238. function getTrusted(type, maybeTrusted) {
  11239. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  11240. return maybeTrusted;
  11241. }
  11242. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  11243. if (constructor && maybeTrusted instanceof constructor) {
  11244. return maybeTrusted.$$unwrapTrustedValue();
  11245. }
  11246. // If we get here, then we may only take one of two actions.
  11247. // 1. sanitize the value for the requested type, or
  11248. // 2. throw an exception.
  11249. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  11250. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  11251. return maybeTrusted;
  11252. } else {
  11253. throw $sceMinErr('insecurl',
  11254. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  11255. maybeTrusted.toString());
  11256. }
  11257. } else if (type === SCE_CONTEXTS.HTML) {
  11258. return htmlSanitizer(maybeTrusted);
  11259. }
  11260. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11261. }
  11262. return { trustAs: trustAs,
  11263. getTrusted: getTrusted,
  11264. valueOf: valueOf };
  11265. }];
  11266. }
  11267. /**
  11268. * @ngdoc object
  11269. * @name ng.$sceProvider
  11270. * @description
  11271. *
  11272. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  11273. * - enable/disable Strict Contextual Escaping (SCE) in a module
  11274. * - override the default implementation with a custom delegate
  11275. *
  11276. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  11277. */
  11278. /* jshint maxlen: false*/
  11279. /**
  11280. * @ngdoc service
  11281. * @name ng.$sce
  11282. * @function
  11283. *
  11284. * @description
  11285. *
  11286. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  11287. *
  11288. * # Strict Contextual Escaping
  11289. *
  11290. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  11291. * contexts to result in a value that is marked as safe to use for that context. One example of
  11292. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  11293. * to these contexts as privileged or SCE contexts.
  11294. *
  11295. * As of version 1.2, Angular ships with SCE enabled by default.
  11296. *
  11297. * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
  11298. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  11299. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  11300. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  11301. * to the top of your HTML document.
  11302. *
  11303. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  11304. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  11305. *
  11306. * Here's an example of a binding in a privileged context:
  11307. *
  11308. * <pre class="prettyprint">
  11309. * <input ng-model="userHtml">
  11310. * <div ng-bind-html="userHtml">
  11311. * </pre>
  11312. *
  11313. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  11314. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  11315. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  11316. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  11317. * security vulnerabilities.)
  11318. *
  11319. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  11320. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  11321. *
  11322. * How would you ensure that every place that used these types of bindings was bound to a value that
  11323. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  11324. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  11325. * properties/fields and forgot to update the binding to the sanitized value?
  11326. *
  11327. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  11328. * determine that something explicitly says it's safe to use a value for binding in that
  11329. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  11330. * for those values that you can easily tell are safe - because they were received from your server,
  11331. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  11332. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  11333. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  11334. *
  11335. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#methods_trustAs $sce.trustAs}
  11336. * (and shorthand methods such as {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}, etc.) to
  11337. * obtain values that will be accepted by SCE / privileged contexts.
  11338. *
  11339. *
  11340. * ## How does it work?
  11341. *
  11342. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#methods_getTrusted
  11343. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  11344. * ng.$sce#methods_parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  11345. * {@link ng.$sce#methods_getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  11346. *
  11347. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  11348. * ng.$sce#methods_parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  11349. * simplified):
  11350. *
  11351. * <pre class="prettyprint">
  11352. * var ngBindHtmlDirective = ['$sce', function($sce) {
  11353. * return function(scope, element, attr) {
  11354. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  11355. * element.html(value || '');
  11356. * });
  11357. * };
  11358. * }];
  11359. * </pre>
  11360. *
  11361. * ## Impact on loading templates
  11362. *
  11363. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  11364. * `templateUrl`'s specified by {@link guide/directive directives}.
  11365. *
  11366. * By default, Angular only loads templates from the same domain and protocol as the application
  11367. * document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl
  11368. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  11369. * protocols, you may either either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist
  11370. * them} or {@link ng.$sce#methods_trustAsResourceUrl wrap it} into a trusted value.
  11371. *
  11372. * *Please note*:
  11373. * The browser's
  11374. * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
  11375. * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)}
  11376. * policy apply in addition to this and may further restrict whether the template is successfully
  11377. * loaded. This means that without the right CORS policy, loading templates from a different domain
  11378. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  11379. * browsers.
  11380. *
  11381. * ## This feels like too much overhead for the developer?
  11382. *
  11383. * It's important to remember that SCE only applies to interpolation expressions.
  11384. *
  11385. * If your expressions are constant literals, they're automatically trusted and you don't need to
  11386. * call `$sce.trustAs` on them. (e.g.
  11387. * `<div ng-html-bind-unsafe="'<b>implicitly trusted</b>'"></div>`) just works.
  11388. *
  11389. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  11390. * through {@link ng.$sce#methods_getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  11391. *
  11392. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  11393. * templates in `ng-include` from your application's domain without having to even know about SCE.
  11394. * It blocks loading templates from other domains or loading templates over http from an https
  11395. * served document. You can change these by setting your own custom {@link
  11396. * ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelists} and {@link
  11397. * ng.$sceDelegateProvider#methods_resourceUrlBlacklist blacklists} for matching such URLs.
  11398. *
  11399. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  11400. * application that's secure and can be audited to verify that with much more ease than bolting
  11401. * security onto an application later.
  11402. *
  11403. * <a name="contexts"></a>
  11404. * ## What trusted context types are supported?
  11405. *
  11406. * | Context | Notes |
  11407. * |---------------------|----------------|
  11408. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. |
  11409. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  11410. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't consititute an SCE context. |
  11411. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contens 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. |
  11412. * | `$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. |
  11413. *
  11414. * ## Format of items in {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  11415. *
  11416. * Each element in these arrays must be one of the following:
  11417. *
  11418. * - **'self'**
  11419. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  11420. * domain** as the application document using the **same protocol**.
  11421. * - **String** (except the special value `'self'`)
  11422. * - The string is matched against the full *normalized / absolute URL* of the resource
  11423. * being tested (substring matches are not good enough.)
  11424. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  11425. * match themselves.
  11426. * - `*`: matches zero or more occurances of any character other than one of the following 6
  11427. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  11428. * in a whitelist.
  11429. * - `**`: matches zero or more occurances of *any* character. As such, it's not
  11430. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  11431. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  11432. * not have been the intention.) It's usage at the very end of the path is ok. (e.g.
  11433. * http://foo.example.com/templates/**).
  11434. * - **RegExp** (*see caveat below*)
  11435. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  11436. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  11437. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  11438. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  11439. * small number of cases. A `.` character in the regex used when matching the scheme or a
  11440. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  11441. * is highly recommended to use the string patterns and only fall back to regular expressions
  11442. * if they as a last resort.
  11443. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  11444. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  11445. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  11446. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  11447. * - If you are generating your Javascript from some other templating engine (not
  11448. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  11449. * remember to escape your regular expression (and be aware that you might need more than
  11450. * one level of escaping depending on your templating engine and the way you interpolated
  11451. * the value.) Do make use of your platform's escaping mechanism as it might be good
  11452. * enough before coding your own. e.g. Ruby has
  11453. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  11454. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  11455. * Javascript lacks a similar built in function for escaping. Take a look at Google
  11456. * Closure library's [goog.string.regExpEscape(s)](
  11457. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  11458. *
  11459. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  11460. *
  11461. * ## Show me an example using SCE.
  11462. *
  11463. * @example
  11464. <example module="mySceApp">
  11465. <file name="index.html">
  11466. <div ng-controller="myAppController as myCtrl">
  11467. <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  11468. <b>User comments</b><br>
  11469. By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  11470. $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  11471. exploit.
  11472. <div class="well">
  11473. <div ng-repeat="userComment in myCtrl.userComments">
  11474. <b>{{userComment.name}}</b>:
  11475. <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  11476. <br>
  11477. </div>
  11478. </div>
  11479. </div>
  11480. </file>
  11481. <file name="script.js">
  11482. var mySceApp = angular.module('mySceApp', ['ngSanitize']);
  11483. mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  11484. var self = this;
  11485. $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  11486. self.userComments = userComments;
  11487. });
  11488. self.explicitlyTrustedHtml = $sce.trustAsHtml(
  11489. '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  11490. 'sanitization.&quot;">Hover over this text.</span>');
  11491. });
  11492. </file>
  11493. <file name="test_data.json">
  11494. [
  11495. { "name": "Alice",
  11496. "htmlComment":
  11497. "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  11498. },
  11499. { "name": "Bob",
  11500. "htmlComment": "<i>Yes!</i> Am I the only other one?"
  11501. }
  11502. ]
  11503. </file>
  11504. <file name="scenario.js">
  11505. describe('SCE doc demo', function() {
  11506. it('should sanitize untrusted values', function() {
  11507. expect(element('.htmlComment').html()).toBe('<span>Is <i>anyone</i> reading this?</span>');
  11508. });
  11509. it('should NOT sanitize explicitly trusted values', function() {
  11510. expect(element('#explicitlyTrustedHtml').html()).toBe(
  11511. '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  11512. 'sanitization.&quot;">Hover over this text.</span>');
  11513. });
  11514. });
  11515. </file>
  11516. </example>
  11517. *
  11518. *
  11519. *
  11520. * ## Can I disable SCE completely?
  11521. *
  11522. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  11523. * for little coding overhead. It will be much harder to take an SCE disabled application and
  11524. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  11525. * for cases where you have a lot of existing code that was written before SCE was introduced and
  11526. * you're migrating them a module at a time.
  11527. *
  11528. * That said, here's how you can completely disable SCE:
  11529. *
  11530. * <pre class="prettyprint">
  11531. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  11532. * // Completely disable SCE. For demonstration purposes only!
  11533. * // Do not use in new projects.
  11534. * $sceProvider.enabled(false);
  11535. * });
  11536. * </pre>
  11537. *
  11538. */
  11539. /* jshint maxlen: 100 */
  11540. function $SceProvider() {
  11541. var enabled = true;
  11542. /**
  11543. * @ngdoc function
  11544. * @name ng.sceProvider#enabled
  11545. * @methodOf ng.$sceProvider
  11546. * @function
  11547. *
  11548. * @param {boolean=} value If provided, then enables/disables SCE.
  11549. * @return {boolean} true if SCE is enabled, false otherwise.
  11550. *
  11551. * @description
  11552. * Enables/disables SCE and returns the current value.
  11553. */
  11554. this.enabled = function (value) {
  11555. if (arguments.length) {
  11556. enabled = !!value;
  11557. }
  11558. return enabled;
  11559. };
  11560. /* Design notes on the default implementation for SCE.
  11561. *
  11562. * The API contract for the SCE delegate
  11563. * -------------------------------------
  11564. * The SCE delegate object must provide the following 3 methods:
  11565. *
  11566. * - trustAs(contextEnum, value)
  11567. * This method is used to tell the SCE service that the provided value is OK to use in the
  11568. * contexts specified by contextEnum. It must return an object that will be accepted by
  11569. * getTrusted() for a compatible contextEnum and return this value.
  11570. *
  11571. * - valueOf(value)
  11572. * For values that were not produced by trustAs(), return them as is. For values that were
  11573. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  11574. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  11575. * such a value.
  11576. *
  11577. * - getTrusted(contextEnum, value)
  11578. * This function should return the a value that is safe to use in the context specified by
  11579. * contextEnum or throw and exception otherwise.
  11580. *
  11581. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  11582. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  11583. * instance, an implementation could maintain a registry of all trusted objects by context. In
  11584. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  11585. * return the same object passed in if it was found in the registry under a compatible context or
  11586. * throw an exception otherwise. An implementation might only wrap values some of the time based
  11587. * on some criteria. getTrusted() might return a value and not throw an exception for special
  11588. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  11589. *
  11590. *
  11591. * A note on the inheritance model for SCE contexts
  11592. * ------------------------------------------------
  11593. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  11594. * is purely an implementation details.
  11595. *
  11596. * The contract is simply this:
  11597. *
  11598. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  11599. * will also succeed.
  11600. *
  11601. * Inheritance happens to capture this in a natural way. In some future, we
  11602. * may not use inheritance anymore. That is OK because no code outside of
  11603. * sce.js and sceSpecs.js would need to be aware of this detail.
  11604. */
  11605. this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
  11606. $parse, $sniffer, $sceDelegate) {
  11607. // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
  11608. // the "expression(javascript expression)" syntax which is insecure.
  11609. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
  11610. throw $sceMinErr('iequirks',
  11611. 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
  11612. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  11613. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  11614. }
  11615. var sce = copy(SCE_CONTEXTS);
  11616. /**
  11617. * @ngdoc function
  11618. * @name ng.sce#isEnabled
  11619. * @methodOf ng.$sce
  11620. * @function
  11621. *
  11622. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  11623. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  11624. *
  11625. * @description
  11626. * Returns a boolean indicating if SCE is enabled.
  11627. */
  11628. sce.isEnabled = function () {
  11629. return enabled;
  11630. };
  11631. sce.trustAs = $sceDelegate.trustAs;
  11632. sce.getTrusted = $sceDelegate.getTrusted;
  11633. sce.valueOf = $sceDelegate.valueOf;
  11634. if (!enabled) {
  11635. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  11636. sce.valueOf = identity;
  11637. }
  11638. /**
  11639. * @ngdoc method
  11640. * @name ng.$sce#parse
  11641. * @methodOf ng.$sce
  11642. *
  11643. * @description
  11644. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  11645. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  11646. * wraps the expression in a call to {@link ng.$sce#methods_getTrusted $sce.getTrusted(*type*,
  11647. * *result*)}
  11648. *
  11649. * @param {string} type The kind of SCE context in which this result will be used.
  11650. * @param {string} expression String expression to compile.
  11651. * @returns {function(context, locals)} a function which represents the compiled expression:
  11652. *
  11653. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11654. * are evaluated against (typically a scope object).
  11655. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11656. * `context`.
  11657. */
  11658. sce.parseAs = function sceParseAs(type, expr) {
  11659. var parsed = $parse(expr);
  11660. if (parsed.literal && parsed.constant) {
  11661. return parsed;
  11662. } else {
  11663. return function sceParseAsTrusted(self, locals) {
  11664. return sce.getTrusted(type, parsed(self, locals));
  11665. };
  11666. }
  11667. };
  11668. /**
  11669. * @ngdoc method
  11670. * @name ng.$sce#trustAs
  11671. * @methodOf ng.$sce
  11672. *
  11673. * @description
  11674. * Delegates to {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}. As such,
  11675. * returns an objectthat is trusted by angular for use in specified strict contextual
  11676. * escaping contexts (such as ng-html-bind-unsafe, ng-include, any src attribute
  11677. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  11678. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  11679. * escaping.
  11680. *
  11681. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  11682. * resource_url, html, js and css.
  11683. * @param {*} value The value that that should be considered trusted/safe.
  11684. * @returns {*} A value that can be used to stand in for the provided `value` in places
  11685. * where Angular expects a $sce.trustAs() return value.
  11686. */
  11687. /**
  11688. * @ngdoc method
  11689. * @name ng.$sce#trustAsHtml
  11690. * @methodOf ng.$sce
  11691. *
  11692. * @description
  11693. * Shorthand method. `$sce.trustAsHtml(value)` →
  11694. * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  11695. *
  11696. * @param {*} value The value to trustAs.
  11697. * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedHtml
  11698. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  11699. * only accept expressions that are either literal constants or are the
  11700. * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
  11701. */
  11702. /**
  11703. * @ngdoc method
  11704. * @name ng.$sce#trustAsUrl
  11705. * @methodOf ng.$sce
  11706. *
  11707. * @description
  11708. * Shorthand method. `$sce.trustAsUrl(value)` →
  11709. * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  11710. *
  11711. * @param {*} value The value to trustAs.
  11712. * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedUrl
  11713. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  11714. * only accept expressions that are either literal constants or are the
  11715. * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
  11716. */
  11717. /**
  11718. * @ngdoc method
  11719. * @name ng.$sce#trustAsResourceUrl
  11720. * @methodOf ng.$sce
  11721. *
  11722. * @description
  11723. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  11724. * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  11725. *
  11726. * @param {*} value The value to trustAs.
  11727. * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedResourceUrl
  11728. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  11729. * only accept expressions that are either literal constants or are the return
  11730. * value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
  11731. */
  11732. /**
  11733. * @ngdoc method
  11734. * @name ng.$sce#trustAsJs
  11735. * @methodOf ng.$sce
  11736. *
  11737. * @description
  11738. * Shorthand method. `$sce.trustAsJs(value)` →
  11739. * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  11740. *
  11741. * @param {*} value The value to trustAs.
  11742. * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedJs
  11743. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  11744. * only accept expressions that are either literal constants or are the
  11745. * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
  11746. */
  11747. /**
  11748. * @ngdoc method
  11749. * @name ng.$sce#getTrusted
  11750. * @methodOf ng.$sce
  11751. *
  11752. * @description
  11753. * Delegates to {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted`}. As such,
  11754. * takes the result of a {@link ng.$sce#methods_trustAs `$sce.trustAs`}() call and returns the
  11755. * originally supplied value if the queried context type is a supertype of the created type.
  11756. * If this condition isn't satisfied, throws an exception.
  11757. *
  11758. * @param {string} type The kind of context in which this value is to be used.
  11759. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#methods_trustAs `$sce.trustAs`}
  11760. * call.
  11761. * @returns {*} The value the was originally provided to
  11762. * {@link ng.$sce#methods_trustAs `$sce.trustAs`} if valid in this context.
  11763. * Otherwise, throws an exception.
  11764. */
  11765. /**
  11766. * @ngdoc method
  11767. * @name ng.$sce#getTrustedHtml
  11768. * @methodOf ng.$sce
  11769. *
  11770. * @description
  11771. * Shorthand method. `$sce.getTrustedHtml(value)` →
  11772. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  11773. *
  11774. * @param {*} value The value to pass to `$sce.getTrusted`.
  11775. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  11776. */
  11777. /**
  11778. * @ngdoc method
  11779. * @name ng.$sce#getTrustedCss
  11780. * @methodOf ng.$sce
  11781. *
  11782. * @description
  11783. * Shorthand method. `$sce.getTrustedCss(value)` →
  11784. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  11785. *
  11786. * @param {*} value The value to pass to `$sce.getTrusted`.
  11787. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  11788. */
  11789. /**
  11790. * @ngdoc method
  11791. * @name ng.$sce#getTrustedUrl
  11792. * @methodOf ng.$sce
  11793. *
  11794. * @description
  11795. * Shorthand method. `$sce.getTrustedUrl(value)` →
  11796. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  11797. *
  11798. * @param {*} value The value to pass to `$sce.getTrusted`.
  11799. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  11800. */
  11801. /**
  11802. * @ngdoc method
  11803. * @name ng.$sce#getTrustedResourceUrl
  11804. * @methodOf ng.$sce
  11805. *
  11806. * @description
  11807. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  11808. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  11809. *
  11810. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  11811. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  11812. */
  11813. /**
  11814. * @ngdoc method
  11815. * @name ng.$sce#getTrustedJs
  11816. * @methodOf ng.$sce
  11817. *
  11818. * @description
  11819. * Shorthand method. `$sce.getTrustedJs(value)` →
  11820. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  11821. *
  11822. * @param {*} value The value to pass to `$sce.getTrusted`.
  11823. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  11824. */
  11825. /**
  11826. * @ngdoc method
  11827. * @name ng.$sce#parseAsHtml
  11828. * @methodOf ng.$sce
  11829. *
  11830. * @description
  11831. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  11832. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.HTML, value)`}
  11833. *
  11834. * @param {string} expression String expression to compile.
  11835. * @returns {function(context, locals)} a function which represents the compiled expression:
  11836. *
  11837. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11838. * are evaluated against (typically a scope object).
  11839. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11840. * `context`.
  11841. */
  11842. /**
  11843. * @ngdoc method
  11844. * @name ng.$sce#parseAsCss
  11845. * @methodOf ng.$sce
  11846. *
  11847. * @description
  11848. * Shorthand method. `$sce.parseAsCss(value)` →
  11849. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.CSS, value)`}
  11850. *
  11851. * @param {string} expression String expression to compile.
  11852. * @returns {function(context, locals)} a function which represents the compiled expression:
  11853. *
  11854. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11855. * are evaluated against (typically a scope object).
  11856. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11857. * `context`.
  11858. */
  11859. /**
  11860. * @ngdoc method
  11861. * @name ng.$sce#parseAsUrl
  11862. * @methodOf ng.$sce
  11863. *
  11864. * @description
  11865. * Shorthand method. `$sce.parseAsUrl(value)` →
  11866. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.URL, value)`}
  11867. *
  11868. * @param {string} expression String expression to compile.
  11869. * @returns {function(context, locals)} a function which represents the compiled expression:
  11870. *
  11871. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11872. * are evaluated against (typically a scope object).
  11873. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11874. * `context`.
  11875. */
  11876. /**
  11877. * @ngdoc method
  11878. * @name ng.$sce#parseAsResourceUrl
  11879. * @methodOf ng.$sce
  11880. *
  11881. * @description
  11882. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  11883. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
  11884. *
  11885. * @param {string} expression String expression to compile.
  11886. * @returns {function(context, locals)} a function which represents the compiled expression:
  11887. *
  11888. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11889. * are evaluated against (typically a scope object).
  11890. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11891. * `context`.
  11892. */
  11893. /**
  11894. * @ngdoc method
  11895. * @name ng.$sce#parseAsJs
  11896. * @methodOf ng.$sce
  11897. *
  11898. * @description
  11899. * Shorthand method. `$sce.parseAsJs(value)` →
  11900. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.JS, value)`}
  11901. *
  11902. * @param {string} expression String expression to compile.
  11903. * @returns {function(context, locals)} a function which represents the compiled expression:
  11904. *
  11905. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11906. * are evaluated against (typically a scope object).
  11907. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11908. * `context`.
  11909. */
  11910. // Shorthand delegations.
  11911. var parse = sce.parseAs,
  11912. getTrusted = sce.getTrusted,
  11913. trustAs = sce.trustAs;
  11914. forEach(SCE_CONTEXTS, function (enumValue, name) {
  11915. var lName = lowercase(name);
  11916. sce[camelCase("parse_as_" + lName)] = function (expr) {
  11917. return parse(enumValue, expr);
  11918. };
  11919. sce[camelCase("get_trusted_" + lName)] = function (value) {
  11920. return getTrusted(enumValue, value);
  11921. };
  11922. sce[camelCase("trust_as_" + lName)] = function (value) {
  11923. return trustAs(enumValue, value);
  11924. };
  11925. });
  11926. return sce;
  11927. }];
  11928. }
  11929. /**
  11930. * !!! This is an undocumented "private" service !!!
  11931. *
  11932. * @name ng.$sniffer
  11933. * @requires $window
  11934. * @requires $document
  11935. *
  11936. * @property {boolean} history Does the browser support html5 history api ?
  11937. * @property {boolean} hashchange Does the browser support hashchange event ?
  11938. * @property {boolean} transitions Does the browser support CSS transition events ?
  11939. * @property {boolean} animations Does the browser support CSS animation events ?
  11940. *
  11941. * @description
  11942. * This is very simple implementation of testing browser's features.
  11943. */
  11944. function $SnifferProvider() {
  11945. this.$get = ['$window', '$document', function($window, $document) {
  11946. var eventSupport = {},
  11947. android =
  11948. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  11949. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  11950. document = $document[0] || {},
  11951. documentMode = document.documentMode,
  11952. vendorPrefix,
  11953. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  11954. bodyStyle = document.body && document.body.style,
  11955. transitions = false,
  11956. animations = false,
  11957. match;
  11958. if (bodyStyle) {
  11959. for(var prop in bodyStyle) {
  11960. if(match = vendorRegex.exec(prop)) {
  11961. vendorPrefix = match[0];
  11962. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  11963. break;
  11964. }
  11965. }
  11966. if(!vendorPrefix) {
  11967. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  11968. }
  11969. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  11970. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  11971. if (android && (!transitions||!animations)) {
  11972. transitions = isString(document.body.style.webkitTransition);
  11973. animations = isString(document.body.style.webkitAnimation);
  11974. }
  11975. }
  11976. return {
  11977. // Android has history.pushState, but it does not update location correctly
  11978. // so let's not use the history API at all.
  11979. // http://code.google.com/p/android/issues/detail?id=17471
  11980. // https://github.com/angular/angular.js/issues/904
  11981. // older webit browser (533.9) on Boxee box has exactly the same problem as Android has
  11982. // so let's not use the history API also
  11983. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  11984. // jshint -W018
  11985. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  11986. // jshint +W018
  11987. hashchange: 'onhashchange' in $window &&
  11988. // IE8 compatible mode lies
  11989. (!documentMode || documentMode > 7),
  11990. hasEvent: function(event) {
  11991. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  11992. // it. In particular the event is not fired when backspace or delete key are pressed or
  11993. // when cut operation is performed.
  11994. if (event == 'input' && msie == 9) return false;
  11995. if (isUndefined(eventSupport[event])) {
  11996. var divElm = document.createElement('div');
  11997. eventSupport[event] = 'on' + event in divElm;
  11998. }
  11999. return eventSupport[event];
  12000. },
  12001. csp: csp(),
  12002. vendorPrefix: vendorPrefix,
  12003. transitions : transitions,
  12004. animations : animations,
  12005. msie : msie,
  12006. msieDocumentMode: documentMode
  12007. };
  12008. }];
  12009. }
  12010. function $TimeoutProvider() {
  12011. this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
  12012. function($rootScope, $browser, $q, $exceptionHandler) {
  12013. var deferreds = {};
  12014. /**
  12015. * @ngdoc function
  12016. * @name ng.$timeout
  12017. * @requires $browser
  12018. *
  12019. * @description
  12020. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  12021. * block and delegates any exceptions to
  12022. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12023. *
  12024. * The return value of registering a timeout function is a promise, which will be resolved when
  12025. * the timeout is reached and the timeout function is executed.
  12026. *
  12027. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  12028. *
  12029. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  12030. * synchronously flush the queue of deferred functions.
  12031. *
  12032. * @param {function()} fn A function, whose execution should be delayed.
  12033. * @param {number=} [delay=0] Delay in milliseconds.
  12034. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12035. * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
  12036. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  12037. * promise will be resolved with is the return value of the `fn` function.
  12038. *
  12039. * @example
  12040. <doc:example module="time">
  12041. <doc:source>
  12042. <script>
  12043. function Ctrl2($scope,$timeout) {
  12044. $scope.format = 'M/d/yy h:mm:ss a';
  12045. $scope.blood_1 = 100;
  12046. $scope.blood_2 = 120;
  12047. var stop;
  12048. $scope.fight = function() {
  12049. stop = $timeout(function() {
  12050. if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  12051. $scope.blood_1 = $scope.blood_1 - 3;
  12052. $scope.blood_2 = $scope.blood_2 - 4;
  12053. $scope.fight();
  12054. } else {
  12055. $timeout.cancel(stop);
  12056. }
  12057. }, 100);
  12058. };
  12059. $scope.stopFight = function() {
  12060. $timeout.cancel(stop);
  12061. };
  12062. $scope.resetFight = function() {
  12063. $scope.blood_1 = 100;
  12064. $scope.blood_2 = 120;
  12065. }
  12066. }
  12067. angular.module('time', [])
  12068. // Register the 'myCurrentTime' directive factory method.
  12069. // We inject $timeout and dateFilter service since the factory method is DI.
  12070. .directive('myCurrentTime', function($timeout, dateFilter) {
  12071. // return the directive link function. (compile function not needed)
  12072. return function(scope, element, attrs) {
  12073. var format, // date format
  12074. timeoutId; // timeoutId, so that we can cancel the time updates
  12075. // used to update the UI
  12076. function updateTime() {
  12077. element.text(dateFilter(new Date(), format));
  12078. }
  12079. // watch the expression, and update the UI on change.
  12080. scope.$watch(attrs.myCurrentTime, function(value) {
  12081. format = value;
  12082. updateTime();
  12083. });
  12084. // schedule update in one second
  12085. function updateLater() {
  12086. // save the timeoutId for canceling
  12087. timeoutId = $timeout(function() {
  12088. updateTime(); // update DOM
  12089. updateLater(); // schedule another update
  12090. }, 1000);
  12091. }
  12092. // listen on DOM destroy (removal) event, and cancel the next UI update
  12093. // to prevent updating time ofter the DOM element was removed.
  12094. element.bind('$destroy', function() {
  12095. $timeout.cancel(timeoutId);
  12096. });
  12097. updateLater(); // kick off the UI update process.
  12098. }
  12099. });
  12100. </script>
  12101. <div>
  12102. <div ng-controller="Ctrl2">
  12103. Date format: <input ng-model="format"> <hr/>
  12104. Current time is: <span my-current-time="format"></span>
  12105. <hr/>
  12106. Blood 1 : <font color='red'>{{blood_1}}</font>
  12107. Blood 2 : <font color='red'>{{blood_2}}</font>
  12108. <button type="button" data-ng-click="fight()">Fight</button>
  12109. <button type="button" data-ng-click="stopFight()">StopFight</button>
  12110. <button type="button" data-ng-click="resetFight()">resetFight</button>
  12111. </div>
  12112. </div>
  12113. </doc:source>
  12114. </doc:example>
  12115. */
  12116. function timeout(fn, delay, invokeApply) {
  12117. var deferred = $q.defer(),
  12118. promise = deferred.promise,
  12119. skipApply = (isDefined(invokeApply) && !invokeApply),
  12120. timeoutId;
  12121. timeoutId = $browser.defer(function() {
  12122. try {
  12123. deferred.resolve(fn());
  12124. } catch(e) {
  12125. deferred.reject(e);
  12126. $exceptionHandler(e);
  12127. }
  12128. finally {
  12129. delete deferreds[promise.$$timeoutId];
  12130. }
  12131. if (!skipApply) $rootScope.$apply();
  12132. }, delay);
  12133. promise.$$timeoutId = timeoutId;
  12134. deferreds[timeoutId] = deferred;
  12135. return promise;
  12136. }
  12137. /**
  12138. * @ngdoc function
  12139. * @name ng.$timeout#cancel
  12140. * @methodOf ng.$timeout
  12141. *
  12142. * @description
  12143. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  12144. * resolved with a rejection.
  12145. *
  12146. * @param {Promise=} promise Promise returned by the `$timeout` function.
  12147. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  12148. * canceled.
  12149. */
  12150. timeout.cancel = function(promise) {
  12151. if (promise && promise.$$timeoutId in deferreds) {
  12152. deferreds[promise.$$timeoutId].reject('canceled');
  12153. delete deferreds[promise.$$timeoutId];
  12154. return $browser.defer.cancel(promise.$$timeoutId);
  12155. }
  12156. return false;
  12157. };
  12158. return timeout;
  12159. }];
  12160. }
  12161. // NOTE: The usage of window and document instead of $window and $document here is
  12162. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  12163. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  12164. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  12165. // doesn't know about mocked locations and resolves URLs to the real document - which is
  12166. // exactly the behavior needed here. There is little value is mocking these out for this
  12167. // service.
  12168. var urlParsingNode = document.createElement("a");
  12169. var originUrl = urlResolve(window.location.href, true);
  12170. /**
  12171. *
  12172. * Implementation Notes for non-IE browsers
  12173. * ----------------------------------------
  12174. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  12175. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  12176. * URL will be resolved into an absolute URL in the context of the application document.
  12177. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  12178. * properties are all populated to reflect the normalized URL. This approach has wide
  12179. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  12180. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12181. *
  12182. * Implementation Notes for IE
  12183. * ---------------------------
  12184. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  12185. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  12186. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  12187. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  12188. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  12189. * properties such as protocol, hostname, port, etc.
  12190. *
  12191. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  12192. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  12193. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  12194. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  12195. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  12196. * method and IE < 8 is unsupported.
  12197. *
  12198. * References:
  12199. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  12200. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12201. * http://url.spec.whatwg.org/#urlutils
  12202. * https://github.com/angular/angular.js/pull/2902
  12203. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  12204. *
  12205. * @function
  12206. * @param {string} url The URL to be parsed.
  12207. * @description Normalizes and parses a URL.
  12208. * @returns {object} Returns the normalized URL as a dictionary.
  12209. *
  12210. * | member name | Description |
  12211. * |---------------|----------------|
  12212. * | href | A normalized version of the provided URL if it was not an absolute URL |
  12213. * | protocol | The protocol including the trailing colon |
  12214. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  12215. * | search | The search params, minus the question mark |
  12216. * | hash | The hash string, minus the hash symbol
  12217. * | hostname | The hostname
  12218. * | port | The port, without ":"
  12219. * | pathname | The pathname, beginning with "/"
  12220. *
  12221. */
  12222. function urlResolve(url, base) {
  12223. var href = url;
  12224. if (msie) {
  12225. // Normalize before parse. Refer Implementation Notes on why this is
  12226. // done in two steps on IE.
  12227. urlParsingNode.setAttribute("href", href);
  12228. href = urlParsingNode.href;
  12229. }
  12230. urlParsingNode.setAttribute('href', href);
  12231. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  12232. return {
  12233. href: urlParsingNode.href,
  12234. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  12235. host: urlParsingNode.host,
  12236. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  12237. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  12238. hostname: urlParsingNode.hostname,
  12239. port: urlParsingNode.port,
  12240. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  12241. ? urlParsingNode.pathname
  12242. : '/' + urlParsingNode.pathname
  12243. };
  12244. }
  12245. /**
  12246. * Parse a request URL and determine whether this is a same-origin request as the application document.
  12247. *
  12248. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  12249. * or a parsed URL object.
  12250. * @returns {boolean} Whether the request is for the same origin as the application document.
  12251. */
  12252. function urlIsSameOrigin(requestUrl) {
  12253. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  12254. return (parsed.protocol === originUrl.protocol &&
  12255. parsed.host === originUrl.host);
  12256. }
  12257. /**
  12258. * @ngdoc object
  12259. * @name ng.$window
  12260. *
  12261. * @description
  12262. * A reference to the browser's `window` object. While `window`
  12263. * is globally available in JavaScript, it causes testability problems, because
  12264. * it is a global variable. In angular we always refer to it through the
  12265. * `$window` service, so it may be overridden, removed or mocked for testing.
  12266. *
  12267. * Expressions, like the one defined for the `ngClick` directive in the example
  12268. * below, are evaluated with respect to the current scope. Therefore, there is
  12269. * no risk of inadvertently coding in a dependency on a global value in such an
  12270. * expression.
  12271. *
  12272. * @example
  12273. <doc:example>
  12274. <doc:source>
  12275. <script>
  12276. function Ctrl($scope, $window) {
  12277. $scope.greeting = 'Hello, World!';
  12278. $scope.doGreeting = function(greeting) {
  12279. $window.alert(greeting);
  12280. };
  12281. }
  12282. </script>
  12283. <div ng-controller="Ctrl">
  12284. <input type="text" ng-model="greeting" />
  12285. <button ng-click="doGreeting(greeting)">ALERT</button>
  12286. </div>
  12287. </doc:source>
  12288. <doc:scenario>
  12289. it('should display the greeting in the input box', function() {
  12290. input('greeting').enter('Hello, E2E Tests');
  12291. // If we click the button it will block the test runner
  12292. // element(':button').click();
  12293. });
  12294. </doc:scenario>
  12295. </doc:example>
  12296. */
  12297. function $WindowProvider(){
  12298. this.$get = valueFn(window);
  12299. }
  12300. /**
  12301. * @ngdoc object
  12302. * @name ng.$filterProvider
  12303. * @description
  12304. *
  12305. * Filters are just functions which transform input to an output. However filters need to be
  12306. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  12307. * annotated with dependencies and is responsible for creating a filter function.
  12308. *
  12309. * <pre>
  12310. * // Filter registration
  12311. * function MyModule($provide, $filterProvider) {
  12312. * // create a service to demonstrate injection (not always needed)
  12313. * $provide.value('greet', function(name){
  12314. * return 'Hello ' + name + '!';
  12315. * });
  12316. *
  12317. * // register a filter factory which uses the
  12318. * // greet service to demonstrate DI.
  12319. * $filterProvider.register('greet', function(greet){
  12320. * // return the filter function which uses the greet service
  12321. * // to generate salutation
  12322. * return function(text) {
  12323. * // filters need to be forgiving so check input validity
  12324. * return text && greet(text) || text;
  12325. * };
  12326. * });
  12327. * }
  12328. * </pre>
  12329. *
  12330. * The filter function is registered with the `$injector` under the filter name suffix with
  12331. * `Filter`.
  12332. *
  12333. * <pre>
  12334. * it('should be the same instance', inject(
  12335. * function($filterProvider) {
  12336. * $filterProvider.register('reverse', function(){
  12337. * return ...;
  12338. * });
  12339. * },
  12340. * function($filter, reverseFilter) {
  12341. * expect($filter('reverse')).toBe(reverseFilter);
  12342. * });
  12343. * </pre>
  12344. *
  12345. *
  12346. * For more information about how angular filters work, and how to create your own filters, see
  12347. * {@link guide/filter Filters} in the Angular Developer Guide.
  12348. */
  12349. /**
  12350. * @ngdoc method
  12351. * @name ng.$filterProvider#register
  12352. * @methodOf ng.$filterProvider
  12353. * @description
  12354. * Register filter factory function.
  12355. *
  12356. * @param {String} name Name of the filter.
  12357. * @param {function} fn The filter factory function which is injectable.
  12358. */
  12359. /**
  12360. * @ngdoc function
  12361. * @name ng.$filter
  12362. * @function
  12363. * @description
  12364. * Filters are used for formatting data displayed to the user.
  12365. *
  12366. * The general syntax in templates is as follows:
  12367. *
  12368. * {{ expression [| filter_name[:parameter_value] ... ] }}
  12369. *
  12370. * @param {String} name Name of the filter function to retrieve
  12371. * @return {Function} the filter function
  12372. */
  12373. $FilterProvider.$inject = ['$provide'];
  12374. function $FilterProvider($provide) {
  12375. var suffix = 'Filter';
  12376. /**
  12377. * @ngdoc function
  12378. * @name ng.$controllerProvider#register
  12379. * @methodOf ng.$controllerProvider
  12380. * @param {string|Object} name Name of the filter function, or an object map of filters where
  12381. * the keys are the filter names and the values are the filter factories.
  12382. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  12383. * of the registered filter instances.
  12384. */
  12385. function register(name, factory) {
  12386. if(isObject(name)) {
  12387. var filters = {};
  12388. forEach(name, function(filter, key) {
  12389. filters[key] = register(key, filter);
  12390. });
  12391. return filters;
  12392. } else {
  12393. return $provide.factory(name + suffix, factory);
  12394. }
  12395. }
  12396. this.register = register;
  12397. this.$get = ['$injector', function($injector) {
  12398. return function(name) {
  12399. return $injector.get(name + suffix);
  12400. };
  12401. }];
  12402. ////////////////////////////////////////
  12403. /* global
  12404. currencyFilter: false,
  12405. dateFilter: false,
  12406. filterFilter: false,
  12407. jsonFilter: false,
  12408. limitToFilter: false,
  12409. lowercaseFilter: false,
  12410. numberFilter: false,
  12411. orderByFilter: false,
  12412. uppercaseFilter: false,
  12413. */
  12414. register('currency', currencyFilter);
  12415. register('date', dateFilter);
  12416. register('filter', filterFilter);
  12417. register('json', jsonFilter);
  12418. register('limitTo', limitToFilter);
  12419. register('lowercase', lowercaseFilter);
  12420. register('number', numberFilter);
  12421. register('orderBy', orderByFilter);
  12422. register('uppercase', uppercaseFilter);
  12423. }
  12424. /**
  12425. * @ngdoc filter
  12426. * @name ng.filter:filter
  12427. * @function
  12428. *
  12429. * @description
  12430. * Selects a subset of items from `array` and returns it as a new array.
  12431. *
  12432. * @param {Array} array The source array.
  12433. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  12434. * `array`.
  12435. *
  12436. * Can be one of:
  12437. *
  12438. * - `string`: Predicate that results in a substring match using the value of `expression`
  12439. * string. All strings or objects with string properties in `array` that contain this string
  12440. * will be returned. The predicate can be negated by prefixing the string with `!`.
  12441. *
  12442. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  12443. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  12444. * which have property `name` containing "M" and property `phone` containing "1". A special
  12445. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  12446. * property of the object. That's equivalent to the simple substring match with a `string`
  12447. * as described above.
  12448. *
  12449. * - `function`: A predicate function can be used to write arbitrary filters. The function is
  12450. * called for each element of `array`. The final result is an array of those elements that
  12451. * the predicate returned true for.
  12452. *
  12453. * @param {function(expected, actual)|true|undefined} comparator Comparator which is used in
  12454. * determining if the expected value (from the filter expression) and actual value (from
  12455. * the object in the array) should be considered a match.
  12456. *
  12457. * Can be one of:
  12458. *
  12459. * - `function(expected, actual)`:
  12460. * The function will be given the object value and the predicate value to compare and
  12461. * should return true if the item should be included in filtered result.
  12462. *
  12463. * - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`.
  12464. * this is essentially strict comparison of expected and actual.
  12465. *
  12466. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  12467. * insensitive way.
  12468. *
  12469. * @example
  12470. <doc:example>
  12471. <doc:source>
  12472. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  12473. {name:'Mary', phone:'800-BIG-MARY'},
  12474. {name:'Mike', phone:'555-4321'},
  12475. {name:'Adam', phone:'555-5678'},
  12476. {name:'Julie', phone:'555-8765'},
  12477. {name:'Juliette', phone:'555-5678'}]"></div>
  12478. Search: <input ng-model="searchText">
  12479. <table id="searchTextResults">
  12480. <tr><th>Name</th><th>Phone</th></tr>
  12481. <tr ng-repeat="friend in friends | filter:searchText">
  12482. <td>{{friend.name}}</td>
  12483. <td>{{friend.phone}}</td>
  12484. </tr>
  12485. </table>
  12486. <hr>
  12487. Any: <input ng-model="search.$"> <br>
  12488. Name only <input ng-model="search.name"><br>
  12489. Phone only <input ng-model="search.phone"><br>
  12490. Equality <input type="checkbox" ng-model="strict"><br>
  12491. <table id="searchObjResults">
  12492. <tr><th>Name</th><th>Phone</th></tr>
  12493. <tr ng-repeat="friend in friends | filter:search:strict">
  12494. <td>{{friend.name}}</td>
  12495. <td>{{friend.phone}}</td>
  12496. </tr>
  12497. </table>
  12498. </doc:source>
  12499. <doc:scenario>
  12500. it('should search across all fields when filtering with a string', function() {
  12501. input('searchText').enter('m');
  12502. expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
  12503. toEqual(['Mary', 'Mike', 'Adam']);
  12504. input('searchText').enter('76');
  12505. expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
  12506. toEqual(['John', 'Julie']);
  12507. });
  12508. it('should search in specific fields when filtering with a predicate object', function() {
  12509. input('search.$').enter('i');
  12510. expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
  12511. toEqual(['Mary', 'Mike', 'Julie', 'Juliette']);
  12512. });
  12513. it('should use a equal comparison when comparator is true', function() {
  12514. input('search.name').enter('Julie');
  12515. input('strict').check();
  12516. expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
  12517. toEqual(['Julie']);
  12518. });
  12519. </doc:scenario>
  12520. </doc:example>
  12521. */
  12522. function filterFilter() {
  12523. return function(array, expression, comparator) {
  12524. if (!isArray(array)) return array;
  12525. var comparatorType = typeof(comparator),
  12526. predicates = [];
  12527. predicates.check = function(value) {
  12528. for (var j = 0; j < predicates.length; j++) {
  12529. if(!predicates[j](value)) {
  12530. return false;
  12531. }
  12532. }
  12533. return true;
  12534. };
  12535. if (comparatorType !== 'function') {
  12536. if (comparatorType === 'boolean' && comparator) {
  12537. comparator = function(obj, text) {
  12538. return angular.equals(obj, text);
  12539. };
  12540. } else {
  12541. comparator = function(obj, text) {
  12542. text = (''+text).toLowerCase();
  12543. return (''+obj).toLowerCase().indexOf(text) > -1;
  12544. };
  12545. }
  12546. }
  12547. var search = function(obj, text){
  12548. if (typeof text == 'string' && text.charAt(0) === '!') {
  12549. return !search(obj, text.substr(1));
  12550. }
  12551. switch (typeof obj) {
  12552. case "boolean":
  12553. case "number":
  12554. case "string":
  12555. return comparator(obj, text);
  12556. case "object":
  12557. switch (typeof text) {
  12558. case "object":
  12559. return comparator(obj, text);
  12560. default:
  12561. for ( var objKey in obj) {
  12562. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  12563. return true;
  12564. }
  12565. }
  12566. break;
  12567. }
  12568. return false;
  12569. case "array":
  12570. for ( var i = 0; i < obj.length; i++) {
  12571. if (search(obj[i], text)) {
  12572. return true;
  12573. }
  12574. }
  12575. return false;
  12576. default:
  12577. return false;
  12578. }
  12579. };
  12580. switch (typeof expression) {
  12581. case "boolean":
  12582. case "number":
  12583. case "string":
  12584. // Set up expression object and fall through
  12585. expression = {$:expression};
  12586. // jshint -W086
  12587. case "object":
  12588. // jshint +W086
  12589. for (var key in expression) {
  12590. if (key == '$') {
  12591. (function() {
  12592. if (!expression[key]) return;
  12593. var path = key;
  12594. predicates.push(function(value) {
  12595. return search(value, expression[path]);
  12596. });
  12597. })();
  12598. } else {
  12599. (function() {
  12600. if (typeof(expression[key]) == 'undefined') { return; }
  12601. var path = key;
  12602. predicates.push(function(value) {
  12603. return search(getter(value,path), expression[path]);
  12604. });
  12605. })();
  12606. }
  12607. }
  12608. break;
  12609. case 'function':
  12610. predicates.push(expression);
  12611. break;
  12612. default:
  12613. return array;
  12614. }
  12615. var filtered = [];
  12616. for ( var j = 0; j < array.length; j++) {
  12617. var value = array[j];
  12618. if (predicates.check(value)) {
  12619. filtered.push(value);
  12620. }
  12621. }
  12622. return filtered;
  12623. };
  12624. }
  12625. /**
  12626. * @ngdoc filter
  12627. * @name ng.filter:currency
  12628. * @function
  12629. *
  12630. * @description
  12631. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  12632. * symbol for current locale is used.
  12633. *
  12634. * @param {number} amount Input to filter.
  12635. * @param {string=} symbol Currency symbol or identifier to be displayed.
  12636. * @returns {string} Formatted number.
  12637. *
  12638. *
  12639. * @example
  12640. <doc:example>
  12641. <doc:source>
  12642. <script>
  12643. function Ctrl($scope) {
  12644. $scope.amount = 1234.56;
  12645. }
  12646. </script>
  12647. <div ng-controller="Ctrl">
  12648. <input type="number" ng-model="amount"> <br>
  12649. default currency symbol ($): {{amount | currency}}<br>
  12650. custom currency identifier (USD$): {{amount | currency:"USD$"}}
  12651. </div>
  12652. </doc:source>
  12653. <doc:scenario>
  12654. it('should init with 1234.56', function() {
  12655. expect(binding('amount | currency')).toBe('$1,234.56');
  12656. expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
  12657. });
  12658. it('should update', function() {
  12659. input('amount').enter('-1234');
  12660. expect(binding('amount | currency')).toBe('($1,234.00)');
  12661. expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
  12662. });
  12663. </doc:scenario>
  12664. </doc:example>
  12665. */
  12666. currencyFilter.$inject = ['$locale'];
  12667. function currencyFilter($locale) {
  12668. var formats = $locale.NUMBER_FORMATS;
  12669. return function(amount, currencySymbol){
  12670. if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
  12671. return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
  12672. replace(/\u00A4/g, currencySymbol);
  12673. };
  12674. }
  12675. /**
  12676. * @ngdoc filter
  12677. * @name ng.filter:number
  12678. * @function
  12679. *
  12680. * @description
  12681. * Formats a number as text.
  12682. *
  12683. * If the input is not a number an empty string is returned.
  12684. *
  12685. * @param {number|string} number Number to format.
  12686. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  12687. * If this is not provided then the fraction size is computed from the current locale's number
  12688. * formatting pattern. In the case of the default locale, it will be 3.
  12689. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  12690. *
  12691. * @example
  12692. <doc:example>
  12693. <doc:source>
  12694. <script>
  12695. function Ctrl($scope) {
  12696. $scope.val = 1234.56789;
  12697. }
  12698. </script>
  12699. <div ng-controller="Ctrl">
  12700. Enter number: <input ng-model='val'><br>
  12701. Default formatting: {{val | number}}<br>
  12702. No fractions: {{val | number:0}}<br>
  12703. Negative number: {{-val | number:4}}
  12704. </div>
  12705. </doc:source>
  12706. <doc:scenario>
  12707. it('should format numbers', function() {
  12708. expect(binding('val | number')).toBe('1,234.568');
  12709. expect(binding('val | number:0')).toBe('1,235');
  12710. expect(binding('-val | number:4')).toBe('-1,234.5679');
  12711. });
  12712. it('should update', function() {
  12713. input('val').enter('3374.333');
  12714. expect(binding('val | number')).toBe('3,374.333');
  12715. expect(binding('val | number:0')).toBe('3,374');
  12716. expect(binding('-val | number:4')).toBe('-3,374.3330');
  12717. });
  12718. </doc:scenario>
  12719. </doc:example>
  12720. */
  12721. numberFilter.$inject = ['$locale'];
  12722. function numberFilter($locale) {
  12723. var formats = $locale.NUMBER_FORMATS;
  12724. return function(number, fractionSize) {
  12725. return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  12726. fractionSize);
  12727. };
  12728. }
  12729. var DECIMAL_SEP = '.';
  12730. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  12731. if (isNaN(number) || !isFinite(number)) return '';
  12732. var isNegative = number < 0;
  12733. number = Math.abs(number);
  12734. var numStr = number + '',
  12735. formatedText = '',
  12736. parts = [];
  12737. var hasExponent = false;
  12738. if (numStr.indexOf('e') !== -1) {
  12739. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  12740. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  12741. numStr = '0';
  12742. } else {
  12743. formatedText = numStr;
  12744. hasExponent = true;
  12745. }
  12746. }
  12747. if (!hasExponent) {
  12748. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  12749. // determine fractionSize if it is not specified
  12750. if (isUndefined(fractionSize)) {
  12751. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  12752. }
  12753. var pow = Math.pow(10, fractionSize);
  12754. number = Math.round(number * pow) / pow;
  12755. var fraction = ('' + number).split(DECIMAL_SEP);
  12756. var whole = fraction[0];
  12757. fraction = fraction[1] || '';
  12758. var i, pos = 0,
  12759. lgroup = pattern.lgSize,
  12760. group = pattern.gSize;
  12761. if (whole.length >= (lgroup + group)) {
  12762. pos = whole.length - lgroup;
  12763. for (i = 0; i < pos; i++) {
  12764. if ((pos - i)%group === 0 && i !== 0) {
  12765. formatedText += groupSep;
  12766. }
  12767. formatedText += whole.charAt(i);
  12768. }
  12769. }
  12770. for (i = pos; i < whole.length; i++) {
  12771. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  12772. formatedText += groupSep;
  12773. }
  12774. formatedText += whole.charAt(i);
  12775. }
  12776. // format fraction part.
  12777. while(fraction.length < fractionSize) {
  12778. fraction += '0';
  12779. }
  12780. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  12781. } else {
  12782. if (fractionSize > 0 && number > -1 && number < 1) {
  12783. formatedText = number.toFixed(fractionSize);
  12784. }
  12785. }
  12786. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  12787. parts.push(formatedText);
  12788. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  12789. return parts.join('');
  12790. }
  12791. function padNumber(num, digits, trim) {
  12792. var neg = '';
  12793. if (num < 0) {
  12794. neg = '-';
  12795. num = -num;
  12796. }
  12797. num = '' + num;
  12798. while(num.length < digits) num = '0' + num;
  12799. if (trim)
  12800. num = num.substr(num.length - digits);
  12801. return neg + num;
  12802. }
  12803. function dateGetter(name, size, offset, trim) {
  12804. offset = offset || 0;
  12805. return function(date) {
  12806. var value = date['get' + name]();
  12807. if (offset > 0 || value > -offset)
  12808. value += offset;
  12809. if (value === 0 && offset == -12 ) value = 12;
  12810. return padNumber(value, size, trim);
  12811. };
  12812. }
  12813. function dateStrGetter(name, shortForm) {
  12814. return function(date, formats) {
  12815. var value = date['get' + name]();
  12816. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  12817. return formats[get][value];
  12818. };
  12819. }
  12820. function timeZoneGetter(date) {
  12821. var zone = -1 * date.getTimezoneOffset();
  12822. var paddedZone = (zone >= 0) ? "+" : "";
  12823. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  12824. padNumber(Math.abs(zone % 60), 2);
  12825. return paddedZone;
  12826. }
  12827. function ampmGetter(date, formats) {
  12828. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  12829. }
  12830. var DATE_FORMATS = {
  12831. yyyy: dateGetter('FullYear', 4),
  12832. yy: dateGetter('FullYear', 2, 0, true),
  12833. y: dateGetter('FullYear', 1),
  12834. MMMM: dateStrGetter('Month'),
  12835. MMM: dateStrGetter('Month', true),
  12836. MM: dateGetter('Month', 2, 1),
  12837. M: dateGetter('Month', 1, 1),
  12838. dd: dateGetter('Date', 2),
  12839. d: dateGetter('Date', 1),
  12840. HH: dateGetter('Hours', 2),
  12841. H: dateGetter('Hours', 1),
  12842. hh: dateGetter('Hours', 2, -12),
  12843. h: dateGetter('Hours', 1, -12),
  12844. mm: dateGetter('Minutes', 2),
  12845. m: dateGetter('Minutes', 1),
  12846. ss: dateGetter('Seconds', 2),
  12847. s: dateGetter('Seconds', 1),
  12848. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  12849. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  12850. sss: dateGetter('Milliseconds', 3),
  12851. EEEE: dateStrGetter('Day'),
  12852. EEE: dateStrGetter('Day', true),
  12853. a: ampmGetter,
  12854. Z: timeZoneGetter
  12855. };
  12856. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
  12857. NUMBER_STRING = /^\-?\d+$/;
  12858. /**
  12859. * @ngdoc filter
  12860. * @name ng.filter:date
  12861. * @function
  12862. *
  12863. * @description
  12864. * Formats `date` to a string based on the requested `format`.
  12865. *
  12866. * `format` string can be composed of the following elements:
  12867. *
  12868. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  12869. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  12870. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  12871. * * `'MMMM'`: Month in year (January-December)
  12872. * * `'MMM'`: Month in year (Jan-Dec)
  12873. * * `'MM'`: Month in year, padded (01-12)
  12874. * * `'M'`: Month in year (1-12)
  12875. * * `'dd'`: Day in month, padded (01-31)
  12876. * * `'d'`: Day in month (1-31)
  12877. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  12878. * * `'EEE'`: Day in Week, (Sun-Sat)
  12879. * * `'HH'`: Hour in day, padded (00-23)
  12880. * * `'H'`: Hour in day (0-23)
  12881. * * `'hh'`: Hour in am/pm, padded (01-12)
  12882. * * `'h'`: Hour in am/pm, (1-12)
  12883. * * `'mm'`: Minute in hour, padded (00-59)
  12884. * * `'m'`: Minute in hour (0-59)
  12885. * * `'ss'`: Second in minute, padded (00-59)
  12886. * * `'s'`: Second in minute (0-59)
  12887. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  12888. * * `'a'`: am/pm marker
  12889. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  12890. *
  12891. * `format` string can also be one of the following predefined
  12892. * {@link guide/i18n localizable formats}:
  12893. *
  12894. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  12895. * (e.g. Sep 3, 2010 12:05:08 pm)
  12896. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
  12897. * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
  12898. * (e.g. Friday, September 3, 2010)
  12899. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  12900. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  12901. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  12902. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
  12903. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
  12904. *
  12905. * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
  12906. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
  12907. * (e.g. `"h 'o''clock'"`).
  12908. *
  12909. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  12910. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
  12911. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  12912. * specified in the string input, the time is considered to be in the local timezone.
  12913. * @param {string=} format Formatting rules (see Description). If not specified,
  12914. * `mediumDate` is used.
  12915. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  12916. *
  12917. * @example
  12918. <doc:example>
  12919. <doc:source>
  12920. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  12921. {{1288323623006 | date:'medium'}}<br>
  12922. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  12923. {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
  12924. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  12925. {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
  12926. </doc:source>
  12927. <doc:scenario>
  12928. it('should format date', function() {
  12929. expect(binding("1288323623006 | date:'medium'")).
  12930. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  12931. expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
  12932. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  12933. expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
  12934. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  12935. });
  12936. </doc:scenario>
  12937. </doc:example>
  12938. */
  12939. dateFilter.$inject = ['$locale'];
  12940. function dateFilter($locale) {
  12941. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  12942. // 1 2 3 4 5 6 7 8 9 10 11
  12943. function jsonStringToDate(string) {
  12944. var match;
  12945. if (match = string.match(R_ISO8601_STR)) {
  12946. var date = new Date(0),
  12947. tzHour = 0,
  12948. tzMin = 0,
  12949. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  12950. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  12951. if (match[9]) {
  12952. tzHour = int(match[9] + match[10]);
  12953. tzMin = int(match[9] + match[11]);
  12954. }
  12955. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  12956. var h = int(match[4]||0) - tzHour;
  12957. var m = int(match[5]||0) - tzMin;
  12958. var s = int(match[6]||0);
  12959. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  12960. timeSetter.call(date, h, m, s, ms);
  12961. return date;
  12962. }
  12963. return string;
  12964. }
  12965. return function(date, format) {
  12966. var text = '',
  12967. parts = [],
  12968. fn, match;
  12969. format = format || 'mediumDate';
  12970. format = $locale.DATETIME_FORMATS[format] || format;
  12971. if (isString(date)) {
  12972. if (NUMBER_STRING.test(date)) {
  12973. date = int(date);
  12974. } else {
  12975. date = jsonStringToDate(date);
  12976. }
  12977. }
  12978. if (isNumber(date)) {
  12979. date = new Date(date);
  12980. }
  12981. if (!isDate(date)) {
  12982. return date;
  12983. }
  12984. while(format) {
  12985. match = DATE_FORMATS_SPLIT.exec(format);
  12986. if (match) {
  12987. parts = concat(parts, match, 1);
  12988. format = parts.pop();
  12989. } else {
  12990. parts.push(format);
  12991. format = null;
  12992. }
  12993. }
  12994. forEach(parts, function(value){
  12995. fn = DATE_FORMATS[value];
  12996. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  12997. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  12998. });
  12999. return text;
  13000. };
  13001. }
  13002. /**
  13003. * @ngdoc filter
  13004. * @name ng.filter:json
  13005. * @function
  13006. *
  13007. * @description
  13008. * Allows you to convert a JavaScript object into JSON string.
  13009. *
  13010. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  13011. * the binding is automatically converted to JSON.
  13012. *
  13013. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  13014. * @returns {string} JSON string.
  13015. *
  13016. *
  13017. * @example:
  13018. <doc:example>
  13019. <doc:source>
  13020. <pre>{{ {'name':'value'} | json }}</pre>
  13021. </doc:source>
  13022. <doc:scenario>
  13023. it('should jsonify filtered objects', function() {
  13024. expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
  13025. });
  13026. </doc:scenario>
  13027. </doc:example>
  13028. *
  13029. */
  13030. function jsonFilter() {
  13031. return function(object) {
  13032. return toJson(object, true);
  13033. };
  13034. }
  13035. /**
  13036. * @ngdoc filter
  13037. * @name ng.filter:lowercase
  13038. * @function
  13039. * @description
  13040. * Converts string to lowercase.
  13041. * @see angular.lowercase
  13042. */
  13043. var lowercaseFilter = valueFn(lowercase);
  13044. /**
  13045. * @ngdoc filter
  13046. * @name ng.filter:uppercase
  13047. * @function
  13048. * @description
  13049. * Converts string to uppercase.
  13050. * @see angular.uppercase
  13051. */
  13052. var uppercaseFilter = valueFn(uppercase);
  13053. /**
  13054. * @ngdoc function
  13055. * @name ng.filter:limitTo
  13056. * @function
  13057. *
  13058. * @description
  13059. * Creates a new array or string containing only a specified number of elements. The elements
  13060. * are taken from either the beginning or the end of the source array or string, as specified by
  13061. * the value and sign (positive or negative) of `limit`.
  13062. *
  13063. * @param {Array|string} input Source array or string to be limited.
  13064. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  13065. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  13066. * If the number is negative, `limit` number of items from the end of the source array/string
  13067. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  13068. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  13069. * had less than `limit` elements.
  13070. *
  13071. * @example
  13072. <doc:example>
  13073. <doc:source>
  13074. <script>
  13075. function Ctrl($scope) {
  13076. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  13077. $scope.letters = "abcdefghi";
  13078. $scope.numLimit = 3;
  13079. $scope.letterLimit = 3;
  13080. }
  13081. </script>
  13082. <div ng-controller="Ctrl">
  13083. Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
  13084. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  13085. Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
  13086. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  13087. </div>
  13088. </doc:source>
  13089. <doc:scenario>
  13090. it('should limit the number array to first three items', function() {
  13091. expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3');
  13092. expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3');
  13093. expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]');
  13094. expect(binding('letters | limitTo:letterLimit')).toEqual('abc');
  13095. });
  13096. it('should update the output when -3 is entered', function() {
  13097. input('numLimit').enter(-3);
  13098. input('letterLimit').enter(-3);
  13099. expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]');
  13100. expect(binding('letters | limitTo:letterLimit')).toEqual('ghi');
  13101. });
  13102. it('should not exceed the maximum size of input array', function() {
  13103. input('numLimit').enter(100);
  13104. input('letterLimit').enter(100);
  13105. expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]');
  13106. expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi');
  13107. });
  13108. </doc:scenario>
  13109. </doc:example>
  13110. */
  13111. function limitToFilter(){
  13112. return function(input, limit) {
  13113. if (!isArray(input) && !isString(input)) return input;
  13114. limit = int(limit);
  13115. if (isString(input)) {
  13116. //NaN check on limit
  13117. if (limit) {
  13118. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  13119. } else {
  13120. return "";
  13121. }
  13122. }
  13123. var out = [],
  13124. i, n;
  13125. // if abs(limit) exceeds maximum length, trim it
  13126. if (limit > input.length)
  13127. limit = input.length;
  13128. else if (limit < -input.length)
  13129. limit = -input.length;
  13130. if (limit > 0) {
  13131. i = 0;
  13132. n = limit;
  13133. } else {
  13134. i = input.length + limit;
  13135. n = input.length;
  13136. }
  13137. for (; i<n; i++) {
  13138. out.push(input[i]);
  13139. }
  13140. return out;
  13141. };
  13142. }
  13143. /**
  13144. * @ngdoc function
  13145. * @name ng.filter:orderBy
  13146. * @function
  13147. *
  13148. * @description
  13149. * Orders a specified `array` by the `expression` predicate.
  13150. *
  13151. * @param {Array} array The array to sort.
  13152. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
  13153. * used by the comparator to determine the order of elements.
  13154. *
  13155. * Can be one of:
  13156. *
  13157. * - `function`: Getter function. The result of this function will be sorted using the
  13158. * `<`, `=`, `>` operator.
  13159. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
  13160. * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
  13161. * ascending or descending sort order (for example, +name or -name).
  13162. * - `Array`: An array of function or string predicates. The first predicate in the array
  13163. * is used for sorting, but when two items are equivalent, the next predicate is used.
  13164. *
  13165. * @param {boolean=} reverse Reverse the order the array.
  13166. * @returns {Array} Sorted copy of the source array.
  13167. *
  13168. * @example
  13169. <doc:example>
  13170. <doc:source>
  13171. <script>
  13172. function Ctrl($scope) {
  13173. $scope.friends =
  13174. [{name:'John', phone:'555-1212', age:10},
  13175. {name:'Mary', phone:'555-9876', age:19},
  13176. {name:'Mike', phone:'555-4321', age:21},
  13177. {name:'Adam', phone:'555-5678', age:35},
  13178. {name:'Julie', phone:'555-8765', age:29}]
  13179. $scope.predicate = '-age';
  13180. }
  13181. </script>
  13182. <div ng-controller="Ctrl">
  13183. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  13184. <hr/>
  13185. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  13186. <table class="friend">
  13187. <tr>
  13188. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  13189. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  13190. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  13191. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  13192. </tr>
  13193. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  13194. <td>{{friend.name}}</td>
  13195. <td>{{friend.phone}}</td>
  13196. <td>{{friend.age}}</td>
  13197. </tr>
  13198. </table>
  13199. </div>
  13200. </doc:source>
  13201. <doc:scenario>
  13202. it('should be reverse ordered by aged', function() {
  13203. expect(binding('predicate')).toBe('-age');
  13204. expect(repeater('table.friend', 'friend in friends').column('friend.age')).
  13205. toEqual(['35', '29', '21', '19', '10']);
  13206. expect(repeater('table.friend', 'friend in friends').column('friend.name')).
  13207. toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
  13208. });
  13209. it('should reorder the table when user selects different predicate', function() {
  13210. element('.doc-example-live a:contains("Name")').click();
  13211. expect(repeater('table.friend', 'friend in friends').column('friend.name')).
  13212. toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
  13213. expect(repeater('table.friend', 'friend in friends').column('friend.age')).
  13214. toEqual(['35', '10', '29', '19', '21']);
  13215. element('.doc-example-live a:contains("Phone")').click();
  13216. expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
  13217. toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
  13218. expect(repeater('table.friend', 'friend in friends').column('friend.name')).
  13219. toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
  13220. });
  13221. </doc:scenario>
  13222. </doc:example>
  13223. */
  13224. orderByFilter.$inject = ['$parse'];
  13225. function orderByFilter($parse){
  13226. return function(array, sortPredicate, reverseOrder) {
  13227. if (!isArray(array)) return array;
  13228. if (!sortPredicate) return array;
  13229. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  13230. sortPredicate = map(sortPredicate, function(predicate){
  13231. var descending = false, get = predicate || identity;
  13232. if (isString(predicate)) {
  13233. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  13234. descending = predicate.charAt(0) == '-';
  13235. predicate = predicate.substring(1);
  13236. }
  13237. get = $parse(predicate);
  13238. }
  13239. return reverseComparator(function(a,b){
  13240. return compare(get(a),get(b));
  13241. }, descending);
  13242. });
  13243. var arrayCopy = [];
  13244. for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  13245. return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
  13246. function comparator(o1, o2){
  13247. for ( var i = 0; i < sortPredicate.length; i++) {
  13248. var comp = sortPredicate[i](o1, o2);
  13249. if (comp !== 0) return comp;
  13250. }
  13251. return 0;
  13252. }
  13253. function reverseComparator(comp, descending) {
  13254. return toBoolean(descending)
  13255. ? function(a,b){return comp(b,a);}
  13256. : comp;
  13257. }
  13258. function compare(v1, v2){
  13259. var t1 = typeof v1;
  13260. var t2 = typeof v2;
  13261. if (t1 == t2) {
  13262. if (t1 == "string") {
  13263. v1 = v1.toLowerCase();
  13264. v2 = v2.toLowerCase();
  13265. }
  13266. if (v1 === v2) return 0;
  13267. return v1 < v2 ? -1 : 1;
  13268. } else {
  13269. return t1 < t2 ? -1 : 1;
  13270. }
  13271. }
  13272. };
  13273. }
  13274. function ngDirective(directive) {
  13275. if (isFunction(directive)) {
  13276. directive = {
  13277. link: directive
  13278. };
  13279. }
  13280. directive.restrict = directive.restrict || 'AC';
  13281. return valueFn(directive);
  13282. }
  13283. /**
  13284. * @ngdoc directive
  13285. * @name ng.directive:a
  13286. * @restrict E
  13287. *
  13288. * @description
  13289. * Modifies the default behavior of the html A tag so that the default action is prevented when
  13290. * the href attribute is empty.
  13291. *
  13292. * This change permits the easy creation of action links with the `ngClick` directive
  13293. * without changing the location or causing page reloads, e.g.:
  13294. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  13295. */
  13296. var htmlAnchorDirective = valueFn({
  13297. restrict: 'E',
  13298. compile: function(element, attr) {
  13299. if (msie <= 8) {
  13300. // turn <a href ng-click="..">link</a> into a stylable link in IE
  13301. // but only if it doesn't have name attribute, in which case it's an anchor
  13302. if (!attr.href && !attr.name) {
  13303. attr.$set('href', '');
  13304. }
  13305. // add a comment node to anchors to workaround IE bug that causes element content to be reset
  13306. // to new attribute content if attribute is updated with value containing @ and element also
  13307. // contains value with @
  13308. // see issue #1949
  13309. element.append(document.createComment('IE fix'));
  13310. }
  13311. if (!attr.href && !attr.name) {
  13312. return function(scope, element) {
  13313. element.on('click', function(event){
  13314. // if we have no href url, then don't navigate anywhere.
  13315. if (!element.attr('href')) {
  13316. event.preventDefault();
  13317. }
  13318. });
  13319. };
  13320. }
  13321. }
  13322. });
  13323. /**
  13324. * @ngdoc directive
  13325. * @name ng.directive:ngHref
  13326. * @restrict A
  13327. *
  13328. * @description
  13329. * Using Angular markup like `{{hash}}` in an href attribute will
  13330. * make the link go to the wrong URL if the user clicks it before
  13331. * Angular has a chance to replace the `{{hash}}` markup with its
  13332. * value. Until Angular replaces the markup the link will be broken
  13333. * and will most likely return a 404 error.
  13334. *
  13335. * The `ngHref` directive solves this problem.
  13336. *
  13337. * The wrong way to write it:
  13338. * <pre>
  13339. * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
  13340. * </pre>
  13341. *
  13342. * The correct way to write it:
  13343. * <pre>
  13344. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
  13345. * </pre>
  13346. *
  13347. * @element A
  13348. * @param {template} ngHref any string which can contain `{{}}` markup.
  13349. *
  13350. * @example
  13351. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  13352. * in links and their different behaviors:
  13353. <doc:example>
  13354. <doc:source>
  13355. <input ng-model="value" /><br />
  13356. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  13357. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  13358. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  13359. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  13360. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  13361. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  13362. </doc:source>
  13363. <doc:scenario>
  13364. it('should execute ng-click but not reload when href without value', function() {
  13365. element('#link-1').click();
  13366. expect(input('value').val()).toEqual('1');
  13367. expect(element('#link-1').attr('href')).toBe("");
  13368. });
  13369. it('should execute ng-click but not reload when href empty string', function() {
  13370. element('#link-2').click();
  13371. expect(input('value').val()).toEqual('2');
  13372. expect(element('#link-2').attr('href')).toBe("");
  13373. });
  13374. it('should execute ng-click and change url when ng-href specified', function() {
  13375. expect(element('#link-3').attr('href')).toBe("/123");
  13376. element('#link-3').click();
  13377. expect(browser().window().path()).toEqual('/123');
  13378. });
  13379. it('should execute ng-click but not reload when href empty string and name specified', function() {
  13380. element('#link-4').click();
  13381. expect(input('value').val()).toEqual('4');
  13382. expect(element('#link-4').attr('href')).toBe('');
  13383. });
  13384. it('should execute ng-click but not reload when no href but name specified', function() {
  13385. element('#link-5').click();
  13386. expect(input('value').val()).toEqual('5');
  13387. expect(element('#link-5').attr('href')).toBe(undefined);
  13388. });
  13389. it('should only change url when only ng-href', function() {
  13390. input('value').enter('6');
  13391. expect(element('#link-6').attr('href')).toBe('6');
  13392. element('#link-6').click();
  13393. expect(browser().location().url()).toEqual('/6');
  13394. });
  13395. </doc:scenario>
  13396. </doc:example>
  13397. */
  13398. /**
  13399. * @ngdoc directive
  13400. * @name ng.directive:ngSrc
  13401. * @restrict A
  13402. *
  13403. * @description
  13404. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  13405. * work right: The browser will fetch from the URL with the literal
  13406. * text `{{hash}}` until Angular replaces the expression inside
  13407. * `{{hash}}`. The `ngSrc` directive solves this problem.
  13408. *
  13409. * The buggy way to write it:
  13410. * <pre>
  13411. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  13412. * </pre>
  13413. *
  13414. * The correct way to write it:
  13415. * <pre>
  13416. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  13417. * </pre>
  13418. *
  13419. * @element IMG
  13420. * @param {template} ngSrc any string which can contain `{{}}` markup.
  13421. */
  13422. /**
  13423. * @ngdoc directive
  13424. * @name ng.directive:ngSrcset
  13425. * @restrict A
  13426. *
  13427. * @description
  13428. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  13429. * work right: The browser will fetch from the URL with the literal
  13430. * text `{{hash}}` until Angular replaces the expression inside
  13431. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  13432. *
  13433. * The buggy way to write it:
  13434. * <pre>
  13435. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  13436. * </pre>
  13437. *
  13438. * The correct way to write it:
  13439. * <pre>
  13440. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  13441. * </pre>
  13442. *
  13443. * @element IMG
  13444. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  13445. */
  13446. /**
  13447. * @ngdoc directive
  13448. * @name ng.directive:ngDisabled
  13449. * @restrict A
  13450. *
  13451. * @description
  13452. *
  13453. * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  13454. * <pre>
  13455. * <div ng-init="scope = { isDisabled: false }">
  13456. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  13457. * </div>
  13458. * </pre>
  13459. *
  13460. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13461. * such as disabled. (Their presence means true and their absence means false.)
  13462. * If we put an Angular interpolation expression into such an attribute then the
  13463. * binding information would be lost when the browser removes the attribute.
  13464. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  13465. * This complementary directive is not removed by the browser and so provides
  13466. * a permanent reliable place to store the binding information.
  13467. *
  13468. * @example
  13469. <doc:example>
  13470. <doc:source>
  13471. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  13472. <button ng-model="button" ng-disabled="checked">Button</button>
  13473. </doc:source>
  13474. <doc:scenario>
  13475. it('should toggle button', function() {
  13476. expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
  13477. input('checked').check();
  13478. expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
  13479. });
  13480. </doc:scenario>
  13481. </doc:example>
  13482. *
  13483. * @element INPUT
  13484. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  13485. * then special attribute "disabled" will be set on the element
  13486. */
  13487. /**
  13488. * @ngdoc directive
  13489. * @name ng.directive:ngChecked
  13490. * @restrict A
  13491. *
  13492. * @description
  13493. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13494. * such as checked. (Their presence means true and their absence means false.)
  13495. * If we put an Angular interpolation expression into such an attribute then the
  13496. * binding information would be lost when the browser removes the attribute.
  13497. * The `ngChecked` directive solves this problem for the `checked` attribute.
  13498. * This complementary directive is not removed by the browser and so provides
  13499. * a permanent reliable place to store the binding information.
  13500. * @example
  13501. <doc:example>
  13502. <doc:source>
  13503. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  13504. <input id="checkSlave" type="checkbox" ng-checked="master">
  13505. </doc:source>
  13506. <doc:scenario>
  13507. it('should check both checkBoxes', function() {
  13508. expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
  13509. input('master').check();
  13510. expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
  13511. });
  13512. </doc:scenario>
  13513. </doc:example>
  13514. *
  13515. * @element INPUT
  13516. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  13517. * then special attribute "checked" will be set on the element
  13518. */
  13519. /**
  13520. * @ngdoc directive
  13521. * @name ng.directive:ngReadonly
  13522. * @restrict A
  13523. *
  13524. * @description
  13525. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13526. * such as readonly. (Their presence means true and their absence means false.)
  13527. * If we put an Angular interpolation expression into such an attribute then the
  13528. * binding information would be lost when the browser removes the attribute.
  13529. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  13530. * This complementary directive is not removed by the browser and so provides
  13531. * a permanent reliable place to store the binding information.
  13532. * @example
  13533. <doc:example>
  13534. <doc:source>
  13535. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  13536. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  13537. </doc:source>
  13538. <doc:scenario>
  13539. it('should toggle readonly attr', function() {
  13540. expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
  13541. input('checked').check();
  13542. expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
  13543. });
  13544. </doc:scenario>
  13545. </doc:example>
  13546. *
  13547. * @element INPUT
  13548. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  13549. * then special attribute "readonly" will be set on the element
  13550. */
  13551. /**
  13552. * @ngdoc directive
  13553. * @name ng.directive:ngSelected
  13554. * @restrict A
  13555. *
  13556. * @description
  13557. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13558. * such as selected. (Their presence means true and their absence means false.)
  13559. * If we put an Angular interpolation expression into such an attribute then the
  13560. * binding information would be lost when the browser removes the attribute.
  13561. * The `ngSelected` directive solves this problem for the `selected` atttribute.
  13562. * This complementary directive is not removed by the browser and so provides
  13563. * a permanent reliable place to store the binding information.
  13564. * @example
  13565. <doc:example>
  13566. <doc:source>
  13567. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  13568. <select>
  13569. <option>Hello!</option>
  13570. <option id="greet" ng-selected="selected">Greetings!</option>
  13571. </select>
  13572. </doc:source>
  13573. <doc:scenario>
  13574. it('should select Greetings!', function() {
  13575. expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
  13576. input('selected').check();
  13577. expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
  13578. });
  13579. </doc:scenario>
  13580. </doc:example>
  13581. *
  13582. * @element OPTION
  13583. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  13584. * then special attribute "selected" will be set on the element
  13585. */
  13586. /**
  13587. * @ngdoc directive
  13588. * @name ng.directive:ngOpen
  13589. * @restrict A
  13590. *
  13591. * @description
  13592. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13593. * such as open. (Their presence means true and their absence means false.)
  13594. * If we put an Angular interpolation expression into such an attribute then the
  13595. * binding information would be lost when the browser removes the attribute.
  13596. * The `ngOpen` directive solves this problem for the `open` attribute.
  13597. * This complementary directive is not removed by the browser and so provides
  13598. * a permanent reliable place to store the binding information.
  13599. *
  13600. * @example
  13601. <doc:example>
  13602. <doc:source>
  13603. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  13604. <details id="details" ng-open="open">
  13605. <summary>Show/Hide me</summary>
  13606. </details>
  13607. </doc:source>
  13608. <doc:scenario>
  13609. it('should toggle open', function() {
  13610. expect(element('#details').prop('open')).toBeFalsy();
  13611. input('open').check();
  13612. expect(element('#details').prop('open')).toBeTruthy();
  13613. });
  13614. </doc:scenario>
  13615. </doc:example>
  13616. *
  13617. * @element DETAILS
  13618. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  13619. * then special attribute "open" will be set on the element
  13620. */
  13621. var ngAttributeAliasDirectives = {};
  13622. // boolean attrs are evaluated
  13623. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  13624. // binding to multiple is not supported
  13625. if (propName == "multiple") return;
  13626. var normalized = directiveNormalize('ng-' + attrName);
  13627. ngAttributeAliasDirectives[normalized] = function() {
  13628. return {
  13629. priority: 100,
  13630. compile: function() {
  13631. return function(scope, element, attr) {
  13632. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  13633. attr.$set(attrName, !!value);
  13634. });
  13635. };
  13636. }
  13637. };
  13638. };
  13639. });
  13640. // ng-src, ng-srcset, ng-href are interpolated
  13641. forEach(['src', 'srcset', 'href'], function(attrName) {
  13642. var normalized = directiveNormalize('ng-' + attrName);
  13643. ngAttributeAliasDirectives[normalized] = function() {
  13644. return {
  13645. priority: 99, // it needs to run after the attributes are interpolated
  13646. link: function(scope, element, attr) {
  13647. attr.$observe(normalized, function(value) {
  13648. if (!value)
  13649. return;
  13650. attr.$set(attrName, value);
  13651. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  13652. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  13653. // to set the property as well to achieve the desired effect.
  13654. // we use attr[attrName] value since $set can sanitize the url.
  13655. if (msie) element.prop(attrName, attr[attrName]);
  13656. });
  13657. }
  13658. };
  13659. };
  13660. });
  13661. /* global -nullFormCtrl */
  13662. var nullFormCtrl = {
  13663. $addControl: noop,
  13664. $removeControl: noop,
  13665. $setValidity: noop,
  13666. $setDirty: noop,
  13667. $setPristine: noop
  13668. };
  13669. /**
  13670. * @ngdoc object
  13671. * @name ng.directive:form.FormController
  13672. *
  13673. * @property {boolean} $pristine True if user has not interacted with the form yet.
  13674. * @property {boolean} $dirty True if user has already interacted with the form.
  13675. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  13676. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  13677. *
  13678. * @property {Object} $error Is an object hash, containing references to all invalid controls or
  13679. * forms, where:
  13680. *
  13681. * - keys are validation tokens (error names),
  13682. * - values are arrays of controls or forms that are invalid for given error name.
  13683. *
  13684. *
  13685. * Built-in validation tokens:
  13686. *
  13687. * - `email`
  13688. * - `max`
  13689. * - `maxlength`
  13690. * - `min`
  13691. * - `minlength`
  13692. * - `number`
  13693. * - `pattern`
  13694. * - `required`
  13695. * - `url`
  13696. *
  13697. * @description
  13698. * `FormController` keeps track of all its controls and nested forms as well as state of them,
  13699. * such as being valid/invalid or dirty/pristine.
  13700. *
  13701. * Each {@link ng.directive:form form} directive creates an instance
  13702. * of `FormController`.
  13703. *
  13704. */
  13705. //asks for $scope to fool the BC controller module
  13706. FormController.$inject = ['$element', '$attrs', '$scope'];
  13707. function FormController(element, attrs) {
  13708. var form = this,
  13709. parentForm = element.parent().controller('form') || nullFormCtrl,
  13710. invalidCount = 0, // used to easily determine if we are valid
  13711. errors = form.$error = {},
  13712. controls = [];
  13713. // init state
  13714. form.$name = attrs.name || attrs.ngForm;
  13715. form.$dirty = false;
  13716. form.$pristine = true;
  13717. form.$valid = true;
  13718. form.$invalid = false;
  13719. parentForm.$addControl(form);
  13720. // Setup initial state of the control
  13721. element.addClass(PRISTINE_CLASS);
  13722. toggleValidCss(true);
  13723. // convenience method for easy toggling of classes
  13724. function toggleValidCss(isValid, validationErrorKey) {
  13725. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  13726. element.
  13727. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
  13728. addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  13729. }
  13730. /**
  13731. * @ngdoc function
  13732. * @name ng.directive:form.FormController#$addControl
  13733. * @methodOf ng.directive:form.FormController
  13734. *
  13735. * @description
  13736. * Register a control with the form.
  13737. *
  13738. * Input elements using ngModelController do this automatically when they are linked.
  13739. */
  13740. form.$addControl = function(control) {
  13741. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  13742. // and not added to the scope. Now we throw an error.
  13743. assertNotHasOwnProperty(control.$name, 'input');
  13744. controls.push(control);
  13745. if (control.$name) {
  13746. form[control.$name] = control;
  13747. }
  13748. };
  13749. /**
  13750. * @ngdoc function
  13751. * @name ng.directive:form.FormController#$removeControl
  13752. * @methodOf ng.directive:form.FormController
  13753. *
  13754. * @description
  13755. * Deregister a control from the form.
  13756. *
  13757. * Input elements using ngModelController do this automatically when they are destroyed.
  13758. */
  13759. form.$removeControl = function(control) {
  13760. if (control.$name && form[control.$name] === control) {
  13761. delete form[control.$name];
  13762. }
  13763. forEach(errors, function(queue, validationToken) {
  13764. form.$setValidity(validationToken, true, control);
  13765. });
  13766. arrayRemove(controls, control);
  13767. };
  13768. /**
  13769. * @ngdoc function
  13770. * @name ng.directive:form.FormController#$setValidity
  13771. * @methodOf ng.directive:form.FormController
  13772. *
  13773. * @description
  13774. * Sets the validity of a form control.
  13775. *
  13776. * This method will also propagate to parent forms.
  13777. */
  13778. form.$setValidity = function(validationToken, isValid, control) {
  13779. var queue = errors[validationToken];
  13780. if (isValid) {
  13781. if (queue) {
  13782. arrayRemove(queue, control);
  13783. if (!queue.length) {
  13784. invalidCount--;
  13785. if (!invalidCount) {
  13786. toggleValidCss(isValid);
  13787. form.$valid = true;
  13788. form.$invalid = false;
  13789. }
  13790. errors[validationToken] = false;
  13791. toggleValidCss(true, validationToken);
  13792. parentForm.$setValidity(validationToken, true, form);
  13793. }
  13794. }
  13795. } else {
  13796. if (!invalidCount) {
  13797. toggleValidCss(isValid);
  13798. }
  13799. if (queue) {
  13800. if (includes(queue, control)) return;
  13801. } else {
  13802. errors[validationToken] = queue = [];
  13803. invalidCount++;
  13804. toggleValidCss(false, validationToken);
  13805. parentForm.$setValidity(validationToken, false, form);
  13806. }
  13807. queue.push(control);
  13808. form.$valid = false;
  13809. form.$invalid = true;
  13810. }
  13811. };
  13812. /**
  13813. * @ngdoc function
  13814. * @name ng.directive:form.FormController#$setDirty
  13815. * @methodOf ng.directive:form.FormController
  13816. *
  13817. * @description
  13818. * Sets the form to a dirty state.
  13819. *
  13820. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  13821. * state (ng-dirty class). This method will also propagate to parent forms.
  13822. */
  13823. form.$setDirty = function() {
  13824. element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
  13825. form.$dirty = true;
  13826. form.$pristine = false;
  13827. parentForm.$setDirty();
  13828. };
  13829. /**
  13830. * @ngdoc function
  13831. * @name ng.directive:form.FormController#$setPristine
  13832. * @methodOf ng.directive:form.FormController
  13833. *
  13834. * @description
  13835. * Sets the form to its pristine state.
  13836. *
  13837. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  13838. * state (ng-pristine class). This method will also propagate to all the controls contained
  13839. * in this form.
  13840. *
  13841. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  13842. * saving or resetting it.
  13843. */
  13844. form.$setPristine = function () {
  13845. element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
  13846. form.$dirty = false;
  13847. form.$pristine = true;
  13848. forEach(controls, function(control) {
  13849. control.$setPristine();
  13850. });
  13851. };
  13852. }
  13853. /**
  13854. * @ngdoc directive
  13855. * @name ng.directive:ngForm
  13856. * @restrict EAC
  13857. *
  13858. * @description
  13859. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  13860. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  13861. * sub-group of controls needs to be determined.
  13862. *
  13863. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  13864. * related scope, under this name.
  13865. *
  13866. */
  13867. /**
  13868. * @ngdoc directive
  13869. * @name ng.directive:form
  13870. * @restrict E
  13871. *
  13872. * @description
  13873. * Directive that instantiates
  13874. * {@link ng.directive:form.FormController FormController}.
  13875. *
  13876. * If the `name` attribute is specified, the form controller is published onto the current scope under
  13877. * this name.
  13878. *
  13879. * # Alias: {@link ng.directive:ngForm `ngForm`}
  13880. *
  13881. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  13882. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  13883. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  13884. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  13885. * using Angular validation directives in forms that are dynamically generated using the
  13886. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  13887. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  13888. * `ngForm` directive and nest these in an outer `form` element.
  13889. *
  13890. *
  13891. * # CSS classes
  13892. * - `ng-valid` Is set if the form is valid.
  13893. * - `ng-invalid` Is set if the form is invalid.
  13894. * - `ng-pristine` Is set if the form is pristine.
  13895. * - `ng-dirty` Is set if the form is dirty.
  13896. *
  13897. *
  13898. * # Submitting a form and preventing the default action
  13899. *
  13900. * Since the role of forms in client-side Angular applications is different than in classical
  13901. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  13902. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  13903. * to handle the form submission in an application-specific way.
  13904. *
  13905. * For this reason, Angular prevents the default action (form submission to the server) unless the
  13906. * `<form>` element has an `action` attribute specified.
  13907. *
  13908. * You can use one of the following two ways to specify what javascript method should be called when
  13909. * a form is submitted:
  13910. *
  13911. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  13912. * - {@link ng.directive:ngClick ngClick} directive on the first
  13913. * button or input field of type submit (input[type=submit])
  13914. *
  13915. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  13916. * or {@link ng.directive:ngClick ngClick} directives.
  13917. * This is because of the following form submission rules in the HTML specification:
  13918. *
  13919. * - If a form has only one input field then hitting enter in this field triggers form submit
  13920. * (`ngSubmit`)
  13921. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  13922. * doesn't trigger submit
  13923. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  13924. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  13925. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  13926. *
  13927. * @param {string=} name Name of the form. If specified, the form controller will be published into
  13928. * related scope, under this name.
  13929. *
  13930. * @example
  13931. <doc:example>
  13932. <doc:source>
  13933. <script>
  13934. function Ctrl($scope) {
  13935. $scope.userType = 'guest';
  13936. }
  13937. </script>
  13938. <form name="myForm" ng-controller="Ctrl">
  13939. userType: <input name="input" ng-model="userType" required>
  13940. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  13941. <tt>userType = {{userType}}</tt><br>
  13942. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  13943. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  13944. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  13945. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  13946. </form>
  13947. </doc:source>
  13948. <doc:scenario>
  13949. it('should initialize to model', function() {
  13950. expect(binding('userType')).toEqual('guest');
  13951. expect(binding('myForm.input.$valid')).toEqual('true');
  13952. });
  13953. it('should be invalid if empty', function() {
  13954. input('userType').enter('');
  13955. expect(binding('userType')).toEqual('');
  13956. expect(binding('myForm.input.$valid')).toEqual('false');
  13957. });
  13958. </doc:scenario>
  13959. </doc:example>
  13960. */
  13961. var formDirectiveFactory = function(isNgForm) {
  13962. return ['$timeout', function($timeout) {
  13963. var formDirective = {
  13964. name: 'form',
  13965. restrict: isNgForm ? 'EAC' : 'E',
  13966. controller: FormController,
  13967. compile: function() {
  13968. return {
  13969. pre: function(scope, formElement, attr, controller) {
  13970. if (!attr.action) {
  13971. // we can't use jq events because if a form is destroyed during submission the default
  13972. // action is not prevented. see #1238
  13973. //
  13974. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  13975. // page reload if the form was destroyed by submission of the form via a click handler
  13976. // on a button in the form. Looks like an IE9 specific bug.
  13977. var preventDefaultListener = function(event) {
  13978. event.preventDefault
  13979. ? event.preventDefault()
  13980. : event.returnValue = false; // IE
  13981. };
  13982. addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  13983. // unregister the preventDefault listener so that we don't not leak memory but in a
  13984. // way that will achieve the prevention of the default action.
  13985. formElement.on('$destroy', function() {
  13986. $timeout(function() {
  13987. removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  13988. }, 0, false);
  13989. });
  13990. }
  13991. var parentFormCtrl = formElement.parent().controller('form'),
  13992. alias = attr.name || attr.ngForm;
  13993. if (alias) {
  13994. setter(scope, alias, controller, alias);
  13995. }
  13996. if (parentFormCtrl) {
  13997. formElement.on('$destroy', function() {
  13998. parentFormCtrl.$removeControl(controller);
  13999. if (alias) {
  14000. setter(scope, alias, undefined, alias);
  14001. }
  14002. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  14003. });
  14004. }
  14005. }
  14006. };
  14007. }
  14008. };
  14009. return formDirective;
  14010. }];
  14011. };
  14012. var formDirective = formDirectiveFactory();
  14013. var ngFormDirective = formDirectiveFactory(true);
  14014. /* global
  14015. -VALID_CLASS,
  14016. -INVALID_CLASS,
  14017. -PRISTINE_CLASS,
  14018. -DIRTY_CLASS
  14019. */
  14020. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  14021. var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/;
  14022. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  14023. var inputType = {
  14024. /**
  14025. * @ngdoc inputType
  14026. * @name ng.directive:input.text
  14027. *
  14028. * @description
  14029. * Standard HTML text input with angular data binding.
  14030. *
  14031. * @param {string} ngModel Assignable angular expression to data-bind to.
  14032. * @param {string=} name Property name of the form under which the control is published.
  14033. * @param {string=} required Adds `required` validation error key if the value is not entered.
  14034. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14035. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14036. * `required` when you want to data-bind to the `required` attribute.
  14037. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14038. * minlength.
  14039. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14040. * maxlength.
  14041. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14042. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14043. * patterns defined as scope expressions.
  14044. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14045. * interaction with the input element.
  14046. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  14047. *
  14048. * @example
  14049. <doc:example>
  14050. <doc:source>
  14051. <script>
  14052. function Ctrl($scope) {
  14053. $scope.text = 'guest';
  14054. $scope.word = /^\s*\w*\s*$/;
  14055. }
  14056. </script>
  14057. <form name="myForm" ng-controller="Ctrl">
  14058. Single word: <input type="text" name="input" ng-model="text"
  14059. ng-pattern="word" required ng-trim="false">
  14060. <span class="error" ng-show="myForm.input.$error.required">
  14061. Required!</span>
  14062. <span class="error" ng-show="myForm.input.$error.pattern">
  14063. Single word only!</span>
  14064. <tt>text = {{text}}</tt><br/>
  14065. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14066. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14067. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14068. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14069. </form>
  14070. </doc:source>
  14071. <doc:scenario>
  14072. it('should initialize to model', function() {
  14073. expect(binding('text')).toEqual('guest');
  14074. expect(binding('myForm.input.$valid')).toEqual('true');
  14075. });
  14076. it('should be invalid if empty', function() {
  14077. input('text').enter('');
  14078. expect(binding('text')).toEqual('');
  14079. expect(binding('myForm.input.$valid')).toEqual('false');
  14080. });
  14081. it('should be invalid if multi word', function() {
  14082. input('text').enter('hello world');
  14083. expect(binding('myForm.input.$valid')).toEqual('false');
  14084. });
  14085. it('should not be trimmed', function() {
  14086. input('text').enter('untrimmed ');
  14087. expect(binding('text')).toEqual('untrimmed ');
  14088. expect(binding('myForm.input.$valid')).toEqual('true');
  14089. });
  14090. </doc:scenario>
  14091. </doc:example>
  14092. */
  14093. 'text': textInputType,
  14094. /**
  14095. * @ngdoc inputType
  14096. * @name ng.directive:input.number
  14097. *
  14098. * @description
  14099. * Text input with number validation and transformation. Sets the `number` validation
  14100. * error if not a valid number.
  14101. *
  14102. * @param {string} ngModel Assignable angular expression to data-bind to.
  14103. * @param {string=} name Property name of the form under which the control is published.
  14104. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  14105. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  14106. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14107. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14108. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14109. * `required` when you want to data-bind to the `required` attribute.
  14110. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14111. * minlength.
  14112. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14113. * maxlength.
  14114. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14115. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14116. * patterns defined as scope expressions.
  14117. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14118. * interaction with the input element.
  14119. *
  14120. * @example
  14121. <doc:example>
  14122. <doc:source>
  14123. <script>
  14124. function Ctrl($scope) {
  14125. $scope.value = 12;
  14126. }
  14127. </script>
  14128. <form name="myForm" ng-controller="Ctrl">
  14129. Number: <input type="number" name="input" ng-model="value"
  14130. min="0" max="99" required>
  14131. <span class="error" ng-show="myForm.input.$error.required">
  14132. Required!</span>
  14133. <span class="error" ng-show="myForm.input.$error.number">
  14134. Not valid number!</span>
  14135. <tt>value = {{value}}</tt><br/>
  14136. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14137. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14138. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14139. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14140. </form>
  14141. </doc:source>
  14142. <doc:scenario>
  14143. it('should initialize to model', function() {
  14144. expect(binding('value')).toEqual('12');
  14145. expect(binding('myForm.input.$valid')).toEqual('true');
  14146. });
  14147. it('should be invalid if empty', function() {
  14148. input('value').enter('');
  14149. expect(binding('value')).toEqual('');
  14150. expect(binding('myForm.input.$valid')).toEqual('false');
  14151. });
  14152. it('should be invalid if over max', function() {
  14153. input('value').enter('123');
  14154. expect(binding('value')).toEqual('');
  14155. expect(binding('myForm.input.$valid')).toEqual('false');
  14156. });
  14157. </doc:scenario>
  14158. </doc:example>
  14159. */
  14160. 'number': numberInputType,
  14161. /**
  14162. * @ngdoc inputType
  14163. * @name ng.directive:input.url
  14164. *
  14165. * @description
  14166. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  14167. * valid URL.
  14168. *
  14169. * @param {string} ngModel Assignable angular expression to data-bind to.
  14170. * @param {string=} name Property name of the form under which the control is published.
  14171. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14172. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14173. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14174. * `required` when you want to data-bind to the `required` attribute.
  14175. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14176. * minlength.
  14177. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14178. * maxlength.
  14179. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14180. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14181. * patterns defined as scope expressions.
  14182. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14183. * interaction with the input element.
  14184. *
  14185. * @example
  14186. <doc:example>
  14187. <doc:source>
  14188. <script>
  14189. function Ctrl($scope) {
  14190. $scope.text = 'http://google.com';
  14191. }
  14192. </script>
  14193. <form name="myForm" ng-controller="Ctrl">
  14194. URL: <input type="url" name="input" ng-model="text" required>
  14195. <span class="error" ng-show="myForm.input.$error.required">
  14196. Required!</span>
  14197. <span class="error" ng-show="myForm.input.$error.url">
  14198. Not valid url!</span>
  14199. <tt>text = {{text}}</tt><br/>
  14200. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14201. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14202. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14203. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14204. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  14205. </form>
  14206. </doc:source>
  14207. <doc:scenario>
  14208. it('should initialize to model', function() {
  14209. expect(binding('text')).toEqual('http://google.com');
  14210. expect(binding('myForm.input.$valid')).toEqual('true');
  14211. });
  14212. it('should be invalid if empty', function() {
  14213. input('text').enter('');
  14214. expect(binding('text')).toEqual('');
  14215. expect(binding('myForm.input.$valid')).toEqual('false');
  14216. });
  14217. it('should be invalid if not url', function() {
  14218. input('text').enter('xxx');
  14219. expect(binding('myForm.input.$valid')).toEqual('false');
  14220. });
  14221. </doc:scenario>
  14222. </doc:example>
  14223. */
  14224. 'url': urlInputType,
  14225. /**
  14226. * @ngdoc inputType
  14227. * @name ng.directive:input.email
  14228. *
  14229. * @description
  14230. * Text input with email validation. Sets the `email` validation error key if not a valid email
  14231. * address.
  14232. *
  14233. * @param {string} ngModel Assignable angular expression to data-bind to.
  14234. * @param {string=} name Property name of the form under which the control is published.
  14235. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14236. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14237. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14238. * `required` when you want to data-bind to the `required` attribute.
  14239. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14240. * minlength.
  14241. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14242. * maxlength.
  14243. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14244. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14245. * patterns defined as scope expressions.
  14246. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14247. * interaction with the input element.
  14248. *
  14249. * @example
  14250. <doc:example>
  14251. <doc:source>
  14252. <script>
  14253. function Ctrl($scope) {
  14254. $scope.text = '[email protected]';
  14255. }
  14256. </script>
  14257. <form name="myForm" ng-controller="Ctrl">
  14258. Email: <input type="email" name="input" ng-model="text" required>
  14259. <span class="error" ng-show="myForm.input.$error.required">
  14260. Required!</span>
  14261. <span class="error" ng-show="myForm.input.$error.email">
  14262. Not valid email!</span>
  14263. <tt>text = {{text}}</tt><br/>
  14264. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14265. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14266. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14267. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14268. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  14269. </form>
  14270. </doc:source>
  14271. <doc:scenario>
  14272. it('should initialize to model', function() {
  14273. expect(binding('text')).toEqual('[email protected]');
  14274. expect(binding('myForm.input.$valid')).toEqual('true');
  14275. });
  14276. it('should be invalid if empty', function() {
  14277. input('text').enter('');
  14278. expect(binding('text')).toEqual('');
  14279. expect(binding('myForm.input.$valid')).toEqual('false');
  14280. });
  14281. it('should be invalid if not email', function() {
  14282. input('text').enter('xxx');
  14283. expect(binding('myForm.input.$valid')).toEqual('false');
  14284. });
  14285. </doc:scenario>
  14286. </doc:example>
  14287. */
  14288. 'email': emailInputType,
  14289. /**
  14290. * @ngdoc inputType
  14291. * @name ng.directive:input.radio
  14292. *
  14293. * @description
  14294. * HTML radio button.
  14295. *
  14296. * @param {string} ngModel Assignable angular expression to data-bind to.
  14297. * @param {string} value The value to which the expression should be set when selected.
  14298. * @param {string=} name Property name of the form under which the control is published.
  14299. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14300. * interaction with the input element.
  14301. *
  14302. * @example
  14303. <doc:example>
  14304. <doc:source>
  14305. <script>
  14306. function Ctrl($scope) {
  14307. $scope.color = 'blue';
  14308. }
  14309. </script>
  14310. <form name="myForm" ng-controller="Ctrl">
  14311. <input type="radio" ng-model="color" value="red"> Red <br/>
  14312. <input type="radio" ng-model="color" value="green"> Green <br/>
  14313. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  14314. <tt>color = {{color}}</tt><br/>
  14315. </form>
  14316. </doc:source>
  14317. <doc:scenario>
  14318. it('should change state', function() {
  14319. expect(binding('color')).toEqual('blue');
  14320. input('color').select('red');
  14321. expect(binding('color')).toEqual('red');
  14322. });
  14323. </doc:scenario>
  14324. </doc:example>
  14325. */
  14326. 'radio': radioInputType,
  14327. /**
  14328. * @ngdoc inputType
  14329. * @name ng.directive:input.checkbox
  14330. *
  14331. * @description
  14332. * HTML checkbox.
  14333. *
  14334. * @param {string} ngModel Assignable angular expression to data-bind to.
  14335. * @param {string=} name Property name of the form under which the control is published.
  14336. * @param {string=} ngTrueValue The value to which the expression should be set when selected.
  14337. * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
  14338. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14339. * interaction with the input element.
  14340. *
  14341. * @example
  14342. <doc:example>
  14343. <doc:source>
  14344. <script>
  14345. function Ctrl($scope) {
  14346. $scope.value1 = true;
  14347. $scope.value2 = 'YES'
  14348. }
  14349. </script>
  14350. <form name="myForm" ng-controller="Ctrl">
  14351. Value1: <input type="checkbox" ng-model="value1"> <br/>
  14352. Value2: <input type="checkbox" ng-model="value2"
  14353. ng-true-value="YES" ng-false-value="NO"> <br/>
  14354. <tt>value1 = {{value1}}</tt><br/>
  14355. <tt>value2 = {{value2}}</tt><br/>
  14356. </form>
  14357. </doc:source>
  14358. <doc:scenario>
  14359. it('should change state', function() {
  14360. expect(binding('value1')).toEqual('true');
  14361. expect(binding('value2')).toEqual('YES');
  14362. input('value1').check();
  14363. input('value2').check();
  14364. expect(binding('value1')).toEqual('false');
  14365. expect(binding('value2')).toEqual('NO');
  14366. });
  14367. </doc:scenario>
  14368. </doc:example>
  14369. */
  14370. 'checkbox': checkboxInputType,
  14371. 'hidden': noop,
  14372. 'button': noop,
  14373. 'submit': noop,
  14374. 'reset': noop
  14375. };
  14376. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  14377. // In composition mode, users are still inputing intermediate text buffer,
  14378. // hold the listener until composition is done.
  14379. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  14380. var composing = false;
  14381. element.on('compositionstart', function() {
  14382. composing = true;
  14383. });
  14384. element.on('compositionend', function() {
  14385. composing = false;
  14386. });
  14387. var listener = function() {
  14388. if (composing) return;
  14389. var value = element.val();
  14390. // By default we will trim the value
  14391. // If the attribute ng-trim exists we will avoid trimming
  14392. // e.g. <input ng-model="foo" ng-trim="false">
  14393. if (toBoolean(attr.ngTrim || 'T')) {
  14394. value = trim(value);
  14395. }
  14396. if (ctrl.$viewValue !== value) {
  14397. scope.$apply(function() {
  14398. ctrl.$setViewValue(value);
  14399. });
  14400. }
  14401. };
  14402. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  14403. // input event on backspace, delete or cut
  14404. if ($sniffer.hasEvent('input')) {
  14405. element.on('input', listener);
  14406. } else {
  14407. var timeout;
  14408. var deferListener = function() {
  14409. if (!timeout) {
  14410. timeout = $browser.defer(function() {
  14411. listener();
  14412. timeout = null;
  14413. });
  14414. }
  14415. };
  14416. element.on('keydown', function(event) {
  14417. var key = event.keyCode;
  14418. // ignore
  14419. // command modifiers arrows
  14420. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  14421. deferListener();
  14422. });
  14423. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  14424. if ($sniffer.hasEvent('paste')) {
  14425. element.on('paste cut', deferListener);
  14426. }
  14427. }
  14428. // if user paste into input using mouse on older browser
  14429. // or form autocomplete on newer browser, we need "change" event to catch it
  14430. element.on('change', listener);
  14431. ctrl.$render = function() {
  14432. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  14433. };
  14434. // pattern validator
  14435. var pattern = attr.ngPattern,
  14436. patternValidator,
  14437. match;
  14438. var validate = function(regexp, value) {
  14439. if (ctrl.$isEmpty(value) || regexp.test(value)) {
  14440. ctrl.$setValidity('pattern', true);
  14441. return value;
  14442. } else {
  14443. ctrl.$setValidity('pattern', false);
  14444. return undefined;
  14445. }
  14446. };
  14447. if (pattern) {
  14448. match = pattern.match(/^\/(.*)\/([gim]*)$/);
  14449. if (match) {
  14450. pattern = new RegExp(match[1], match[2]);
  14451. patternValidator = function(value) {
  14452. return validate(pattern, value);
  14453. };
  14454. } else {
  14455. patternValidator = function(value) {
  14456. var patternObj = scope.$eval(pattern);
  14457. if (!patternObj || !patternObj.test) {
  14458. throw minErr('ngPattern')('noregexp',
  14459. 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
  14460. patternObj, startingTag(element));
  14461. }
  14462. return validate(patternObj, value);
  14463. };
  14464. }
  14465. ctrl.$formatters.push(patternValidator);
  14466. ctrl.$parsers.push(patternValidator);
  14467. }
  14468. // min length validator
  14469. if (attr.ngMinlength) {
  14470. var minlength = int(attr.ngMinlength);
  14471. var minLengthValidator = function(value) {
  14472. if (!ctrl.$isEmpty(value) && value.length < minlength) {
  14473. ctrl.$setValidity('minlength', false);
  14474. return undefined;
  14475. } else {
  14476. ctrl.$setValidity('minlength', true);
  14477. return value;
  14478. }
  14479. };
  14480. ctrl.$parsers.push(minLengthValidator);
  14481. ctrl.$formatters.push(minLengthValidator);
  14482. }
  14483. // max length validator
  14484. if (attr.ngMaxlength) {
  14485. var maxlength = int(attr.ngMaxlength);
  14486. var maxLengthValidator = function(value) {
  14487. if (!ctrl.$isEmpty(value) && value.length > maxlength) {
  14488. ctrl.$setValidity('maxlength', false);
  14489. return undefined;
  14490. } else {
  14491. ctrl.$setValidity('maxlength', true);
  14492. return value;
  14493. }
  14494. };
  14495. ctrl.$parsers.push(maxLengthValidator);
  14496. ctrl.$formatters.push(maxLengthValidator);
  14497. }
  14498. }
  14499. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  14500. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  14501. ctrl.$parsers.push(function(value) {
  14502. var empty = ctrl.$isEmpty(value);
  14503. if (empty || NUMBER_REGEXP.test(value)) {
  14504. ctrl.$setValidity('number', true);
  14505. return value === '' ? null : (empty ? value : parseFloat(value));
  14506. } else {
  14507. ctrl.$setValidity('number', false);
  14508. return undefined;
  14509. }
  14510. });
  14511. ctrl.$formatters.push(function(value) {
  14512. return ctrl.$isEmpty(value) ? '' : '' + value;
  14513. });
  14514. if (attr.min) {
  14515. var minValidator = function(value) {
  14516. var min = parseFloat(attr.min);
  14517. if (!ctrl.$isEmpty(value) && value < min) {
  14518. ctrl.$setValidity('min', false);
  14519. return undefined;
  14520. } else {
  14521. ctrl.$setValidity('min', true);
  14522. return value;
  14523. }
  14524. };
  14525. ctrl.$parsers.push(minValidator);
  14526. ctrl.$formatters.push(minValidator);
  14527. }
  14528. if (attr.max) {
  14529. var maxValidator = function(value) {
  14530. var max = parseFloat(attr.max);
  14531. if (!ctrl.$isEmpty(value) && value > max) {
  14532. ctrl.$setValidity('max', false);
  14533. return undefined;
  14534. } else {
  14535. ctrl.$setValidity('max', true);
  14536. return value;
  14537. }
  14538. };
  14539. ctrl.$parsers.push(maxValidator);
  14540. ctrl.$formatters.push(maxValidator);
  14541. }
  14542. ctrl.$formatters.push(function(value) {
  14543. if (ctrl.$isEmpty(value) || isNumber(value)) {
  14544. ctrl.$setValidity('number', true);
  14545. return value;
  14546. } else {
  14547. ctrl.$setValidity('number', false);
  14548. return undefined;
  14549. }
  14550. });
  14551. }
  14552. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  14553. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  14554. var urlValidator = function(value) {
  14555. if (ctrl.$isEmpty(value) || URL_REGEXP.test(value)) {
  14556. ctrl.$setValidity('url', true);
  14557. return value;
  14558. } else {
  14559. ctrl.$setValidity('url', false);
  14560. return undefined;
  14561. }
  14562. };
  14563. ctrl.$formatters.push(urlValidator);
  14564. ctrl.$parsers.push(urlValidator);
  14565. }
  14566. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  14567. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  14568. var emailValidator = function(value) {
  14569. if (ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value)) {
  14570. ctrl.$setValidity('email', true);
  14571. return value;
  14572. } else {
  14573. ctrl.$setValidity('email', false);
  14574. return undefined;
  14575. }
  14576. };
  14577. ctrl.$formatters.push(emailValidator);
  14578. ctrl.$parsers.push(emailValidator);
  14579. }
  14580. function radioInputType(scope, element, attr, ctrl) {
  14581. // make the name unique, if not defined
  14582. if (isUndefined(attr.name)) {
  14583. element.attr('name', nextUid());
  14584. }
  14585. element.on('click', function() {
  14586. if (element[0].checked) {
  14587. scope.$apply(function() {
  14588. ctrl.$setViewValue(attr.value);
  14589. });
  14590. }
  14591. });
  14592. ctrl.$render = function() {
  14593. var value = attr.value;
  14594. element[0].checked = (value == ctrl.$viewValue);
  14595. };
  14596. attr.$observe('value', ctrl.$render);
  14597. }
  14598. function checkboxInputType(scope, element, attr, ctrl) {
  14599. var trueValue = attr.ngTrueValue,
  14600. falseValue = attr.ngFalseValue;
  14601. if (!isString(trueValue)) trueValue = true;
  14602. if (!isString(falseValue)) falseValue = false;
  14603. element.on('click', function() {
  14604. scope.$apply(function() {
  14605. ctrl.$setViewValue(element[0].checked);
  14606. });
  14607. });
  14608. ctrl.$render = function() {
  14609. element[0].checked = ctrl.$viewValue;
  14610. };
  14611. // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
  14612. ctrl.$isEmpty = function(value) {
  14613. return value !== trueValue;
  14614. };
  14615. ctrl.$formatters.push(function(value) {
  14616. return value === trueValue;
  14617. });
  14618. ctrl.$parsers.push(function(value) {
  14619. return value ? trueValue : falseValue;
  14620. });
  14621. }
  14622. /**
  14623. * @ngdoc directive
  14624. * @name ng.directive:textarea
  14625. * @restrict E
  14626. *
  14627. * @description
  14628. * HTML textarea element control with angular data-binding. The data-binding and validation
  14629. * properties of this element are exactly the same as those of the
  14630. * {@link ng.directive:input input element}.
  14631. *
  14632. * @param {string} ngModel Assignable angular expression to data-bind to.
  14633. * @param {string=} name Property name of the form under which the control is published.
  14634. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14635. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14636. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14637. * `required` when you want to data-bind to the `required` attribute.
  14638. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14639. * minlength.
  14640. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14641. * maxlength.
  14642. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14643. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14644. * patterns defined as scope expressions.
  14645. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14646. * interaction with the input element.
  14647. */
  14648. /**
  14649. * @ngdoc directive
  14650. * @name ng.directive:input
  14651. * @restrict E
  14652. *
  14653. * @description
  14654. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  14655. * and polyfills the HTML5 validation behavior for older browsers.
  14656. *
  14657. * @param {string} ngModel Assignable angular expression to data-bind to.
  14658. * @param {string=} name Property name of the form under which the control is published.
  14659. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14660. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  14661. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14662. * minlength.
  14663. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14664. * maxlength.
  14665. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14666. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14667. * patterns defined as scope expressions.
  14668. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14669. * interaction with the input element.
  14670. *
  14671. * @example
  14672. <doc:example>
  14673. <doc:source>
  14674. <script>
  14675. function Ctrl($scope) {
  14676. $scope.user = {name: 'guest', last: 'visitor'};
  14677. }
  14678. </script>
  14679. <div ng-controller="Ctrl">
  14680. <form name="myForm">
  14681. User name: <input type="text" name="userName" ng-model="user.name" required>
  14682. <span class="error" ng-show="myForm.userName.$error.required">
  14683. Required!</span><br>
  14684. Last name: <input type="text" name="lastName" ng-model="user.last"
  14685. ng-minlength="3" ng-maxlength="10">
  14686. <span class="error" ng-show="myForm.lastName.$error.minlength">
  14687. Too short!</span>
  14688. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  14689. Too long!</span><br>
  14690. </form>
  14691. <hr>
  14692. <tt>user = {{user}}</tt><br/>
  14693. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  14694. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  14695. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  14696. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  14697. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  14698. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  14699. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  14700. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  14701. </div>
  14702. </doc:source>
  14703. <doc:scenario>
  14704. it('should initialize to model', function() {
  14705. expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
  14706. expect(binding('myForm.userName.$valid')).toEqual('true');
  14707. expect(binding('myForm.$valid')).toEqual('true');
  14708. });
  14709. it('should be invalid if empty when required', function() {
  14710. input('user.name').enter('');
  14711. expect(binding('user')).toEqual('{"last":"visitor"}');
  14712. expect(binding('myForm.userName.$valid')).toEqual('false');
  14713. expect(binding('myForm.$valid')).toEqual('false');
  14714. });
  14715. it('should be valid if empty when min length is set', function() {
  14716. input('user.last').enter('');
  14717. expect(binding('user')).toEqual('{"name":"guest","last":""}');
  14718. expect(binding('myForm.lastName.$valid')).toEqual('true');
  14719. expect(binding('myForm.$valid')).toEqual('true');
  14720. });
  14721. it('should be invalid if less than required min length', function() {
  14722. input('user.last').enter('xx');
  14723. expect(binding('user')).toEqual('{"name":"guest"}');
  14724. expect(binding('myForm.lastName.$valid')).toEqual('false');
  14725. expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
  14726. expect(binding('myForm.$valid')).toEqual('false');
  14727. });
  14728. it('should be invalid if longer than max length', function() {
  14729. input('user.last').enter('some ridiculously long name');
  14730. expect(binding('user'))
  14731. .toEqual('{"name":"guest"}');
  14732. expect(binding('myForm.lastName.$valid')).toEqual('false');
  14733. expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
  14734. expect(binding('myForm.$valid')).toEqual('false');
  14735. });
  14736. </doc:scenario>
  14737. </doc:example>
  14738. */
  14739. var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
  14740. return {
  14741. restrict: 'E',
  14742. require: '?ngModel',
  14743. link: function(scope, element, attr, ctrl) {
  14744. if (ctrl) {
  14745. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
  14746. $browser);
  14747. }
  14748. }
  14749. };
  14750. }];
  14751. var VALID_CLASS = 'ng-valid',
  14752. INVALID_CLASS = 'ng-invalid',
  14753. PRISTINE_CLASS = 'ng-pristine',
  14754. DIRTY_CLASS = 'ng-dirty';
  14755. /**
  14756. * @ngdoc object
  14757. * @name ng.directive:ngModel.NgModelController
  14758. *
  14759. * @property {string} $viewValue Actual string value in the view.
  14760. * @property {*} $modelValue The value in the model, that the control is bound to.
  14761. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  14762. the control reads value from the DOM. Each function is called, in turn, passing the value
  14763. through to the next. Used to sanitize / convert the value as well as validation.
  14764. For validation, the parsers should update the validity state using
  14765. {@link ng.directive:ngModel.NgModelController#methods_$setValidity $setValidity()},
  14766. and return `undefined` for invalid values.
  14767. *
  14768. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  14769. the model value changes. Each function is called, in turn, passing the value through to the
  14770. next. Used to format / convert values for display in the control and validation.
  14771. * <pre>
  14772. * function formatter(value) {
  14773. * if (value) {
  14774. * return value.toUpperCase();
  14775. * }
  14776. * }
  14777. * ngModel.$formatters.push(formatter);
  14778. * </pre>
  14779. *
  14780. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  14781. * view value has changed. It is called with no arguments, and its return value is ignored.
  14782. * This can be used in place of additional $watches against the model value.
  14783. *
  14784. * @property {Object} $error An object hash with all errors as keys.
  14785. *
  14786. * @property {boolean} $pristine True if user has not interacted with the control yet.
  14787. * @property {boolean} $dirty True if user has already interacted with the control.
  14788. * @property {boolean} $valid True if there is no error.
  14789. * @property {boolean} $invalid True if at least one error on the control.
  14790. *
  14791. * @description
  14792. *
  14793. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  14794. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  14795. * purposefully does not contain any logic which deals with DOM rendering or listening to
  14796. * DOM events. Such DOM related logic should be provided by other directives which make use of
  14797. * `NgModelController` for data-binding.
  14798. *
  14799. * ## Custom Control Example
  14800. * This example shows how to use `NgModelController` with a custom control to achieve
  14801. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  14802. * collaborate together to achieve the desired result.
  14803. *
  14804. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  14805. * contents be edited in place by the user. This will not work on older browsers.
  14806. *
  14807. * <example module="customControl">
  14808. <file name="style.css">
  14809. [contenteditable] {
  14810. border: 1px solid black;
  14811. background-color: white;
  14812. min-height: 20px;
  14813. }
  14814. .ng-invalid {
  14815. border: 1px solid red;
  14816. }
  14817. </file>
  14818. <file name="script.js">
  14819. angular.module('customControl', []).
  14820. directive('contenteditable', function() {
  14821. return {
  14822. restrict: 'A', // only activate on element attribute
  14823. require: '?ngModel', // get a hold of NgModelController
  14824. link: function(scope, element, attrs, ngModel) {
  14825. if(!ngModel) return; // do nothing if no ng-model
  14826. // Specify how UI should be updated
  14827. ngModel.$render = function() {
  14828. element.html(ngModel.$viewValue || '');
  14829. };
  14830. // Listen for change events to enable binding
  14831. element.on('blur keyup change', function() {
  14832. scope.$apply(read);
  14833. });
  14834. read(); // initialize
  14835. // Write data to the model
  14836. function read() {
  14837. var html = element.html();
  14838. // When we clear the content editable the browser leaves a <br> behind
  14839. // If strip-br attribute is provided then we strip this out
  14840. if( attrs.stripBr && html == '<br>' ) {
  14841. html = '';
  14842. }
  14843. ngModel.$setViewValue(html);
  14844. }
  14845. }
  14846. };
  14847. });
  14848. </file>
  14849. <file name="index.html">
  14850. <form name="myForm">
  14851. <div contenteditable
  14852. name="myWidget" ng-model="userContent"
  14853. strip-br="true"
  14854. required>Change me!</div>
  14855. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  14856. <hr>
  14857. <textarea ng-model="userContent"></textarea>
  14858. </form>
  14859. </file>
  14860. <file name="scenario.js">
  14861. it('should data-bind and become invalid', function() {
  14862. var contentEditable = element('[contenteditable]');
  14863. expect(contentEditable.text()).toEqual('Change me!');
  14864. input('userContent').enter('');
  14865. expect(contentEditable.text()).toEqual('');
  14866. expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
  14867. });
  14868. </file>
  14869. * </example>
  14870. *
  14871. *
  14872. */
  14873. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
  14874. function($scope, $exceptionHandler, $attr, $element, $parse) {
  14875. this.$viewValue = Number.NaN;
  14876. this.$modelValue = Number.NaN;
  14877. this.$parsers = [];
  14878. this.$formatters = [];
  14879. this.$viewChangeListeners = [];
  14880. this.$pristine = true;
  14881. this.$dirty = false;
  14882. this.$valid = true;
  14883. this.$invalid = false;
  14884. this.$name = $attr.name;
  14885. var ngModelGet = $parse($attr.ngModel),
  14886. ngModelSet = ngModelGet.assign;
  14887. if (!ngModelSet) {
  14888. throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  14889. $attr.ngModel, startingTag($element));
  14890. }
  14891. /**
  14892. * @ngdoc function
  14893. * @name ng.directive:ngModel.NgModelController#$render
  14894. * @methodOf ng.directive:ngModel.NgModelController
  14895. *
  14896. * @description
  14897. * Called when the view needs to be updated. It is expected that the user of the ng-model
  14898. * directive will implement this method.
  14899. */
  14900. this.$render = noop;
  14901. /**
  14902. * @ngdoc function
  14903. * @name { ng.directive:ngModel.NgModelController#$isEmpty
  14904. * @methodOf ng.directive:ngModel.NgModelController
  14905. *
  14906. * @description
  14907. * This is called when we need to determine if the value of the input is empty.
  14908. *
  14909. * For instance, the required directive does this to work out if the input has data or not.
  14910. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  14911. *
  14912. * You can override this for input directives whose concept of being empty is different to the
  14913. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  14914. * implies empty.
  14915. */
  14916. this.$isEmpty = function(value) {
  14917. return isUndefined(value) || value === '' || value === null || value !== value;
  14918. };
  14919. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  14920. invalidCount = 0, // used to easily determine if we are valid
  14921. $error = this.$error = {}; // keep invalid keys here
  14922. // Setup initial state of the control
  14923. $element.addClass(PRISTINE_CLASS);
  14924. toggleValidCss(true);
  14925. // convenience method for easy toggling of classes
  14926. function toggleValidCss(isValid, validationErrorKey) {
  14927. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  14928. $element.
  14929. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
  14930. addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  14931. }
  14932. /**
  14933. * @ngdoc function
  14934. * @name ng.directive:ngModel.NgModelController#$setValidity
  14935. * @methodOf ng.directive:ngModel.NgModelController
  14936. *
  14937. * @description
  14938. * Change the validity state, and notifies the form when the control changes validity. (i.e. it
  14939. * does not notify form if given validator is already marked as invalid).
  14940. *
  14941. * This method should be called by validators - i.e. the parser or formatter functions.
  14942. *
  14943. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  14944. * to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
  14945. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  14946. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  14947. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  14948. * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
  14949. */
  14950. this.$setValidity = function(validationErrorKey, isValid) {
  14951. // Purposeful use of ! here to cast isValid to boolean in case it is undefined
  14952. // jshint -W018
  14953. if ($error[validationErrorKey] === !isValid) return;
  14954. // jshint +W018
  14955. if (isValid) {
  14956. if ($error[validationErrorKey]) invalidCount--;
  14957. if (!invalidCount) {
  14958. toggleValidCss(true);
  14959. this.$valid = true;
  14960. this.$invalid = false;
  14961. }
  14962. } else {
  14963. toggleValidCss(false);
  14964. this.$invalid = true;
  14965. this.$valid = false;
  14966. invalidCount++;
  14967. }
  14968. $error[validationErrorKey] = !isValid;
  14969. toggleValidCss(isValid, validationErrorKey);
  14970. parentForm.$setValidity(validationErrorKey, isValid, this);
  14971. };
  14972. /**
  14973. * @ngdoc function
  14974. * @name ng.directive:ngModel.NgModelController#$setPristine
  14975. * @methodOf ng.directive:ngModel.NgModelController
  14976. *
  14977. * @description
  14978. * Sets the control to its pristine state.
  14979. *
  14980. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  14981. * state (ng-pristine class).
  14982. */
  14983. this.$setPristine = function () {
  14984. this.$dirty = false;
  14985. this.$pristine = true;
  14986. $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
  14987. };
  14988. /**
  14989. * @ngdoc function
  14990. * @name ng.directive:ngModel.NgModelController#$setViewValue
  14991. * @methodOf ng.directive:ngModel.NgModelController
  14992. *
  14993. * @description
  14994. * Update the view value.
  14995. *
  14996. * This method should be called when the view value changes, typically from within a DOM event handler.
  14997. * For example {@link ng.directive:input input} and
  14998. * {@link ng.directive:select select} directives call it.
  14999. *
  15000. * It will update the $viewValue, then pass this value through each of the functions in `$parsers`,
  15001. * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to
  15002. * `$modelValue` and the **expression** specified in the `ng-model` attribute.
  15003. *
  15004. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  15005. *
  15006. * Note that calling this function does not trigger a `$digest`.
  15007. *
  15008. * @param {string} value Value from the view.
  15009. */
  15010. this.$setViewValue = function(value) {
  15011. this.$viewValue = value;
  15012. // change to dirty
  15013. if (this.$pristine) {
  15014. this.$dirty = true;
  15015. this.$pristine = false;
  15016. $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
  15017. parentForm.$setDirty();
  15018. }
  15019. forEach(this.$parsers, function(fn) {
  15020. value = fn(value);
  15021. });
  15022. if (this.$modelValue !== value) {
  15023. this.$modelValue = value;
  15024. ngModelSet($scope, value);
  15025. forEach(this.$viewChangeListeners, function(listener) {
  15026. try {
  15027. listener();
  15028. } catch(e) {
  15029. $exceptionHandler(e);
  15030. }
  15031. });
  15032. }
  15033. };
  15034. // model -> value
  15035. var ctrl = this;
  15036. $scope.$watch(function ngModelWatch() {
  15037. var value = ngModelGet($scope);
  15038. // if scope model value and ngModel value are out of sync
  15039. if (ctrl.$modelValue !== value) {
  15040. var formatters = ctrl.$formatters,
  15041. idx = formatters.length;
  15042. ctrl.$modelValue = value;
  15043. while(idx--) {
  15044. value = formatters[idx](value);
  15045. }
  15046. if (ctrl.$viewValue !== value) {
  15047. ctrl.$viewValue = value;
  15048. ctrl.$render();
  15049. }
  15050. }
  15051. return value;
  15052. });
  15053. }];
  15054. /**
  15055. * @ngdoc directive
  15056. * @name ng.directive:ngModel
  15057. *
  15058. * @element input
  15059. *
  15060. * @description
  15061. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  15062. * property on the scope using {@link ng.directive:ngModel.NgModelController NgModelController},
  15063. * which is created and exposed by this directive.
  15064. *
  15065. * `ngModel` is responsible for:
  15066. *
  15067. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  15068. * require.
  15069. * - Providing validation behavior (i.e. required, number, email, url).
  15070. * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
  15071. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`).
  15072. * - Registering the control with its parent {@link ng.directive:form form}.
  15073. *
  15074. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  15075. * current scope. If the property doesn't already exist on this scope, it will be created
  15076. * implicitly and added to the scope.
  15077. *
  15078. * For best practices on using `ngModel`, see:
  15079. *
  15080. * - {@link https://github.com/angular/angular.js/wiki/Understanding-Scopes}
  15081. *
  15082. * For basic examples, how to use `ngModel`, see:
  15083. *
  15084. * - {@link ng.directive:input input}
  15085. * - {@link ng.directive:input.text text}
  15086. * - {@link ng.directive:input.checkbox checkbox}
  15087. * - {@link ng.directive:input.radio radio}
  15088. * - {@link ng.directive:input.number number}
  15089. * - {@link ng.directive:input.email email}
  15090. * - {@link ng.directive:input.url url}
  15091. * - {@link ng.directive:select select}
  15092. * - {@link ng.directive:textarea textarea}
  15093. *
  15094. */
  15095. var ngModelDirective = function() {
  15096. return {
  15097. require: ['ngModel', '^?form'],
  15098. controller: NgModelController,
  15099. link: function(scope, element, attr, ctrls) {
  15100. // notify others, especially parent forms
  15101. var modelCtrl = ctrls[0],
  15102. formCtrl = ctrls[1] || nullFormCtrl;
  15103. formCtrl.$addControl(modelCtrl);
  15104. scope.$on('$destroy', function() {
  15105. formCtrl.$removeControl(modelCtrl);
  15106. });
  15107. }
  15108. };
  15109. };
  15110. /**
  15111. * @ngdoc directive
  15112. * @name ng.directive:ngChange
  15113. *
  15114. * @description
  15115. * Evaluate given expression when user changes the input.
  15116. * The expression is not evaluated when the value change is coming from the model.
  15117. *
  15118. * Note, this directive requires `ngModel` to be present.
  15119. *
  15120. * @element input
  15121. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  15122. * in input value.
  15123. *
  15124. * @example
  15125. * <doc:example>
  15126. * <doc:source>
  15127. * <script>
  15128. * function Controller($scope) {
  15129. * $scope.counter = 0;
  15130. * $scope.change = function() {
  15131. * $scope.counter++;
  15132. * };
  15133. * }
  15134. * </script>
  15135. * <div ng-controller="Controller">
  15136. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  15137. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  15138. * <label for="ng-change-example2">Confirmed</label><br />
  15139. * debug = {{confirmed}}<br />
  15140. * counter = {{counter}}
  15141. * </div>
  15142. * </doc:source>
  15143. * <doc:scenario>
  15144. * it('should evaluate the expression if changing from view', function() {
  15145. * expect(binding('counter')).toEqual('0');
  15146. * element('#ng-change-example1').click();
  15147. * expect(binding('counter')).toEqual('1');
  15148. * expect(binding('confirmed')).toEqual('true');
  15149. * });
  15150. *
  15151. * it('should not evaluate the expression if changing from model', function() {
  15152. * element('#ng-change-example2').click();
  15153. * expect(binding('counter')).toEqual('0');
  15154. * expect(binding('confirmed')).toEqual('true');
  15155. * });
  15156. * </doc:scenario>
  15157. * </doc:example>
  15158. */
  15159. var ngChangeDirective = valueFn({
  15160. require: 'ngModel',
  15161. link: function(scope, element, attr, ctrl) {
  15162. ctrl.$viewChangeListeners.push(function() {
  15163. scope.$eval(attr.ngChange);
  15164. });
  15165. }
  15166. });
  15167. var requiredDirective = function() {
  15168. return {
  15169. require: '?ngModel',
  15170. link: function(scope, elm, attr, ctrl) {
  15171. if (!ctrl) return;
  15172. attr.required = true; // force truthy in case we are on non input element
  15173. var validator = function(value) {
  15174. if (attr.required && ctrl.$isEmpty(value)) {
  15175. ctrl.$setValidity('required', false);
  15176. return;
  15177. } else {
  15178. ctrl.$setValidity('required', true);
  15179. return value;
  15180. }
  15181. };
  15182. ctrl.$formatters.push(validator);
  15183. ctrl.$parsers.unshift(validator);
  15184. attr.$observe('required', function() {
  15185. validator(ctrl.$viewValue);
  15186. });
  15187. }
  15188. };
  15189. };
  15190. /**
  15191. * @ngdoc directive
  15192. * @name ng.directive:ngList
  15193. *
  15194. * @description
  15195. * Text input that converts between a delimited string and an array of strings. The delimiter
  15196. * can be a fixed string (by default a comma) or a regular expression.
  15197. *
  15198. * @element input
  15199. * @param {string=} ngList optional delimiter that should be used to split the value. If
  15200. * specified in form `/something/` then the value will be converted into a regular expression.
  15201. *
  15202. * @example
  15203. <doc:example>
  15204. <doc:source>
  15205. <script>
  15206. function Ctrl($scope) {
  15207. $scope.names = ['igor', 'misko', 'vojta'];
  15208. }
  15209. </script>
  15210. <form name="myForm" ng-controller="Ctrl">
  15211. List: <input name="namesInput" ng-model="names" ng-list required>
  15212. <span class="error" ng-show="myForm.namesInput.$error.required">
  15213. Required!</span>
  15214. <br>
  15215. <tt>names = {{names}}</tt><br/>
  15216. <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  15217. <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  15218. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15219. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15220. </form>
  15221. </doc:source>
  15222. <doc:scenario>
  15223. it('should initialize to model', function() {
  15224. expect(binding('names')).toEqual('["igor","misko","vojta"]');
  15225. expect(binding('myForm.namesInput.$valid')).toEqual('true');
  15226. expect(element('span.error').css('display')).toBe('none');
  15227. });
  15228. it('should be invalid if empty', function() {
  15229. input('names').enter('');
  15230. expect(binding('names')).toEqual('');
  15231. expect(binding('myForm.namesInput.$valid')).toEqual('false');
  15232. expect(element('span.error').css('display')).not().toBe('none');
  15233. });
  15234. </doc:scenario>
  15235. </doc:example>
  15236. */
  15237. var ngListDirective = function() {
  15238. return {
  15239. require: 'ngModel',
  15240. link: function(scope, element, attr, ctrl) {
  15241. var match = /\/(.*)\//.exec(attr.ngList),
  15242. separator = match && new RegExp(match[1]) || attr.ngList || ',';
  15243. var parse = function(viewValue) {
  15244. // If the viewValue is invalid (say required but empty) it will be `undefined`
  15245. if (isUndefined(viewValue)) return;
  15246. var list = [];
  15247. if (viewValue) {
  15248. forEach(viewValue.split(separator), function(value) {
  15249. if (value) list.push(trim(value));
  15250. });
  15251. }
  15252. return list;
  15253. };
  15254. ctrl.$parsers.push(parse);
  15255. ctrl.$formatters.push(function(value) {
  15256. if (isArray(value)) {
  15257. return value.join(', ');
  15258. }
  15259. return undefined;
  15260. });
  15261. // Override the standard $isEmpty because an empty array means the input is empty.
  15262. ctrl.$isEmpty = function(value) {
  15263. return !value || !value.length;
  15264. };
  15265. }
  15266. };
  15267. };
  15268. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  15269. /**
  15270. * @ngdoc directive
  15271. * @name ng.directive:ngValue
  15272. *
  15273. * @description
  15274. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  15275. * that when the element is selected, the `ngModel` of that element is set to the
  15276. * bound value.
  15277. *
  15278. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  15279. * shown below.
  15280. *
  15281. * @element input
  15282. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  15283. * of the `input` element
  15284. *
  15285. * @example
  15286. <doc:example>
  15287. <doc:source>
  15288. <script>
  15289. function Ctrl($scope) {
  15290. $scope.names = ['pizza', 'unicorns', 'robots'];
  15291. $scope.my = { favorite: 'unicorns' };
  15292. }
  15293. </script>
  15294. <form ng-controller="Ctrl">
  15295. <h2>Which is your favorite?</h2>
  15296. <label ng-repeat="name in names" for="{{name}}">
  15297. {{name}}
  15298. <input type="radio"
  15299. ng-model="my.favorite"
  15300. ng-value="name"
  15301. id="{{name}}"
  15302. name="favorite">
  15303. </label>
  15304. <div>You chose {{my.favorite}}</div>
  15305. </form>
  15306. </doc:source>
  15307. <doc:scenario>
  15308. it('should initialize to model', function() {
  15309. expect(binding('my.favorite')).toEqual('unicorns');
  15310. });
  15311. it('should bind the values to the inputs', function() {
  15312. input('my.favorite').select('pizza');
  15313. expect(binding('my.favorite')).toEqual('pizza');
  15314. });
  15315. </doc:scenario>
  15316. </doc:example>
  15317. */
  15318. var ngValueDirective = function() {
  15319. return {
  15320. priority: 100,
  15321. compile: function(tpl, tplAttr) {
  15322. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  15323. return function ngValueConstantLink(scope, elm, attr) {
  15324. attr.$set('value', scope.$eval(attr.ngValue));
  15325. };
  15326. } else {
  15327. return function ngValueLink(scope, elm, attr) {
  15328. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  15329. attr.$set('value', value);
  15330. });
  15331. };
  15332. }
  15333. }
  15334. };
  15335. };
  15336. /**
  15337. * @ngdoc directive
  15338. * @name ng.directive:ngBind
  15339. * @restrict AC
  15340. *
  15341. * @description
  15342. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  15343. * with the value of a given expression, and to update the text content when the value of that
  15344. * expression changes.
  15345. *
  15346. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  15347. * `{{ expression }}` which is similar but less verbose.
  15348. *
  15349. * It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily
  15350. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  15351. * element attribute, it makes the bindings invisible to the user while the page is loading.
  15352. *
  15353. * An alternative solution to this problem would be using the
  15354. * {@link ng.directive:ngCloak ngCloak} directive.
  15355. *
  15356. *
  15357. * @element ANY
  15358. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  15359. *
  15360. * @example
  15361. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  15362. <doc:example>
  15363. <doc:source>
  15364. <script>
  15365. function Ctrl($scope) {
  15366. $scope.name = 'Whirled';
  15367. }
  15368. </script>
  15369. <div ng-controller="Ctrl">
  15370. Enter name: <input type="text" ng-model="name"><br>
  15371. Hello <span ng-bind="name"></span>!
  15372. </div>
  15373. </doc:source>
  15374. <doc:scenario>
  15375. it('should check ng-bind', function() {
  15376. expect(using('.doc-example-live').binding('name')).toBe('Whirled');
  15377. using('.doc-example-live').input('name').enter('world');
  15378. expect(using('.doc-example-live').binding('name')).toBe('world');
  15379. });
  15380. </doc:scenario>
  15381. </doc:example>
  15382. */
  15383. var ngBindDirective = ngDirective(function(scope, element, attr) {
  15384. element.addClass('ng-binding').data('$binding', attr.ngBind);
  15385. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  15386. // We are purposefully using == here rather than === because we want to
  15387. // catch when value is "null or undefined"
  15388. // jshint -W041
  15389. element.text(value == undefined ? '' : value);
  15390. });
  15391. });
  15392. /**
  15393. * @ngdoc directive
  15394. * @name ng.directive:ngBindTemplate
  15395. *
  15396. * @description
  15397. * The `ngBindTemplate` directive specifies that the element
  15398. * text content should be replaced with the interpolation of the template
  15399. * in the `ngBindTemplate` attribute.
  15400. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  15401. * expressions. This directive is needed since some HTML elements
  15402. * (such as TITLE and OPTION) cannot contain SPAN elements.
  15403. *
  15404. * @element ANY
  15405. * @param {string} ngBindTemplate template of form
  15406. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  15407. *
  15408. * @example
  15409. * Try it here: enter text in text box and watch the greeting change.
  15410. <doc:example>
  15411. <doc:source>
  15412. <script>
  15413. function Ctrl($scope) {
  15414. $scope.salutation = 'Hello';
  15415. $scope.name = 'World';
  15416. }
  15417. </script>
  15418. <div ng-controller="Ctrl">
  15419. Salutation: <input type="text" ng-model="salutation"><br>
  15420. Name: <input type="text" ng-model="name"><br>
  15421. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  15422. </div>
  15423. </doc:source>
  15424. <doc:scenario>
  15425. it('should check ng-bind', function() {
  15426. expect(using('.doc-example-live').binding('salutation')).
  15427. toBe('Hello');
  15428. expect(using('.doc-example-live').binding('name')).
  15429. toBe('World');
  15430. using('.doc-example-live').input('salutation').enter('Greetings');
  15431. using('.doc-example-live').input('name').enter('user');
  15432. expect(using('.doc-example-live').binding('salutation')).
  15433. toBe('Greetings');
  15434. expect(using('.doc-example-live').binding('name')).
  15435. toBe('user');
  15436. });
  15437. </doc:scenario>
  15438. </doc:example>
  15439. */
  15440. var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
  15441. return function(scope, element, attr) {
  15442. // TODO: move this to scenario runner
  15443. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  15444. element.addClass('ng-binding').data('$binding', interpolateFn);
  15445. attr.$observe('ngBindTemplate', function(value) {
  15446. element.text(value);
  15447. });
  15448. };
  15449. }];
  15450. /**
  15451. * @ngdoc directive
  15452. * @name ng.directive:ngBindHtml
  15453. *
  15454. * @description
  15455. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  15456. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  15457. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  15458. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  15459. * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to
  15460. * an explicitly trusted value via {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}. See the example
  15461. * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
  15462. *
  15463. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  15464. * will have an exception (instead of an exploit.)
  15465. *
  15466. * @element ANY
  15467. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  15468. *
  15469. * @example
  15470. Try it here: enter text in text box and watch the greeting change.
  15471. <example module="ngBindHtmlExample" deps="angular-sanitize.js">
  15472. <file name="index.html">
  15473. <div ng-controller="ngBindHtmlCtrl">
  15474. <p ng-bind-html="myHTML"></p>
  15475. </div>
  15476. </file>
  15477. <file name="script.js">
  15478. angular.module('ngBindHtmlExample', ['ngSanitize'])
  15479. .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) {
  15480. $scope.myHTML =
  15481. 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>';
  15482. }]);
  15483. </file>
  15484. <file name="scenario.js">
  15485. it('should check ng-bind-html', function() {
  15486. expect(using('.doc-example-live').binding('myHTML')).
  15487. toBe(
  15488. 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>'
  15489. );
  15490. });
  15491. </file>
  15492. </example>
  15493. */
  15494. var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  15495. return function(scope, element, attr) {
  15496. element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
  15497. var parsed = $parse(attr.ngBindHtml);
  15498. function getStringValue() { return (parsed(scope) || '').toString(); }
  15499. scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
  15500. element.html($sce.getTrustedHtml(parsed(scope)) || '');
  15501. });
  15502. };
  15503. }];
  15504. function classDirective(name, selector) {
  15505. name = 'ngClass' + name;
  15506. return function() {
  15507. return {
  15508. restrict: 'AC',
  15509. link: function(scope, element, attr) {
  15510. var oldVal;
  15511. scope.$watch(attr[name], ngClassWatchAction, true);
  15512. attr.$observe('class', function(value) {
  15513. ngClassWatchAction(scope.$eval(attr[name]));
  15514. });
  15515. if (name !== 'ngClass') {
  15516. scope.$watch('$index', function($index, old$index) {
  15517. // jshint bitwise: false
  15518. var mod = $index & 1;
  15519. if (mod !== old$index & 1) {
  15520. var classes = flattenClasses(scope.$eval(attr[name]));
  15521. mod === selector ?
  15522. attr.$addClass(classes) :
  15523. attr.$removeClass(classes);
  15524. }
  15525. });
  15526. }
  15527. function ngClassWatchAction(newVal) {
  15528. if (selector === true || scope.$index % 2 === selector) {
  15529. var newClasses = flattenClasses(newVal || '');
  15530. if(!oldVal) {
  15531. attr.$addClass(newClasses);
  15532. } else if(!equals(newVal,oldVal)) {
  15533. attr.$updateClass(newClasses, flattenClasses(oldVal));
  15534. }
  15535. }
  15536. oldVal = copy(newVal);
  15537. }
  15538. function flattenClasses(classVal) {
  15539. if(isArray(classVal)) {
  15540. return classVal.join(' ');
  15541. } else if (isObject(classVal)) {
  15542. var classes = [], i = 0;
  15543. forEach(classVal, function(v, k) {
  15544. if (v) {
  15545. classes.push(k);
  15546. }
  15547. });
  15548. return classes.join(' ');
  15549. }
  15550. return classVal;
  15551. }
  15552. }
  15553. };
  15554. };
  15555. }
  15556. /**
  15557. * @ngdoc directive
  15558. * @name ng.directive:ngClass
  15559. * @restrict AC
  15560. *
  15561. * @description
  15562. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  15563. * an expression that represents all classes to be added.
  15564. *
  15565. * The directive won't add duplicate classes if a particular class was already set.
  15566. *
  15567. * When the expression changes, the previously added classes are removed and only then the
  15568. * new classes are added.
  15569. *
  15570. * @animations
  15571. * add - happens just before the class is applied to the element
  15572. * remove - happens just before the class is removed from the element
  15573. *
  15574. * @element ANY
  15575. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  15576. * of the evaluation can be a string representing space delimited class
  15577. * names, an array, or a map of class names to boolean values. In the case of a map, the
  15578. * names of the properties whose values are truthy will be added as css classes to the
  15579. * element.
  15580. *
  15581. * @example Example that demonstrates basic bindings via ngClass directive.
  15582. <example>
  15583. <file name="index.html">
  15584. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  15585. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  15586. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  15587. <input type="checkbox" ng-model="error"> error (apply "red" class)
  15588. <hr>
  15589. <p ng-class="style">Using String Syntax</p>
  15590. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  15591. <hr>
  15592. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  15593. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  15594. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  15595. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  15596. </file>
  15597. <file name="style.css">
  15598. .strike {
  15599. text-decoration: line-through;
  15600. }
  15601. .bold {
  15602. font-weight: bold;
  15603. }
  15604. .red {
  15605. color: red;
  15606. }
  15607. </file>
  15608. <file name="scenario.js">
  15609. it('should let you toggle the class', function() {
  15610. expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/bold/);
  15611. expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/red/);
  15612. input('important').check();
  15613. expect(element('.doc-example-live p:first').prop('className')).toMatch(/bold/);
  15614. input('error').check();
  15615. expect(element('.doc-example-live p:first').prop('className')).toMatch(/red/);
  15616. });
  15617. it('should let you toggle string example', function() {
  15618. expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('');
  15619. input('style').enter('red');
  15620. expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('red');
  15621. });
  15622. it('array example should have 3 classes', function() {
  15623. expect(element('.doc-example-live p:last').prop('className')).toBe('');
  15624. input('style1').enter('bold');
  15625. input('style2').enter('strike');
  15626. input('style3').enter('red');
  15627. expect(element('.doc-example-live p:last').prop('className')).toBe('bold strike red');
  15628. });
  15629. </file>
  15630. </example>
  15631. ## Animations
  15632. The example below demonstrates how to perform animations using ngClass.
  15633. <example animations="true">
  15634. <file name="index.html">
  15635. <input type="button" value="set" ng-click="myVar='my-class'">
  15636. <input type="button" value="clear" ng-click="myVar=''">
  15637. <br>
  15638. <span class="base-class" ng-class="myVar">Sample Text</span>
  15639. </file>
  15640. <file name="style.css">
  15641. .base-class {
  15642. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  15643. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  15644. }
  15645. .base-class.my-class {
  15646. color: red;
  15647. font-size:3em;
  15648. }
  15649. </file>
  15650. <file name="scenario.js">
  15651. it('should check ng-class', function() {
  15652. expect(element('.doc-example-live span').prop('className')).not().
  15653. toMatch(/my-class/);
  15654. using('.doc-example-live').element(':button:first').click();
  15655. expect(element('.doc-example-live span').prop('className')).
  15656. toMatch(/my-class/);
  15657. using('.doc-example-live').element(':button:last').click();
  15658. expect(element('.doc-example-live span').prop('className')).not().
  15659. toMatch(/my-class/);
  15660. });
  15661. </file>
  15662. </example>
  15663. ## ngClass and pre-existing CSS3 Transitions/Animations
  15664. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  15665. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  15666. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  15667. to view the step by step details of {@link ngAnimate.$animate#methods_addclass $animate.addClass} and
  15668. {@link ngAnimate.$animate#methods_removeclass $animate.removeClass}.
  15669. */
  15670. var ngClassDirective = classDirective('', true);
  15671. /**
  15672. * @ngdoc directive
  15673. * @name ng.directive:ngClassOdd
  15674. * @restrict AC
  15675. *
  15676. * @description
  15677. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  15678. * {@link ng.directive:ngClass ngClass}, except they work in
  15679. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  15680. *
  15681. * This directive can be applied only within the scope of an
  15682. * {@link ng.directive:ngRepeat ngRepeat}.
  15683. *
  15684. * @element ANY
  15685. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  15686. * of the evaluation can be a string representing space delimited class names or an array.
  15687. *
  15688. * @example
  15689. <example>
  15690. <file name="index.html">
  15691. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  15692. <li ng-repeat="name in names">
  15693. <span ng-class-odd="'odd'" ng-class-even="'even'">
  15694. {{name}}
  15695. </span>
  15696. </li>
  15697. </ol>
  15698. </file>
  15699. <file name="style.css">
  15700. .odd {
  15701. color: red;
  15702. }
  15703. .even {
  15704. color: blue;
  15705. }
  15706. </file>
  15707. <file name="scenario.js">
  15708. it('should check ng-class-odd and ng-class-even', function() {
  15709. expect(element('.doc-example-live li:first span').prop('className')).
  15710. toMatch(/odd/);
  15711. expect(element('.doc-example-live li:last span').prop('className')).
  15712. toMatch(/even/);
  15713. });
  15714. </file>
  15715. </example>
  15716. */
  15717. var ngClassOddDirective = classDirective('Odd', 0);
  15718. /**
  15719. * @ngdoc directive
  15720. * @name ng.directive:ngClassEven
  15721. * @restrict AC
  15722. *
  15723. * @description
  15724. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  15725. * {@link ng.directive:ngClass ngClass}, except they work in
  15726. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  15727. *
  15728. * This directive can be applied only within the scope of an
  15729. * {@link ng.directive:ngRepeat ngRepeat}.
  15730. *
  15731. * @element ANY
  15732. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  15733. * result of the evaluation can be a string representing space delimited class names or an array.
  15734. *
  15735. * @example
  15736. <example>
  15737. <file name="index.html">
  15738. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  15739. <li ng-repeat="name in names">
  15740. <span ng-class-odd="'odd'" ng-class-even="'even'">
  15741. {{name}} &nbsp; &nbsp; &nbsp;
  15742. </span>
  15743. </li>
  15744. </ol>
  15745. </file>
  15746. <file name="style.css">
  15747. .odd {
  15748. color: red;
  15749. }
  15750. .even {
  15751. color: blue;
  15752. }
  15753. </file>
  15754. <file name="scenario.js">
  15755. it('should check ng-class-odd and ng-class-even', function() {
  15756. expect(element('.doc-example-live li:first span').prop('className')).
  15757. toMatch(/odd/);
  15758. expect(element('.doc-example-live li:last span').prop('className')).
  15759. toMatch(/even/);
  15760. });
  15761. </file>
  15762. </example>
  15763. */
  15764. var ngClassEvenDirective = classDirective('Even', 1);
  15765. /**
  15766. * @ngdoc directive
  15767. * @name ng.directive:ngCloak
  15768. * @restrict AC
  15769. *
  15770. * @description
  15771. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  15772. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  15773. * directive to avoid the undesirable flicker effect caused by the html template display.
  15774. *
  15775. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  15776. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  15777. * of the browser view.
  15778. *
  15779. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  15780. * `angular.min.js`.
  15781. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  15782. *
  15783. * <pre>
  15784. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  15785. * display: none !important;
  15786. * }
  15787. * </pre>
  15788. *
  15789. * When this css rule is loaded by the browser, all html elements (including their children) that
  15790. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  15791. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  15792. * the compiled element visible.
  15793. *
  15794. * For the best result, the `angular.js` script must be loaded in the head section of the html
  15795. * document; alternatively, the css rule above must be included in the external stylesheet of the
  15796. * application.
  15797. *
  15798. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  15799. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  15800. * class `ngCloak` in addition to the `ngCloak` directive as shown in the example below.
  15801. *
  15802. * @element ANY
  15803. *
  15804. * @example
  15805. <doc:example>
  15806. <doc:source>
  15807. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  15808. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  15809. </doc:source>
  15810. <doc:scenario>
  15811. it('should remove the template directive and css class', function() {
  15812. expect(element('.doc-example-live #template1').attr('ng-cloak')).
  15813. not().toBeDefined();
  15814. expect(element('.doc-example-live #template2').attr('ng-cloak')).
  15815. not().toBeDefined();
  15816. });
  15817. </doc:scenario>
  15818. </doc:example>
  15819. *
  15820. */
  15821. var ngCloakDirective = ngDirective({
  15822. compile: function(element, attr) {
  15823. attr.$set('ngCloak', undefined);
  15824. element.removeClass('ng-cloak');
  15825. }
  15826. });
  15827. /**
  15828. * @ngdoc directive
  15829. * @name ng.directive:ngController
  15830. *
  15831. * @description
  15832. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  15833. * supports the principles behind the Model-View-Controller design pattern.
  15834. *
  15835. * MVC components in angular:
  15836. *
  15837. * * Model — The Model is scope properties; scopes are attached to the DOM where scope properties
  15838. * are accessed through bindings.
  15839. * * View — The template (HTML with data bindings) that is rendered into the View.
  15840. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  15841. * logic behind the application to decorate the scope with functions and values
  15842. *
  15843. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  15844. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  15845. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  15846. * and executed twice.
  15847. *
  15848. * @element ANY
  15849. * @scope
  15850. * @param {expression} ngController Name of a globally accessible constructor function or an
  15851. * {@link guide/expression expression} that on the current scope evaluates to a
  15852. * constructor function. The controller instance can be published into a scope property
  15853. * by specifying `as propertyName`.
  15854. *
  15855. * @example
  15856. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  15857. * greeting are methods declared on the controller (see source tab). These methods can
  15858. * easily be called from the angular markup. Notice that the scope becomes the `this` for the
  15859. * controller's instance. This allows for easy access to the view data from the controller. Also
  15860. * notice that any changes to the data are automatically reflected in the View without the need
  15861. * for a manual update. The example is shown in two different declaration styles you may use
  15862. * according to preference.
  15863. <doc:example>
  15864. <doc:source>
  15865. <script>
  15866. function SettingsController1() {
  15867. this.name = "John Smith";
  15868. this.contacts = [
  15869. {type: 'phone', value: '408 555 1212'},
  15870. {type: 'email', value: '[email protected]'} ];
  15871. };
  15872. SettingsController1.prototype.greet = function() {
  15873. alert(this.name);
  15874. };
  15875. SettingsController1.prototype.addContact = function() {
  15876. this.contacts.push({type: 'email', value: '[email protected]'});
  15877. };
  15878. SettingsController1.prototype.removeContact = function(contactToRemove) {
  15879. var index = this.contacts.indexOf(contactToRemove);
  15880. this.contacts.splice(index, 1);
  15881. };
  15882. SettingsController1.prototype.clearContact = function(contact) {
  15883. contact.type = 'phone';
  15884. contact.value = '';
  15885. };
  15886. </script>
  15887. <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  15888. Name: <input type="text" ng-model="settings.name"/>
  15889. [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  15890. Contact:
  15891. <ul>
  15892. <li ng-repeat="contact in settings.contacts">
  15893. <select ng-model="contact.type">
  15894. <option>phone</option>
  15895. <option>email</option>
  15896. </select>
  15897. <input type="text" ng-model="contact.value"/>
  15898. [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  15899. | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  15900. </li>
  15901. <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  15902. </ul>
  15903. </div>
  15904. </doc:source>
  15905. <doc:scenario>
  15906. it('should check controller as', function() {
  15907. expect(element('#ctrl-as-exmpl>:input').val()).toBe('John Smith');
  15908. expect(element('#ctrl-as-exmpl li:nth-child(1) input').val())
  15909. .toBe('408 555 1212');
  15910. expect(element('#ctrl-as-exmpl li:nth-child(2) input').val())
  15911. .toBe('[email protected]');
  15912. element('#ctrl-as-exmpl li:first a:contains("clear")').click();
  15913. expect(element('#ctrl-as-exmpl li:first input').val()).toBe('');
  15914. element('#ctrl-as-exmpl li:last a:contains("add")').click();
  15915. expect(element('#ctrl-as-exmpl li:nth-child(3) input').val())
  15916. .toBe('[email protected]');
  15917. });
  15918. </doc:scenario>
  15919. </doc:example>
  15920. <doc:example>
  15921. <doc:source>
  15922. <script>
  15923. function SettingsController2($scope) {
  15924. $scope.name = "John Smith";
  15925. $scope.contacts = [
  15926. {type:'phone', value:'408 555 1212'},
  15927. {type:'email', value:'[email protected]'} ];
  15928. $scope.greet = function() {
  15929. alert(this.name);
  15930. };
  15931. $scope.addContact = function() {
  15932. this.contacts.push({type:'email', value:'[email protected]'});
  15933. };
  15934. $scope.removeContact = function(contactToRemove) {
  15935. var index = this.contacts.indexOf(contactToRemove);
  15936. this.contacts.splice(index, 1);
  15937. };
  15938. $scope.clearContact = function(contact) {
  15939. contact.type = 'phone';
  15940. contact.value = '';
  15941. };
  15942. }
  15943. </script>
  15944. <div id="ctrl-exmpl" ng-controller="SettingsController2">
  15945. Name: <input type="text" ng-model="name"/>
  15946. [ <a href="" ng-click="greet()">greet</a> ]<br/>
  15947. Contact:
  15948. <ul>
  15949. <li ng-repeat="contact in contacts">
  15950. <select ng-model="contact.type">
  15951. <option>phone</option>
  15952. <option>email</option>
  15953. </select>
  15954. <input type="text" ng-model="contact.value"/>
  15955. [ <a href="" ng-click="clearContact(contact)">clear</a>
  15956. | <a href="" ng-click="removeContact(contact)">X</a> ]
  15957. </li>
  15958. <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  15959. </ul>
  15960. </div>
  15961. </doc:source>
  15962. <doc:scenario>
  15963. it('should check controller', function() {
  15964. expect(element('#ctrl-exmpl>:input').val()).toBe('John Smith');
  15965. expect(element('#ctrl-exmpl li:nth-child(1) input').val())
  15966. .toBe('408 555 1212');
  15967. expect(element('#ctrl-exmpl li:nth-child(2) input').val())
  15968. .toBe('[email protected]');
  15969. element('#ctrl-exmpl li:first a:contains("clear")').click();
  15970. expect(element('#ctrl-exmpl li:first input').val()).toBe('');
  15971. element('#ctrl-exmpl li:last a:contains("add")').click();
  15972. expect(element('#ctrl-exmpl li:nth-child(3) input').val())
  15973. .toBe('[email protected]');
  15974. });
  15975. </doc:scenario>
  15976. </doc:example>
  15977. */
  15978. var ngControllerDirective = [function() {
  15979. return {
  15980. scope: true,
  15981. controller: '@',
  15982. priority: 500
  15983. };
  15984. }];
  15985. /**
  15986. * @ngdoc directive
  15987. * @name ng.directive:ngCsp
  15988. *
  15989. * @element html
  15990. * @description
  15991. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  15992. *
  15993. * This is necessary when developing things like Google Chrome Extensions.
  15994. *
  15995. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  15996. * For us to be compatible, we just need to implement the "getterFn" in $parse without violating
  15997. * any of these restrictions.
  15998. *
  15999. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  16000. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  16001. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  16002. * be raised.
  16003. *
  16004. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  16005. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  16006. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  16007. *
  16008. * In order to use this feature put the `ngCsp` directive on the root element of the application.
  16009. *
  16010. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  16011. *
  16012. * @example
  16013. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  16014. <pre>
  16015. <!doctype html>
  16016. <html ng-app ng-csp>
  16017. ...
  16018. ...
  16019. </html>
  16020. </pre>
  16021. */
  16022. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap
  16023. // the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute
  16024. // anywhere in the current doc
  16025. /**
  16026. * @ngdoc directive
  16027. * @name ng.directive:ngClick
  16028. *
  16029. * @description
  16030. * The ngClick directive allows you to specify custom behavior when
  16031. * an element is clicked.
  16032. *
  16033. * @element ANY
  16034. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  16035. * click. (Event object is available as `$event`)
  16036. *
  16037. * @example
  16038. <doc:example>
  16039. <doc:source>
  16040. <button ng-click="count = count + 1" ng-init="count=0">
  16041. Increment
  16042. </button>
  16043. count: {{count}}
  16044. </doc:source>
  16045. <doc:scenario>
  16046. it('should check ng-click', function() {
  16047. expect(binding('count')).toBe('0');
  16048. element('.doc-example-live :button').click();
  16049. expect(binding('count')).toBe('1');
  16050. });
  16051. </doc:scenario>
  16052. </doc:example>
  16053. */
  16054. /*
  16055. * A directive that allows creation of custom onclick handlers that are defined as angular
  16056. * expressions and are compiled and executed within the current scope.
  16057. *
  16058. * Events that are handled via these handler are always configured not to propagate further.
  16059. */
  16060. var ngEventDirectives = {};
  16061. forEach(
  16062. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  16063. function(name) {
  16064. var directiveName = directiveNormalize('ng-' + name);
  16065. ngEventDirectives[directiveName] = ['$parse', function($parse) {
  16066. return {
  16067. compile: function($element, attr) {
  16068. var fn = $parse(attr[directiveName]);
  16069. return function(scope, element, attr) {
  16070. element.on(lowercase(name), function(event) {
  16071. scope.$apply(function() {
  16072. fn(scope, {$event:event});
  16073. });
  16074. });
  16075. };
  16076. }
  16077. };
  16078. }];
  16079. }
  16080. );
  16081. /**
  16082. * @ngdoc directive
  16083. * @name ng.directive:ngDblclick
  16084. *
  16085. * @description
  16086. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  16087. *
  16088. * @element ANY
  16089. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  16090. * a dblclick. (The Event object is available as `$event`)
  16091. *
  16092. * @example
  16093. * See {@link ng.directive:ngClick ngClick}
  16094. */
  16095. /**
  16096. * @ngdoc directive
  16097. * @name ng.directive:ngMousedown
  16098. *
  16099. * @description
  16100. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  16101. *
  16102. * @element ANY
  16103. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  16104. * mousedown. (Event object is available as `$event`)
  16105. *
  16106. * @example
  16107. * See {@link ng.directive:ngClick ngClick}
  16108. */
  16109. /**
  16110. * @ngdoc directive
  16111. * @name ng.directive:ngMouseup
  16112. *
  16113. * @description
  16114. * Specify custom behavior on mouseup event.
  16115. *
  16116. * @element ANY
  16117. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  16118. * mouseup. (Event object is available as `$event`)
  16119. *
  16120. * @example
  16121. * See {@link ng.directive:ngClick ngClick}
  16122. */
  16123. /**
  16124. * @ngdoc directive
  16125. * @name ng.directive:ngMouseover
  16126. *
  16127. * @description
  16128. * Specify custom behavior on mouseover event.
  16129. *
  16130. * @element ANY
  16131. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  16132. * mouseover. (Event object is available as `$event`)
  16133. *
  16134. * @example
  16135. * See {@link ng.directive:ngClick ngClick}
  16136. */
  16137. /**
  16138. * @ngdoc directive
  16139. * @name ng.directive:ngMouseenter
  16140. *
  16141. * @description
  16142. * Specify custom behavior on mouseenter event.
  16143. *
  16144. * @element ANY
  16145. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  16146. * mouseenter. (Event object is available as `$event`)
  16147. *
  16148. * @example
  16149. * See {@link ng.directive:ngClick ngClick}
  16150. */
  16151. /**
  16152. * @ngdoc directive
  16153. * @name ng.directive:ngMouseleave
  16154. *
  16155. * @description
  16156. * Specify custom behavior on mouseleave event.
  16157. *
  16158. * @element ANY
  16159. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  16160. * mouseleave. (Event object is available as `$event`)
  16161. *
  16162. * @example
  16163. * See {@link ng.directive:ngClick ngClick}
  16164. */
  16165. /**
  16166. * @ngdoc directive
  16167. * @name ng.directive:ngMousemove
  16168. *
  16169. * @description
  16170. * Specify custom behavior on mousemove event.
  16171. *
  16172. * @element ANY
  16173. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  16174. * mousemove. (Event object is available as `$event`)
  16175. *
  16176. * @example
  16177. * See {@link ng.directive:ngClick ngClick}
  16178. */
  16179. /**
  16180. * @ngdoc directive
  16181. * @name ng.directive:ngKeydown
  16182. *
  16183. * @description
  16184. * Specify custom behavior on keydown event.
  16185. *
  16186. * @element ANY
  16187. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  16188. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  16189. *
  16190. * @example
  16191. * See {@link ng.directive:ngClick ngClick}
  16192. */
  16193. /**
  16194. * @ngdoc directive
  16195. * @name ng.directive:ngKeyup
  16196. *
  16197. * @description
  16198. * Specify custom behavior on keyup event.
  16199. *
  16200. * @element ANY
  16201. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  16202. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  16203. *
  16204. * @example
  16205. * See {@link ng.directive:ngClick ngClick}
  16206. */
  16207. /**
  16208. * @ngdoc directive
  16209. * @name ng.directive:ngKeypress
  16210. *
  16211. * @description
  16212. * Specify custom behavior on keypress event.
  16213. *
  16214. * @element ANY
  16215. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  16216. * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  16217. *
  16218. * @example
  16219. * See {@link ng.directive:ngClick ngClick}
  16220. */
  16221. /**
  16222. * @ngdoc directive
  16223. * @name ng.directive:ngSubmit
  16224. *
  16225. * @description
  16226. * Enables binding angular expressions to onsubmit events.
  16227. *
  16228. * Additionally it prevents the default action (which for form means sending the request to the
  16229. * server and reloading the current page) **but only if the form does not contain an `action`
  16230. * attribute**.
  16231. *
  16232. * @element form
  16233. * @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`)
  16234. *
  16235. * @example
  16236. <doc:example>
  16237. <doc:source>
  16238. <script>
  16239. function Ctrl($scope) {
  16240. $scope.list = [];
  16241. $scope.text = 'hello';
  16242. $scope.submit = function() {
  16243. if (this.text) {
  16244. this.list.push(this.text);
  16245. this.text = '';
  16246. }
  16247. };
  16248. }
  16249. </script>
  16250. <form ng-submit="submit()" ng-controller="Ctrl">
  16251. Enter text and hit enter:
  16252. <input type="text" ng-model="text" name="text" />
  16253. <input type="submit" id="submit" value="Submit" />
  16254. <pre>list={{list}}</pre>
  16255. </form>
  16256. </doc:source>
  16257. <doc:scenario>
  16258. it('should check ng-submit', function() {
  16259. expect(binding('list')).toBe('[]');
  16260. element('.doc-example-live #submit').click();
  16261. expect(binding('list')).toBe('["hello"]');
  16262. expect(input('text').val()).toBe('');
  16263. });
  16264. it('should ignore empty strings', function() {
  16265. expect(binding('list')).toBe('[]');
  16266. element('.doc-example-live #submit').click();
  16267. element('.doc-example-live #submit').click();
  16268. expect(binding('list')).toBe('["hello"]');
  16269. });
  16270. </doc:scenario>
  16271. </doc:example>
  16272. */
  16273. /**
  16274. * @ngdoc directive
  16275. * @name ng.directive:ngFocus
  16276. *
  16277. * @description
  16278. * Specify custom behavior on focus event.
  16279. *
  16280. * @element window, input, select, textarea, a
  16281. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  16282. * focus. (Event object is available as `$event`)
  16283. *
  16284. * @example
  16285. * See {@link ng.directive:ngClick ngClick}
  16286. */
  16287. /**
  16288. * @ngdoc directive
  16289. * @name ng.directive:ngBlur
  16290. *
  16291. * @description
  16292. * Specify custom behavior on blur event.
  16293. *
  16294. * @element window, input, select, textarea, a
  16295. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  16296. * blur. (Event object is available as `$event`)
  16297. *
  16298. * @example
  16299. * See {@link ng.directive:ngClick ngClick}
  16300. */
  16301. /**
  16302. * @ngdoc directive
  16303. * @name ng.directive:ngCopy
  16304. *
  16305. * @description
  16306. * Specify custom behavior on copy event.
  16307. *
  16308. * @element window, input, select, textarea, a
  16309. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  16310. * copy. (Event object is available as `$event`)
  16311. *
  16312. * @example
  16313. * See {@link ng.directive:ngClick ngClick}
  16314. */
  16315. /**
  16316. * @ngdoc directive
  16317. * @name ng.directive:ngCut
  16318. *
  16319. * @description
  16320. * Specify custom behavior on cut event.
  16321. *
  16322. * @element window, input, select, textarea, a
  16323. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  16324. * cut. (Event object is available as `$event`)
  16325. *
  16326. * @example
  16327. * See {@link ng.directive:ngClick ngClick}
  16328. */
  16329. /**
  16330. * @ngdoc directive
  16331. * @name ng.directive:ngPaste
  16332. *
  16333. * @description
  16334. * Specify custom behavior on paste event.
  16335. *
  16336. * @element window, input, select, textarea, a
  16337. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  16338. * paste. (Event object is available as `$event`)
  16339. *
  16340. * @example
  16341. * See {@link ng.directive:ngClick ngClick}
  16342. */
  16343. /**
  16344. * @ngdoc directive
  16345. * @name ng.directive:ngIf
  16346. * @restrict A
  16347. *
  16348. * @description
  16349. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  16350. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  16351. * value then the element is removed from the DOM, otherwise a clone of the
  16352. * element is reinserted into the DOM.
  16353. *
  16354. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  16355. * element in the DOM rather than changing its visibility via the `display` css property. A common
  16356. * case when this difference is significant is when using css selectors that rely on an element's
  16357. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  16358. *
  16359. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  16360. * is created when the element is restored. The scope created within `ngIf` inherits from
  16361. * its parent scope using
  16362. * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}.
  16363. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  16364. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  16365. * variable within the child scope will override (hide) the value in the parent scope.
  16366. *
  16367. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  16368. * is if an element's class attribute is directly modified after it's compiled, using something like
  16369. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  16370. * the added class will be lost because the original compiled state is used to regenerate the element.
  16371. *
  16372. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  16373. * and `leave` effects.
  16374. *
  16375. * @animations
  16376. * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
  16377. * leave - happens just before the ngIf contents are removed from the DOM
  16378. *
  16379. * @element ANY
  16380. * @scope
  16381. * @priority 600
  16382. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  16383. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  16384. * element is added to the DOM tree.
  16385. *
  16386. * @example
  16387. <example animations="true">
  16388. <file name="index.html">
  16389. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  16390. Show when checked:
  16391. <span ng-if="checked" class="animate-if">
  16392. I'm removed when the checkbox is unchecked.
  16393. </span>
  16394. </file>
  16395. <file name="animations.css">
  16396. .animate-if {
  16397. background:white;
  16398. border:1px solid black;
  16399. padding:10px;
  16400. }
  16401. /&#42;
  16402. The transition styles can also be placed on the CSS base class above
  16403. &#42;/
  16404. .animate-if.ng-enter, .animate-if.ng-leave {
  16405. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16406. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16407. }
  16408. .animate-if.ng-enter,
  16409. .animate-if.ng-leave.ng-leave-active {
  16410. opacity:0;
  16411. }
  16412. .animate-if.ng-leave,
  16413. .animate-if.ng-enter.ng-enter-active {
  16414. opacity:1;
  16415. }
  16416. </file>
  16417. </example>
  16418. */
  16419. var ngIfDirective = ['$animate', function($animate) {
  16420. return {
  16421. transclude: 'element',
  16422. priority: 600,
  16423. terminal: true,
  16424. restrict: 'A',
  16425. $$tlb: true,
  16426. link: function ($scope, $element, $attr, ctrl, $transclude) {
  16427. var block, childScope;
  16428. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  16429. if (toBoolean(value)) {
  16430. if (!childScope) {
  16431. childScope = $scope.$new();
  16432. $transclude(childScope, function (clone) {
  16433. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  16434. // Note: We only need the first/last node of the cloned nodes.
  16435. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  16436. // by a directive with templateUrl when it's template arrives.
  16437. block = {
  16438. clone: clone
  16439. };
  16440. $animate.enter(clone, $element.parent(), $element);
  16441. });
  16442. }
  16443. } else {
  16444. if (childScope) {
  16445. childScope.$destroy();
  16446. childScope = null;
  16447. }
  16448. if (block) {
  16449. $animate.leave(getBlockElements(block.clone));
  16450. block = null;
  16451. }
  16452. }
  16453. });
  16454. }
  16455. };
  16456. }];
  16457. /**
  16458. * @ngdoc directive
  16459. * @name ng.directive:ngInclude
  16460. * @restrict ECA
  16461. *
  16462. * @description
  16463. * Fetches, compiles and includes an external HTML fragment.
  16464. *
  16465. * By default, the template URL is restricted to the same domain and protocol as the
  16466. * application document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl
  16467. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  16468. * you may either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist them} or
  16469. * {@link ng.$sce#methods_trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  16470. * ng.$sce Strict Contextual Escaping}.
  16471. *
  16472. * In addition, the browser's
  16473. * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
  16474. * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing
  16475. * (CORS)} policy may further restrict whether the template is successfully loaded.
  16476. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  16477. * access on some browsers.
  16478. *
  16479. * @animations
  16480. * enter - animation is used to bring new content into the browser.
  16481. * leave - animation is used to animate existing content away.
  16482. *
  16483. * The enter and leave animation occur concurrently.
  16484. *
  16485. * @scope
  16486. * @priority 400
  16487. *
  16488. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  16489. * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
  16490. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  16491. *
  16492. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  16493. * $anchorScroll} to scroll the viewport after the content is loaded.
  16494. *
  16495. * - If the attribute is not set, disable scrolling.
  16496. * - If the attribute is set without value, enable scrolling.
  16497. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  16498. *
  16499. * @example
  16500. <example animations="true">
  16501. <file name="index.html">
  16502. <div ng-controller="Ctrl">
  16503. <select ng-model="template" ng-options="t.name for t in templates">
  16504. <option value="">(blank)</option>
  16505. </select>
  16506. url of the template: <tt>{{template.url}}</tt>
  16507. <hr/>
  16508. <div class="slide-animate-container">
  16509. <div class="slide-animate" ng-include="template.url"></div>
  16510. </div>
  16511. </div>
  16512. </file>
  16513. <file name="script.js">
  16514. function Ctrl($scope) {
  16515. $scope.templates =
  16516. [ { name: 'template1.html', url: 'template1.html'}
  16517. , { name: 'template2.html', url: 'template2.html'} ];
  16518. $scope.template = $scope.templates[0];
  16519. }
  16520. </file>
  16521. <file name="template1.html">
  16522. Content of template1.html
  16523. </file>
  16524. <file name="template2.html">
  16525. Content of template2.html
  16526. </file>
  16527. <file name="animations.css">
  16528. .slide-animate-container {
  16529. position:relative;
  16530. background:white;
  16531. border:1px solid black;
  16532. height:40px;
  16533. overflow:hidden;
  16534. }
  16535. .slide-animate {
  16536. padding:10px;
  16537. }
  16538. .slide-animate.ng-enter, .slide-animate.ng-leave {
  16539. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16540. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16541. position:absolute;
  16542. top:0;
  16543. left:0;
  16544. right:0;
  16545. bottom:0;
  16546. display:block;
  16547. padding:10px;
  16548. }
  16549. .slide-animate.ng-enter {
  16550. top:-50px;
  16551. }
  16552. .slide-animate.ng-enter.ng-enter-active {
  16553. top:0;
  16554. }
  16555. .slide-animate.ng-leave {
  16556. top:0;
  16557. }
  16558. .slide-animate.ng-leave.ng-leave-active {
  16559. top:50px;
  16560. }
  16561. </file>
  16562. <file name="scenario.js">
  16563. it('should load template1.html', function() {
  16564. expect(element('.doc-example-live [ng-include]').text()).
  16565. toMatch(/Content of template1.html/);
  16566. });
  16567. it('should load template2.html', function() {
  16568. select('template').option('1');
  16569. expect(element('.doc-example-live [ng-include]').text()).
  16570. toMatch(/Content of template2.html/);
  16571. });
  16572. it('should change to blank', function() {
  16573. select('template').option('');
  16574. expect(element('.doc-example-live [ng-include]')).toBe(undefined);
  16575. });
  16576. </file>
  16577. </example>
  16578. */
  16579. /**
  16580. * @ngdoc event
  16581. * @name ng.directive:ngInclude#$includeContentRequested
  16582. * @eventOf ng.directive:ngInclude
  16583. * @eventType emit on the scope ngInclude was declared in
  16584. * @description
  16585. * Emitted every time the ngInclude content is requested.
  16586. */
  16587. /**
  16588. * @ngdoc event
  16589. * @name ng.directive:ngInclude#$includeContentLoaded
  16590. * @eventOf ng.directive:ngInclude
  16591. * @eventType emit on the current ngInclude scope
  16592. * @description
  16593. * Emitted every time the ngInclude content is reloaded.
  16594. */
  16595. var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
  16596. function($http, $templateCache, $anchorScroll, $animate, $sce) {
  16597. return {
  16598. restrict: 'ECA',
  16599. priority: 400,
  16600. terminal: true,
  16601. transclude: 'element',
  16602. controller: angular.noop,
  16603. compile: function(element, attr) {
  16604. var srcExp = attr.ngInclude || attr.src,
  16605. onloadExp = attr.onload || '',
  16606. autoScrollExp = attr.autoscroll;
  16607. return function(scope, $element, $attr, ctrl, $transclude) {
  16608. var changeCounter = 0,
  16609. currentScope,
  16610. currentElement;
  16611. var cleanupLastIncludeContent = function() {
  16612. if (currentScope) {
  16613. currentScope.$destroy();
  16614. currentScope = null;
  16615. }
  16616. if(currentElement) {
  16617. $animate.leave(currentElement);
  16618. currentElement = null;
  16619. }
  16620. };
  16621. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  16622. var afterAnimation = function() {
  16623. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  16624. $anchorScroll();
  16625. }
  16626. };
  16627. var thisChangeId = ++changeCounter;
  16628. if (src) {
  16629. $http.get(src, {cache: $templateCache}).success(function(response) {
  16630. if (thisChangeId !== changeCounter) return;
  16631. var newScope = scope.$new();
  16632. ctrl.template = response;
  16633. // Note: This will also link all children of ng-include that were contained in the original
  16634. // html. If that content contains controllers, ... they could pollute/change the scope.
  16635. // However, using ng-include on an element with additional content does not make sense...
  16636. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  16637. // function is called before linking the content, which would apply child
  16638. // directives to non existing elements.
  16639. var clone = $transclude(newScope, function(clone) {
  16640. cleanupLastIncludeContent();
  16641. $animate.enter(clone, null, $element, afterAnimation);
  16642. });
  16643. currentScope = newScope;
  16644. currentElement = clone;
  16645. currentScope.$emit('$includeContentLoaded');
  16646. scope.$eval(onloadExp);
  16647. }).error(function() {
  16648. if (thisChangeId === changeCounter) cleanupLastIncludeContent();
  16649. });
  16650. scope.$emit('$includeContentRequested');
  16651. } else {
  16652. cleanupLastIncludeContent();
  16653. ctrl.template = null;
  16654. }
  16655. });
  16656. };
  16657. }
  16658. };
  16659. }];
  16660. // This directive is called during the $transclude call of the first `ngInclude` directive.
  16661. // It will replace and compile the content of the element with the loaded template.
  16662. // We need this directive so that the element content is already filled when
  16663. // the link function of another directive on the same element as ngInclude
  16664. // is called.
  16665. var ngIncludeFillContentDirective = ['$compile',
  16666. function($compile) {
  16667. return {
  16668. restrict: 'ECA',
  16669. priority: -400,
  16670. require: 'ngInclude',
  16671. link: function(scope, $element, $attr, ctrl) {
  16672. $element.html(ctrl.template);
  16673. $compile($element.contents())(scope);
  16674. }
  16675. };
  16676. }];
  16677. /**
  16678. * @ngdoc directive
  16679. * @name ng.directive:ngInit
  16680. * @restrict AC
  16681. *
  16682. * @description
  16683. * The `ngInit` directive allows you to evaluate an expression in the
  16684. * current scope.
  16685. *
  16686. * <div class="alert alert-error">
  16687. * The only appropriate use of `ngInit` for aliasing special properties of
  16688. * {@link api/ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  16689. * should use {@link guide/controller controllers} rather than `ngInit`
  16690. * to initialize values on a scope.
  16691. * </div>
  16692. *
  16693. * @priority 450
  16694. *
  16695. * @element ANY
  16696. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  16697. *
  16698. * @example
  16699. <doc:example>
  16700. <doc:source>
  16701. <script>
  16702. function Ctrl($scope) {
  16703. $scope.list = [['a', 'b'], ['c', 'd']];
  16704. }
  16705. </script>
  16706. <div ng-controller="Ctrl">
  16707. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  16708. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  16709. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  16710. </div>
  16711. </div>
  16712. </div>
  16713. </doc:source>
  16714. <doc:scenario>
  16715. it('should alias index positions', function() {
  16716. expect(element('.example-init').text())
  16717. .toBe('list[ 0 ][ 0 ] = a;' +
  16718. 'list[ 0 ][ 1 ] = b;' +
  16719. 'list[ 1 ][ 0 ] = c;' +
  16720. 'list[ 1 ][ 1 ] = d;');
  16721. });
  16722. </doc:scenario>
  16723. </doc:example>
  16724. */
  16725. var ngInitDirective = ngDirective({
  16726. priority: 450,
  16727. compile: function() {
  16728. return {
  16729. pre: function(scope, element, attrs) {
  16730. scope.$eval(attrs.ngInit);
  16731. }
  16732. };
  16733. }
  16734. });
  16735. /**
  16736. * @ngdoc directive
  16737. * @name ng.directive:ngNonBindable
  16738. * @restrict AC
  16739. * @priority 1000
  16740. *
  16741. * @description
  16742. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  16743. * DOM element. This is useful if the element contains what appears to be Angular directives and
  16744. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  16745. * displays snippets of code, for instance.
  16746. *
  16747. * @element ANY
  16748. *
  16749. * @example
  16750. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  16751. * but the one wrapped in `ngNonBindable` is left alone.
  16752. *
  16753. * @example
  16754. <doc:example>
  16755. <doc:source>
  16756. <div>Normal: {{1 + 2}}</div>
  16757. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  16758. </doc:source>
  16759. <doc:scenario>
  16760. it('should check ng-non-bindable', function() {
  16761. expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
  16762. expect(using('.doc-example-live').element('div:last').text()).
  16763. toMatch(/1 \+ 2/);
  16764. });
  16765. </doc:scenario>
  16766. </doc:example>
  16767. */
  16768. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  16769. /**
  16770. * @ngdoc directive
  16771. * @name ng.directive:ngPluralize
  16772. * @restrict EA
  16773. *
  16774. * @description
  16775. * # Overview
  16776. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  16777. * These rules are bundled with angular.js, but can be overridden
  16778. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  16779. * by specifying the mappings between
  16780. * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
  16781. * plural categories} and the strings to be displayed.
  16782. *
  16783. * # Plural categories and explicit number rules
  16784. * There are two
  16785. * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
  16786. * plural categories} in Angular's default en-US locale: "one" and "other".
  16787. *
  16788. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  16789. * any number that is not 1), an explicit number rule can only match one number. For example, the
  16790. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  16791. * and explicit number rules throughout the rest of this documentation.
  16792. *
  16793. * # Configuring ngPluralize
  16794. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  16795. * You can also provide an optional attribute, `offset`.
  16796. *
  16797. * The value of the `count` attribute can be either a string or an {@link guide/expression
  16798. * Angular expression}; these are evaluated on the current scope for its bound value.
  16799. *
  16800. * The `when` attribute specifies the mappings between plural categories and the actual
  16801. * string to be displayed. The value of the attribute should be a JSON object.
  16802. *
  16803. * The following example shows how to configure ngPluralize:
  16804. *
  16805. * <pre>
  16806. * <ng-pluralize count="personCount"
  16807. when="{'0': 'Nobody is viewing.',
  16808. * 'one': '1 person is viewing.',
  16809. * 'other': '{} people are viewing.'}">
  16810. * </ng-pluralize>
  16811. *</pre>
  16812. *
  16813. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  16814. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  16815. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  16816. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  16817. * show "a dozen people are viewing".
  16818. *
  16819. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  16820. * into pluralized strings. In the previous example, Angular will replace `{}` with
  16821. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  16822. * for <span ng-non-bindable>{{numberExpression}}</span>.
  16823. *
  16824. * # Configuring ngPluralize with offset
  16825. * The `offset` attribute allows further customization of pluralized text, which can result in
  16826. * a better user experience. For example, instead of the message "4 people are viewing this document",
  16827. * you might display "John, Kate and 2 others are viewing this document".
  16828. * The offset attribute allows you to offset a number by any desired value.
  16829. * Let's take a look at an example:
  16830. *
  16831. * <pre>
  16832. * <ng-pluralize count="personCount" offset=2
  16833. * when="{'0': 'Nobody is viewing.',
  16834. * '1': '{{person1}} is viewing.',
  16835. * '2': '{{person1}} and {{person2}} are viewing.',
  16836. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  16837. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  16838. * </ng-pluralize>
  16839. * </pre>
  16840. *
  16841. * Notice that we are still using two plural categories(one, other), but we added
  16842. * three explicit number rules 0, 1 and 2.
  16843. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  16844. * When three people view the document, no explicit number rule is found, so
  16845. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  16846. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
  16847. * is shown.
  16848. *
  16849. * Note that when you specify offsets, you must provide explicit number rules for
  16850. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  16851. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  16852. * plural categories "one" and "other".
  16853. *
  16854. * @param {string|expression} count The variable to be bounded to.
  16855. * @param {string} when The mapping between plural category to its corresponding strings.
  16856. * @param {number=} offset Offset to deduct from the total number.
  16857. *
  16858. * @example
  16859. <doc:example>
  16860. <doc:source>
  16861. <script>
  16862. function Ctrl($scope) {
  16863. $scope.person1 = 'Igor';
  16864. $scope.person2 = 'Misko';
  16865. $scope.personCount = 1;
  16866. }
  16867. </script>
  16868. <div ng-controller="Ctrl">
  16869. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  16870. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  16871. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  16872. <!--- Example with simple pluralization rules for en locale --->
  16873. Without Offset:
  16874. <ng-pluralize count="personCount"
  16875. when="{'0': 'Nobody is viewing.',
  16876. 'one': '1 person is viewing.',
  16877. 'other': '{} people are viewing.'}">
  16878. </ng-pluralize><br>
  16879. <!--- Example with offset --->
  16880. With Offset(2):
  16881. <ng-pluralize count="personCount" offset=2
  16882. when="{'0': 'Nobody is viewing.',
  16883. '1': '{{person1}} is viewing.',
  16884. '2': '{{person1}} and {{person2}} are viewing.',
  16885. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  16886. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  16887. </ng-pluralize>
  16888. </div>
  16889. </doc:source>
  16890. <doc:scenario>
  16891. it('should show correct pluralized string', function() {
  16892. expect(element('.doc-example-live ng-pluralize:first').text()).
  16893. toBe('1 person is viewing.');
  16894. expect(element('.doc-example-live ng-pluralize:last').text()).
  16895. toBe('Igor is viewing.');
  16896. using('.doc-example-live').input('personCount').enter('0');
  16897. expect(element('.doc-example-live ng-pluralize:first').text()).
  16898. toBe('Nobody is viewing.');
  16899. expect(element('.doc-example-live ng-pluralize:last').text()).
  16900. toBe('Nobody is viewing.');
  16901. using('.doc-example-live').input('personCount').enter('2');
  16902. expect(element('.doc-example-live ng-pluralize:first').text()).
  16903. toBe('2 people are viewing.');
  16904. expect(element('.doc-example-live ng-pluralize:last').text()).
  16905. toBe('Igor and Misko are viewing.');
  16906. using('.doc-example-live').input('personCount').enter('3');
  16907. expect(element('.doc-example-live ng-pluralize:first').text()).
  16908. toBe('3 people are viewing.');
  16909. expect(element('.doc-example-live ng-pluralize:last').text()).
  16910. toBe('Igor, Misko and one other person are viewing.');
  16911. using('.doc-example-live').input('personCount').enter('4');
  16912. expect(element('.doc-example-live ng-pluralize:first').text()).
  16913. toBe('4 people are viewing.');
  16914. expect(element('.doc-example-live ng-pluralize:last').text()).
  16915. toBe('Igor, Misko and 2 other people are viewing.');
  16916. });
  16917. it('should show data-binded names', function() {
  16918. using('.doc-example-live').input('personCount').enter('4');
  16919. expect(element('.doc-example-live ng-pluralize:last').text()).
  16920. toBe('Igor, Misko and 2 other people are viewing.');
  16921. using('.doc-example-live').input('person1').enter('Di');
  16922. using('.doc-example-live').input('person2').enter('Vojta');
  16923. expect(element('.doc-example-live ng-pluralize:last').text()).
  16924. toBe('Di, Vojta and 2 other people are viewing.');
  16925. });
  16926. </doc:scenario>
  16927. </doc:example>
  16928. */
  16929. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  16930. var BRACE = /{}/g;
  16931. return {
  16932. restrict: 'EA',
  16933. link: function(scope, element, attr) {
  16934. var numberExp = attr.count,
  16935. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  16936. offset = attr.offset || 0,
  16937. whens = scope.$eval(whenExp) || {},
  16938. whensExpFns = {},
  16939. startSymbol = $interpolate.startSymbol(),
  16940. endSymbol = $interpolate.endSymbol(),
  16941. isWhen = /^when(Minus)?(.+)$/;
  16942. forEach(attr, function(expression, attributeName) {
  16943. if (isWhen.test(attributeName)) {
  16944. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  16945. element.attr(attr.$attr[attributeName]);
  16946. }
  16947. });
  16948. forEach(whens, function(expression, key) {
  16949. whensExpFns[key] =
  16950. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  16951. offset + endSymbol));
  16952. });
  16953. scope.$watch(function ngPluralizeWatch() {
  16954. var value = parseFloat(scope.$eval(numberExp));
  16955. if (!isNaN(value)) {
  16956. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  16957. //check it against pluralization rules in $locale service
  16958. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  16959. return whensExpFns[value](scope, element, true);
  16960. } else {
  16961. return '';
  16962. }
  16963. }, function ngPluralizeWatchAction(newVal) {
  16964. element.text(newVal);
  16965. });
  16966. }
  16967. };
  16968. }];
  16969. /**
  16970. * @ngdoc directive
  16971. * @name ng.directive:ngRepeat
  16972. *
  16973. * @description
  16974. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  16975. * instance gets its own scope, where the given loop variable is set to the current collection item,
  16976. * and `$index` is set to the item index or key.
  16977. *
  16978. * Special properties are exposed on the local scope of each template instance, including:
  16979. *
  16980. * | Variable | Type | Details |
  16981. * |-----------|-----------------|-----------------------------------------------------------------------------|
  16982. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  16983. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  16984. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  16985. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  16986. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  16987. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  16988. *
  16989. *
  16990. * # Special repeat start and end points
  16991. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  16992. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  16993. * 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)
  16994. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  16995. *
  16996. * The example below makes use of this feature:
  16997. * <pre>
  16998. * <header ng-repeat-start="item in items">
  16999. * Header {{ item }}
  17000. * </header>
  17001. * <div class="body">
  17002. * Body {{ item }}
  17003. * </div>
  17004. * <footer ng-repeat-end>
  17005. * Footer {{ item }}
  17006. * </footer>
  17007. * </pre>
  17008. *
  17009. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  17010. * <pre>
  17011. * <header>
  17012. * Header A
  17013. * </header>
  17014. * <div class="body">
  17015. * Body A
  17016. * </div>
  17017. * <footer>
  17018. * Footer A
  17019. * </footer>
  17020. * <header>
  17021. * Header B
  17022. * </header>
  17023. * <div class="body">
  17024. * Body B
  17025. * </div>
  17026. * <footer>
  17027. * Footer B
  17028. * </footer>
  17029. * </pre>
  17030. *
  17031. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  17032. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  17033. *
  17034. * @animations
  17035. * enter - when a new item is added to the list or when an item is revealed after a filter
  17036. * leave - when an item is removed from the list or when an item is filtered out
  17037. * move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  17038. *
  17039. * @element ANY
  17040. * @scope
  17041. * @priority 1000
  17042. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  17043. * formats are currently supported:
  17044. *
  17045. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  17046. * is a scope expression giving the collection to enumerate.
  17047. *
  17048. * For example: `album in artist.albums`.
  17049. *
  17050. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  17051. * and `expression` is the scope expression giving the collection to enumerate.
  17052. *
  17053. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  17054. *
  17055. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  17056. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  17057. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  17058. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  17059. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  17060. * before specifying a tracking expression.
  17061. *
  17062. * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements
  17063. * will be associated by item identity in the array.
  17064. *
  17065. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  17066. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  17067. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  17068. * element in the same way in the DOM.
  17069. *
  17070. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  17071. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  17072. * property is same.
  17073. *
  17074. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  17075. * to items in conjunction with a tracking expression.
  17076. *
  17077. * @example
  17078. * This example initializes the scope to a list of names and
  17079. * then uses `ngRepeat` to display every person:
  17080. <example animations="true">
  17081. <file name="index.html">
  17082. <div ng-init="friends = [
  17083. {name:'John', age:25, gender:'boy'},
  17084. {name:'Jessie', age:30, gender:'girl'},
  17085. {name:'Johanna', age:28, gender:'girl'},
  17086. {name:'Joy', age:15, gender:'girl'},
  17087. {name:'Mary', age:28, gender:'girl'},
  17088. {name:'Peter', age:95, gender:'boy'},
  17089. {name:'Sebastian', age:50, gender:'boy'},
  17090. {name:'Erika', age:27, gender:'girl'},
  17091. {name:'Patrick', age:40, gender:'boy'},
  17092. {name:'Samantha', age:60, gender:'girl'}
  17093. ]">
  17094. I have {{friends.length}} friends. They are:
  17095. <input type="search" ng-model="q" placeholder="filter friends..." />
  17096. <ul class="example-animate-container">
  17097. <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
  17098. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  17099. </li>
  17100. </ul>
  17101. </div>
  17102. </file>
  17103. <file name="animations.css">
  17104. .example-animate-container {
  17105. background:white;
  17106. border:1px solid black;
  17107. list-style:none;
  17108. margin:0;
  17109. padding:0 10px;
  17110. }
  17111. .animate-repeat {
  17112. line-height:40px;
  17113. list-style:none;
  17114. box-sizing:border-box;
  17115. }
  17116. .animate-repeat.ng-move,
  17117. .animate-repeat.ng-enter,
  17118. .animate-repeat.ng-leave {
  17119. -webkit-transition:all linear 0.5s;
  17120. transition:all linear 0.5s;
  17121. }
  17122. .animate-repeat.ng-leave.ng-leave-active,
  17123. .animate-repeat.ng-move,
  17124. .animate-repeat.ng-enter {
  17125. opacity:0;
  17126. max-height:0;
  17127. }
  17128. .animate-repeat.ng-leave,
  17129. .animate-repeat.ng-move.ng-move-active,
  17130. .animate-repeat.ng-enter.ng-enter-active {
  17131. opacity:1;
  17132. max-height:40px;
  17133. }
  17134. </file>
  17135. <file name="scenario.js">
  17136. it('should render initial data set', function() {
  17137. var r = using('.doc-example-live').repeater('ul li');
  17138. expect(r.count()).toBe(10);
  17139. expect(r.row(0)).toEqual(["1","John","25"]);
  17140. expect(r.row(1)).toEqual(["2","Jessie","30"]);
  17141. expect(r.row(9)).toEqual(["10","Samantha","60"]);
  17142. expect(binding('friends.length')).toBe("10");
  17143. });
  17144. it('should update repeater when filter predicate changes', function() {
  17145. var r = using('.doc-example-live').repeater('ul li');
  17146. expect(r.count()).toBe(10);
  17147. input('q').enter('ma');
  17148. expect(r.count()).toBe(2);
  17149. expect(r.row(0)).toEqual(["1","Mary","28"]);
  17150. expect(r.row(1)).toEqual(["2","Samantha","60"]);
  17151. });
  17152. </file>
  17153. </example>
  17154. */
  17155. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  17156. var NG_REMOVED = '$$NG_REMOVED';
  17157. var ngRepeatMinErr = minErr('ngRepeat');
  17158. return {
  17159. transclude: 'element',
  17160. priority: 1000,
  17161. terminal: true,
  17162. $$tlb: true,
  17163. link: function($scope, $element, $attr, ctrl, $transclude){
  17164. var expression = $attr.ngRepeat;
  17165. var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),
  17166. trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
  17167. lhs, rhs, valueIdentifier, keyIdentifier,
  17168. hashFnLocals = {$id: hashKey};
  17169. if (!match) {
  17170. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  17171. expression);
  17172. }
  17173. lhs = match[1];
  17174. rhs = match[2];
  17175. trackByExp = match[4];
  17176. if (trackByExp) {
  17177. trackByExpGetter = $parse(trackByExp);
  17178. trackByIdExpFn = function(key, value, index) {
  17179. // assign key, value, and $index to the locals so that they can be used in hash functions
  17180. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  17181. hashFnLocals[valueIdentifier] = value;
  17182. hashFnLocals.$index = index;
  17183. return trackByExpGetter($scope, hashFnLocals);
  17184. };
  17185. } else {
  17186. trackByIdArrayFn = function(key, value) {
  17187. return hashKey(value);
  17188. };
  17189. trackByIdObjFn = function(key) {
  17190. return key;
  17191. };
  17192. }
  17193. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  17194. if (!match) {
  17195. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  17196. lhs);
  17197. }
  17198. valueIdentifier = match[3] || match[1];
  17199. keyIdentifier = match[2];
  17200. // Store a list of elements from previous run. This is a hash where key is the item from the
  17201. // iterator, and the value is objects with following properties.
  17202. // - scope: bound scope
  17203. // - element: previous element.
  17204. // - index: position
  17205. var lastBlockMap = {};
  17206. //watch props
  17207. $scope.$watchCollection(rhs, function ngRepeatAction(collection){
  17208. var index, length,
  17209. previousNode = $element[0], // current position of the node
  17210. nextNode,
  17211. // Same as lastBlockMap but it has the current state. It will become the
  17212. // lastBlockMap on the next iteration.
  17213. nextBlockMap = {},
  17214. arrayLength,
  17215. childScope,
  17216. key, value, // key/value of iteration
  17217. trackById,
  17218. trackByIdFn,
  17219. collectionKeys,
  17220. block, // last object information {scope, element, id}
  17221. nextBlockOrder = [],
  17222. elementsToRemove;
  17223. if (isArrayLike(collection)) {
  17224. collectionKeys = collection;
  17225. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  17226. } else {
  17227. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  17228. // if object, extract keys, sort them and use to determine order of iteration over obj props
  17229. collectionKeys = [];
  17230. for (key in collection) {
  17231. if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
  17232. collectionKeys.push(key);
  17233. }
  17234. }
  17235. collectionKeys.sort();
  17236. }
  17237. arrayLength = collectionKeys.length;
  17238. // locate existing items
  17239. length = nextBlockOrder.length = collectionKeys.length;
  17240. for(index = 0; index < length; index++) {
  17241. key = (collection === collectionKeys) ? index : collectionKeys[index];
  17242. value = collection[key];
  17243. trackById = trackByIdFn(key, value, index);
  17244. assertNotHasOwnProperty(trackById, '`track by` id');
  17245. if(lastBlockMap.hasOwnProperty(trackById)) {
  17246. block = lastBlockMap[trackById];
  17247. delete lastBlockMap[trackById];
  17248. nextBlockMap[trackById] = block;
  17249. nextBlockOrder[index] = block;
  17250. } else if (nextBlockMap.hasOwnProperty(trackById)) {
  17251. // restore lastBlockMap
  17252. forEach(nextBlockOrder, function(block) {
  17253. if (block && block.scope) lastBlockMap[block.id] = block;
  17254. });
  17255. // This is a duplicate and we need to throw an error
  17256. throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
  17257. expression, trackById);
  17258. } else {
  17259. // new never before seen block
  17260. nextBlockOrder[index] = { id: trackById };
  17261. nextBlockMap[trackById] = false;
  17262. }
  17263. }
  17264. // remove existing items
  17265. for (key in lastBlockMap) {
  17266. // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
  17267. if (lastBlockMap.hasOwnProperty(key)) {
  17268. block = lastBlockMap[key];
  17269. elementsToRemove = getBlockElements(block.clone);
  17270. $animate.leave(elementsToRemove);
  17271. forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
  17272. block.scope.$destroy();
  17273. }
  17274. }
  17275. // we are not using forEach for perf reasons (trying to avoid #call)
  17276. for (index = 0, length = collectionKeys.length; index < length; index++) {
  17277. key = (collection === collectionKeys) ? index : collectionKeys[index];
  17278. value = collection[key];
  17279. block = nextBlockOrder[index];
  17280. if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
  17281. if (block.scope) {
  17282. // if we have already seen this object, then we need to reuse the
  17283. // associated scope/element
  17284. childScope = block.scope;
  17285. nextNode = previousNode;
  17286. do {
  17287. nextNode = nextNode.nextSibling;
  17288. } while(nextNode && nextNode[NG_REMOVED]);
  17289. if (getBlockStart(block) != nextNode) {
  17290. // existing item which got moved
  17291. $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
  17292. }
  17293. previousNode = getBlockEnd(block);
  17294. } else {
  17295. // new item which we don't know about
  17296. childScope = $scope.$new();
  17297. }
  17298. childScope[valueIdentifier] = value;
  17299. if (keyIdentifier) childScope[keyIdentifier] = key;
  17300. childScope.$index = index;
  17301. childScope.$first = (index === 0);
  17302. childScope.$last = (index === (arrayLength - 1));
  17303. childScope.$middle = !(childScope.$first || childScope.$last);
  17304. // jshint bitwise: false
  17305. childScope.$odd = !(childScope.$even = (index&1) === 0);
  17306. // jshint bitwise: true
  17307. if (!block.scope) {
  17308. $transclude(childScope, function(clone) {
  17309. clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
  17310. $animate.enter(clone, null, jqLite(previousNode));
  17311. previousNode = clone;
  17312. block.scope = childScope;
  17313. // Note: We only need the first/last node of the cloned nodes.
  17314. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  17315. // by a directive with templateUrl when it's template arrives.
  17316. block.clone = clone;
  17317. nextBlockMap[block.id] = block;
  17318. });
  17319. }
  17320. }
  17321. lastBlockMap = nextBlockMap;
  17322. });
  17323. }
  17324. };
  17325. function getBlockStart(block) {
  17326. return block.clone[0];
  17327. }
  17328. function getBlockEnd(block) {
  17329. return block.clone[block.clone.length - 1];
  17330. }
  17331. }];
  17332. /**
  17333. * @ngdoc directive
  17334. * @name ng.directive:ngShow
  17335. *
  17336. * @description
  17337. * The `ngShow` directive shows or hides the given HTML element based on the expression
  17338. * provided to the ngShow attribute. The element is shown or hidden by removing or adding
  17339. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  17340. * in AngularJS and sets the display style to none (using an !important flag).
  17341. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  17342. *
  17343. * <pre>
  17344. * <!-- when $scope.myValue is truthy (element is visible) -->
  17345. * <div ng-show="myValue"></div>
  17346. *
  17347. * <!-- when $scope.myValue is falsy (element is hidden) -->
  17348. * <div ng-show="myValue" class="ng-hide"></div>
  17349. * </pre>
  17350. *
  17351. * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute
  17352. * on the element causing it to become hidden. When true, the ng-hide CSS class is removed
  17353. * from the element causing the element not to appear hidden.
  17354. *
  17355. * ## Why is !important used?
  17356. *
  17357. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  17358. * can be easily overridden by heavier selectors. For example, something as simple
  17359. * as changing the display style on a HTML list item would make hidden elements appear visible.
  17360. * This also becomes a bigger issue when dealing with CSS frameworks.
  17361. *
  17362. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  17363. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  17364. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  17365. *
  17366. * ### Overriding .ng-hide
  17367. *
  17368. * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
  17369. * restating the styles for the .ng-hide class in CSS:
  17370. * <pre>
  17371. * .ng-hide {
  17372. * //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
  17373. * display:block!important;
  17374. *
  17375. * //this is just another form of hiding an element
  17376. * position:absolute;
  17377. * top:-9999px;
  17378. * left:-9999px;
  17379. * }
  17380. * </pre>
  17381. *
  17382. * Just remember to include the important flag so the CSS override will function.
  17383. *
  17384. * ## A note about animations with ngShow
  17385. *
  17386. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  17387. * is true and false. This system works like the animation system present with ngClass except that
  17388. * you must also include the !important flag to override the display property
  17389. * so that you can perform an animation when the element is hidden during the time of the animation.
  17390. *
  17391. * <pre>
  17392. * //
  17393. * //a working example can be found at the bottom of this page
  17394. * //
  17395. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  17396. * transition:0.5s linear all;
  17397. * display:block!important;
  17398. * }
  17399. *
  17400. * .my-element.ng-hide-add { ... }
  17401. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  17402. * .my-element.ng-hide-remove { ... }
  17403. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  17404. * </pre>
  17405. *
  17406. * @animations
  17407. * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
  17408. * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
  17409. *
  17410. * @element ANY
  17411. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  17412. * then the element is shown or hidden respectively.
  17413. *
  17414. * @example
  17415. <example animations="true">
  17416. <file name="index.html">
  17417. Click me: <input type="checkbox" ng-model="checked"><br/>
  17418. <div>
  17419. Show:
  17420. <div class="check-element animate-show" ng-show="checked">
  17421. <span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
  17422. </div>
  17423. </div>
  17424. <div>
  17425. Hide:
  17426. <div class="check-element animate-show" ng-hide="checked">
  17427. <span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
  17428. </div>
  17429. </div>
  17430. </file>
  17431. <file name="animations.css">
  17432. .animate-show {
  17433. -webkit-transition:all linear 0.5s;
  17434. transition:all linear 0.5s;
  17435. line-height:20px;
  17436. opacity:1;
  17437. padding:10px;
  17438. border:1px solid black;
  17439. background:white;
  17440. }
  17441. .animate-show.ng-hide-add,
  17442. .animate-show.ng-hide-remove {
  17443. display:block!important;
  17444. }
  17445. .animate-show.ng-hide {
  17446. line-height:0;
  17447. opacity:0;
  17448. padding:0 10px;
  17449. }
  17450. .check-element {
  17451. padding:10px;
  17452. border:1px solid black;
  17453. background:white;
  17454. }
  17455. </file>
  17456. <file name="scenario.js">
  17457. it('should check ng-show / ng-hide', function() {
  17458. expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
  17459. expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
  17460. input('checked').check();
  17461. expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
  17462. expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
  17463. });
  17464. </file>
  17465. </example>
  17466. */
  17467. var ngShowDirective = ['$animate', function($animate) {
  17468. return function(scope, element, attr) {
  17469. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  17470. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
  17471. });
  17472. };
  17473. }];
  17474. /**
  17475. * @ngdoc directive
  17476. * @name ng.directive:ngHide
  17477. *
  17478. * @description
  17479. * The `ngHide` directive shows or hides the given HTML element based on the expression
  17480. * provided to the ngHide attribute. The element is shown or hidden by removing or adding
  17481. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  17482. * in AngularJS and sets the display style to none (using an !important flag).
  17483. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  17484. *
  17485. * <pre>
  17486. * <!-- when $scope.myValue is truthy (element is hidden) -->
  17487. * <div ng-hide="myValue"></div>
  17488. *
  17489. * <!-- when $scope.myValue is falsy (element is visible) -->
  17490. * <div ng-hide="myValue" class="ng-hide"></div>
  17491. * </pre>
  17492. *
  17493. * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute
  17494. * on the element causing it to become hidden. When false, the ng-hide CSS class is removed
  17495. * from the element causing the element not to appear hidden.
  17496. *
  17497. * ## Why is !important used?
  17498. *
  17499. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  17500. * can be easily overridden by heavier selectors. For example, something as simple
  17501. * as changing the display style on a HTML list item would make hidden elements appear visible.
  17502. * This also becomes a bigger issue when dealing with CSS frameworks.
  17503. *
  17504. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  17505. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  17506. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  17507. *
  17508. * ### Overriding .ng-hide
  17509. *
  17510. * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
  17511. * restating the styles for the .ng-hide class in CSS:
  17512. * <pre>
  17513. * .ng-hide {
  17514. * //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
  17515. * display:block!important;
  17516. *
  17517. * //this is just another form of hiding an element
  17518. * position:absolute;
  17519. * top:-9999px;
  17520. * left:-9999px;
  17521. * }
  17522. * </pre>
  17523. *
  17524. * Just remember to include the important flag so the CSS override will function.
  17525. *
  17526. * ## A note about animations with ngHide
  17527. *
  17528. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  17529. * is true and false. This system works like the animation system present with ngClass, except that
  17530. * you must also include the !important flag to override the display property so
  17531. * that you can perform an animation when the element is hidden during the time of the animation.
  17532. *
  17533. * <pre>
  17534. * //
  17535. * //a working example can be found at the bottom of this page
  17536. * //
  17537. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  17538. * transition:0.5s linear all;
  17539. * display:block!important;
  17540. * }
  17541. *
  17542. * .my-element.ng-hide-add { ... }
  17543. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  17544. * .my-element.ng-hide-remove { ... }
  17545. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  17546. * </pre>
  17547. *
  17548. * @animations
  17549. * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
  17550. * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
  17551. *
  17552. * @element ANY
  17553. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  17554. * the element is shown or hidden respectively.
  17555. *
  17556. * @example
  17557. <example animations="true">
  17558. <file name="index.html">
  17559. Click me: <input type="checkbox" ng-model="checked"><br/>
  17560. <div>
  17561. Show:
  17562. <div class="check-element animate-hide" ng-show="checked">
  17563. <span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
  17564. </div>
  17565. </div>
  17566. <div>
  17567. Hide:
  17568. <div class="check-element animate-hide" ng-hide="checked">
  17569. <span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
  17570. </div>
  17571. </div>
  17572. </file>
  17573. <file name="animations.css">
  17574. .animate-hide {
  17575. -webkit-transition:all linear 0.5s;
  17576. transition:all linear 0.5s;
  17577. line-height:20px;
  17578. opacity:1;
  17579. padding:10px;
  17580. border:1px solid black;
  17581. background:white;
  17582. }
  17583. .animate-hide.ng-hide-add,
  17584. .animate-hide.ng-hide-remove {
  17585. display:block!important;
  17586. }
  17587. .animate-hide.ng-hide {
  17588. line-height:0;
  17589. opacity:0;
  17590. padding:0 10px;
  17591. }
  17592. .check-element {
  17593. padding:10px;
  17594. border:1px solid black;
  17595. background:white;
  17596. }
  17597. </file>
  17598. <file name="scenario.js">
  17599. it('should check ng-show / ng-hide', function() {
  17600. expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1);
  17601. expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1);
  17602. input('checked').check();
  17603. expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1);
  17604. expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1);
  17605. });
  17606. </file>
  17607. </example>
  17608. */
  17609. var ngHideDirective = ['$animate', function($animate) {
  17610. return function(scope, element, attr) {
  17611. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  17612. $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
  17613. });
  17614. };
  17615. }];
  17616. /**
  17617. * @ngdoc directive
  17618. * @name ng.directive:ngStyle
  17619. * @restrict AC
  17620. *
  17621. * @description
  17622. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  17623. *
  17624. * @element ANY
  17625. * @param {expression} ngStyle {@link guide/expression Expression} which evals to an
  17626. * object whose keys are CSS style names and values are corresponding values for those CSS
  17627. * keys.
  17628. *
  17629. * @example
  17630. <example>
  17631. <file name="index.html">
  17632. <input type="button" value="set" ng-click="myStyle={color:'red'}">
  17633. <input type="button" value="clear" ng-click="myStyle={}">
  17634. <br/>
  17635. <span ng-style="myStyle">Sample Text</span>
  17636. <pre>myStyle={{myStyle}}</pre>
  17637. </file>
  17638. <file name="style.css">
  17639. span {
  17640. color: black;
  17641. }
  17642. </file>
  17643. <file name="scenario.js">
  17644. it('should check ng-style', function() {
  17645. expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
  17646. element('.doc-example-live :button[value=set]').click();
  17647. expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
  17648. element('.doc-example-live :button[value=clear]').click();
  17649. expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
  17650. });
  17651. </file>
  17652. </example>
  17653. */
  17654. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  17655. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  17656. if (oldStyles && (newStyles !== oldStyles)) {
  17657. forEach(oldStyles, function(val, style) { element.css(style, '');});
  17658. }
  17659. if (newStyles) element.css(newStyles);
  17660. }, true);
  17661. });
  17662. /**
  17663. * @ngdoc directive
  17664. * @name ng.directive:ngSwitch
  17665. * @restrict EA
  17666. *
  17667. * @description
  17668. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  17669. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  17670. * as specified in the template.
  17671. *
  17672. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  17673. * from the template cache), `ngSwitch` simply choses one of the nested elements and makes it visible based on which element
  17674. * matches the value obtained from the evaluated expression. In other words, you define a container element
  17675. * (where you place the directive), place an expression on the **`on="..."` attribute**
  17676. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  17677. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  17678. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  17679. * attribute is displayed.
  17680. *
  17681. * <div class="alert alert-info">
  17682. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  17683. * as literal string values to match against.
  17684. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  17685. * value of the expression `$scope.someVal`.
  17686. * </div>
  17687. * @animations
  17688. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  17689. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  17690. *
  17691. * @usage
  17692. * <ANY ng-switch="expression">
  17693. * <ANY ng-switch-when="matchValue1">...</ANY>
  17694. * <ANY ng-switch-when="matchValue2">...</ANY>
  17695. * <ANY ng-switch-default>...</ANY>
  17696. * </ANY>
  17697. *
  17698. *
  17699. * @scope
  17700. * @priority 800
  17701. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  17702. * @paramDescription
  17703. * On child elements add:
  17704. *
  17705. * * `ngSwitchWhen`: the case statement to match against. If match then this
  17706. * case will be displayed. If the same match appears multiple times, all the
  17707. * elements will be displayed.
  17708. * * `ngSwitchDefault`: the default case when no other case match. If there
  17709. * are multiple default cases, all of them will be displayed when no other
  17710. * case match.
  17711. *
  17712. *
  17713. * @example
  17714. <example animations="true">
  17715. <file name="index.html">
  17716. <div ng-controller="Ctrl">
  17717. <select ng-model="selection" ng-options="item for item in items">
  17718. </select>
  17719. <tt>selection={{selection}}</tt>
  17720. <hr/>
  17721. <div class="animate-switch-container"
  17722. ng-switch on="selection">
  17723. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  17724. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  17725. <div class="animate-switch" ng-switch-default>default</div>
  17726. </div>
  17727. </div>
  17728. </file>
  17729. <file name="script.js">
  17730. function Ctrl($scope) {
  17731. $scope.items = ['settings', 'home', 'other'];
  17732. $scope.selection = $scope.items[0];
  17733. }
  17734. </file>
  17735. <file name="animations.css">
  17736. .animate-switch-container {
  17737. position:relative;
  17738. background:white;
  17739. border:1px solid black;
  17740. height:40px;
  17741. overflow:hidden;
  17742. }
  17743. .animate-switch {
  17744. padding:10px;
  17745. }
  17746. .animate-switch.ng-animate {
  17747. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17748. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17749. position:absolute;
  17750. top:0;
  17751. left:0;
  17752. right:0;
  17753. bottom:0;
  17754. }
  17755. .animate-switch.ng-leave.ng-leave-active,
  17756. .animate-switch.ng-enter {
  17757. top:-50px;
  17758. }
  17759. .animate-switch.ng-leave,
  17760. .animate-switch.ng-enter.ng-enter-active {
  17761. top:0;
  17762. }
  17763. </file>
  17764. <file name="scenario.js">
  17765. it('should start in settings', function() {
  17766. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
  17767. });
  17768. it('should change to home', function() {
  17769. select('selection').option('home');
  17770. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
  17771. });
  17772. it('should select default', function() {
  17773. select('selection').option('other');
  17774. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
  17775. });
  17776. </file>
  17777. </example>
  17778. */
  17779. var ngSwitchDirective = ['$animate', function($animate) {
  17780. return {
  17781. restrict: 'EA',
  17782. require: 'ngSwitch',
  17783. // asks for $scope to fool the BC controller module
  17784. controller: ['$scope', function ngSwitchController() {
  17785. this.cases = {};
  17786. }],
  17787. link: function(scope, element, attr, ngSwitchController) {
  17788. var watchExpr = attr.ngSwitch || attr.on,
  17789. selectedTranscludes,
  17790. selectedElements,
  17791. selectedScopes = [];
  17792. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  17793. for (var i= 0, ii=selectedScopes.length; i<ii; i++) {
  17794. selectedScopes[i].$destroy();
  17795. $animate.leave(selectedElements[i]);
  17796. }
  17797. selectedElements = [];
  17798. selectedScopes = [];
  17799. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  17800. scope.$eval(attr.change);
  17801. forEach(selectedTranscludes, function(selectedTransclude) {
  17802. var selectedScope = scope.$new();
  17803. selectedScopes.push(selectedScope);
  17804. selectedTransclude.transclude(selectedScope, function(caseElement) {
  17805. var anchor = selectedTransclude.element;
  17806. selectedElements.push(caseElement);
  17807. $animate.enter(caseElement, anchor.parent(), anchor);
  17808. });
  17809. });
  17810. }
  17811. });
  17812. }
  17813. };
  17814. }];
  17815. var ngSwitchWhenDirective = ngDirective({
  17816. transclude: 'element',
  17817. priority: 800,
  17818. require: '^ngSwitch',
  17819. compile: function(element, attrs) {
  17820. return function(scope, element, attr, ctrl, $transclude) {
  17821. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  17822. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  17823. };
  17824. }
  17825. });
  17826. var ngSwitchDefaultDirective = ngDirective({
  17827. transclude: 'element',
  17828. priority: 800,
  17829. require: '^ngSwitch',
  17830. link: function(scope, element, attr, ctrl, $transclude) {
  17831. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  17832. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  17833. }
  17834. });
  17835. /**
  17836. * @ngdoc directive
  17837. * @name ng.directive:ngTransclude
  17838. * @restrict AC
  17839. *
  17840. * @description
  17841. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  17842. *
  17843. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  17844. *
  17845. * @element ANY
  17846. *
  17847. * @example
  17848. <doc:example module="transclude">
  17849. <doc:source>
  17850. <script>
  17851. function Ctrl($scope) {
  17852. $scope.title = 'Lorem Ipsum';
  17853. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  17854. }
  17855. angular.module('transclude', [])
  17856. .directive('pane', function(){
  17857. return {
  17858. restrict: 'E',
  17859. transclude: true,
  17860. scope: { title:'@' },
  17861. template: '<div style="border: 1px solid black;">' +
  17862. '<div style="background-color: gray">{{title}}</div>' +
  17863. '<div ng-transclude></div>' +
  17864. '</div>'
  17865. };
  17866. });
  17867. </script>
  17868. <div ng-controller="Ctrl">
  17869. <input ng-model="title"><br>
  17870. <textarea ng-model="text"></textarea> <br/>
  17871. <pane title="{{title}}">{{text}}</pane>
  17872. </div>
  17873. </doc:source>
  17874. <doc:scenario>
  17875. it('should have transcluded', function() {
  17876. input('title').enter('TITLE');
  17877. input('text').enter('TEXT');
  17878. expect(binding('title')).toEqual('TITLE');
  17879. expect(binding('text')).toEqual('TEXT');
  17880. });
  17881. </doc:scenario>
  17882. </doc:example>
  17883. *
  17884. */
  17885. var ngTranscludeDirective = ngDirective({
  17886. controller: ['$element', '$transclude', function($element, $transclude) {
  17887. if (!$transclude) {
  17888. throw minErr('ngTransclude')('orphan',
  17889. 'Illegal use of ngTransclude directive in the template! ' +
  17890. 'No parent directive that requires a transclusion found. ' +
  17891. 'Element: {0}',
  17892. startingTag($element));
  17893. }
  17894. // remember the transclusion fn but call it during linking so that we don't process transclusion before directives on
  17895. // the parent element even when the transclusion replaces the current element. (we can't use priority here because
  17896. // that applies only to compile fns and not controllers
  17897. this.$transclude = $transclude;
  17898. }],
  17899. link: function($scope, $element, $attrs, controller) {
  17900. controller.$transclude(function(clone) {
  17901. $element.empty();
  17902. $element.append(clone);
  17903. });
  17904. }
  17905. });
  17906. /**
  17907. * @ngdoc directive
  17908. * @name ng.directive:script
  17909. * @restrict E
  17910. *
  17911. * @description
  17912. * Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
  17913. * template can be used by `ngInclude`, `ngView` or directive templates.
  17914. *
  17915. * @param {'text/ng-template'} type must be set to `'text/ng-template'`
  17916. *
  17917. * @example
  17918. <doc:example>
  17919. <doc:source>
  17920. <script type="text/ng-template" id="/tpl.html">
  17921. Content of the template.
  17922. </script>
  17923. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  17924. <div id="tpl-content" ng-include src="currentTpl"></div>
  17925. </doc:source>
  17926. <doc:scenario>
  17927. it('should load template defined inside script tag', function() {
  17928. element('#tpl-link').click();
  17929. expect(element('#tpl-content').text()).toMatch(/Content of the template/);
  17930. });
  17931. </doc:scenario>
  17932. </doc:example>
  17933. */
  17934. var scriptDirective = ['$templateCache', function($templateCache) {
  17935. return {
  17936. restrict: 'E',
  17937. terminal: true,
  17938. compile: function(element, attr) {
  17939. if (attr.type == 'text/ng-template') {
  17940. var templateUrl = attr.id,
  17941. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  17942. text = element[0].text;
  17943. $templateCache.put(templateUrl, text);
  17944. }
  17945. }
  17946. };
  17947. }];
  17948. var ngOptionsMinErr = minErr('ngOptions');
  17949. /**
  17950. * @ngdoc directive
  17951. * @name ng.directive:select
  17952. * @restrict E
  17953. *
  17954. * @description
  17955. * HTML `SELECT` element with angular data-binding.
  17956. *
  17957. * # `ngOptions`
  17958. *
  17959. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  17960. * elements for the `<select>` element using the array or object obtained by evaluating the
  17961. * `ngOptions` comprehension_expression.
  17962. *
  17963. * When an item in the `<select>` menu is selected, the array element or object property
  17964. * represented by the selected option will be bound to the model identified by the `ngModel`
  17965. * directive.
  17966. *
  17967. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  17968. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  17969. * option. See example below for demonstration.
  17970. *
  17971. * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
  17972. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  17973. * `select` model to be bound to a non-string value. This is because an option element can only
  17974. * be bound to string values at present.
  17975. *
  17976. * @param {string} ngModel Assignable angular expression to data-bind to.
  17977. * @param {string=} name Property name of the form under which the control is published.
  17978. * @param {string=} required The control is considered valid only if value is entered.
  17979. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17980. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17981. * `required` when you want to data-bind to the `required` attribute.
  17982. * @param {comprehension_expression=} ngOptions in one of the following forms:
  17983. *
  17984. * * for array data sources:
  17985. * * `label` **`for`** `value` **`in`** `array`
  17986. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  17987. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  17988. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  17989. * * for object data sources:
  17990. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  17991. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  17992. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  17993. * * `select` **`as`** `label` **`group by`** `group`
  17994. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  17995. *
  17996. * Where:
  17997. *
  17998. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  17999. * * `value`: local variable which will refer to each item in the `array` or each property value
  18000. * of `object` during iteration.
  18001. * * `key`: local variable which will refer to a property name in `object` during iteration.
  18002. * * `label`: The result of this expression will be the label for `<option>` element. The
  18003. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  18004. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  18005. * element. If not specified, `select` expression will default to `value`.
  18006. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  18007. * DOM element.
  18008. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  18009. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  18010. * `value` variable (e.g. `value.propertyName`).
  18011. *
  18012. * @example
  18013. <doc:example>
  18014. <doc:source>
  18015. <script>
  18016. function MyCntrl($scope) {
  18017. $scope.colors = [
  18018. {name:'black', shade:'dark'},
  18019. {name:'white', shade:'light'},
  18020. {name:'red', shade:'dark'},
  18021. {name:'blue', shade:'dark'},
  18022. {name:'yellow', shade:'light'}
  18023. ];
  18024. $scope.color = $scope.colors[2]; // red
  18025. }
  18026. </script>
  18027. <div ng-controller="MyCntrl">
  18028. <ul>
  18029. <li ng-repeat="color in colors">
  18030. Name: <input ng-model="color.name">
  18031. [<a href ng-click="colors.splice($index, 1)">X</a>]
  18032. </li>
  18033. <li>
  18034. [<a href ng-click="colors.push({})">add</a>]
  18035. </li>
  18036. </ul>
  18037. <hr/>
  18038. Color (null not allowed):
  18039. <select ng-model="color" ng-options="c.name for c in colors"></select><br>
  18040. Color (null allowed):
  18041. <span class="nullable">
  18042. <select ng-model="color" ng-options="c.name for c in colors">
  18043. <option value="">-- choose color --</option>
  18044. </select>
  18045. </span><br/>
  18046. Color grouped by shade:
  18047. <select ng-model="color" ng-options="c.name group by c.shade for c in colors">
  18048. </select><br/>
  18049. Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
  18050. <hr/>
  18051. Currently selected: {{ {selected_color:color} }}
  18052. <div style="border:solid 1px black; height:20px"
  18053. ng-style="{'background-color':color.name}">
  18054. </div>
  18055. </div>
  18056. </doc:source>
  18057. <doc:scenario>
  18058. it('should check ng-options', function() {
  18059. expect(binding('{selected_color:color}')).toMatch('red');
  18060. select('color').option('0');
  18061. expect(binding('{selected_color:color}')).toMatch('black');
  18062. using('.nullable').select('color').option('');
  18063. expect(binding('{selected_color:color}')).toMatch('null');
  18064. });
  18065. </doc:scenario>
  18066. </doc:example>
  18067. */
  18068. var ngOptionsDirective = valueFn({ terminal: true });
  18069. // jshint maxlen: false
  18070. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  18071. //0000111110000000000022220000000000000000000000333300000000000000444444444444444000000000555555555555555000000066666666666666600000000000000007777000000000000000000088888
  18072. var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/,
  18073. nullModelCtrl = {$setViewValue: noop};
  18074. // jshint maxlen: 100
  18075. return {
  18076. restrict: 'E',
  18077. require: ['select', '?ngModel'],
  18078. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  18079. var self = this,
  18080. optionsMap = {},
  18081. ngModelCtrl = nullModelCtrl,
  18082. nullOption,
  18083. unknownOption;
  18084. self.databound = $attrs.ngModel;
  18085. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  18086. ngModelCtrl = ngModelCtrl_;
  18087. nullOption = nullOption_;
  18088. unknownOption = unknownOption_;
  18089. };
  18090. self.addOption = function(value) {
  18091. assertNotHasOwnProperty(value, '"option value"');
  18092. optionsMap[value] = true;
  18093. if (ngModelCtrl.$viewValue == value) {
  18094. $element.val(value);
  18095. if (unknownOption.parent()) unknownOption.remove();
  18096. }
  18097. };
  18098. self.removeOption = function(value) {
  18099. if (this.hasOption(value)) {
  18100. delete optionsMap[value];
  18101. if (ngModelCtrl.$viewValue == value) {
  18102. this.renderUnknownOption(value);
  18103. }
  18104. }
  18105. };
  18106. self.renderUnknownOption = function(val) {
  18107. var unknownVal = '? ' + hashKey(val) + ' ?';
  18108. unknownOption.val(unknownVal);
  18109. $element.prepend(unknownOption);
  18110. $element.val(unknownVal);
  18111. unknownOption.prop('selected', true); // needed for IE
  18112. };
  18113. self.hasOption = function(value) {
  18114. return optionsMap.hasOwnProperty(value);
  18115. };
  18116. $scope.$on('$destroy', function() {
  18117. // disable unknown option so that we don't do work when the whole select is being destroyed
  18118. self.renderUnknownOption = noop;
  18119. });
  18120. }],
  18121. link: function(scope, element, attr, ctrls) {
  18122. // if ngModel is not defined, we don't need to do anything
  18123. if (!ctrls[1]) return;
  18124. var selectCtrl = ctrls[0],
  18125. ngModelCtrl = ctrls[1],
  18126. multiple = attr.multiple,
  18127. optionsExp = attr.ngOptions,
  18128. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  18129. emptyOption,
  18130. // we can't just jqLite('<option>') since jqLite is not smart enough
  18131. // to create it in <select> and IE barfs otherwise.
  18132. optionTemplate = jqLite(document.createElement('option')),
  18133. optGroupTemplate =jqLite(document.createElement('optgroup')),
  18134. unknownOption = optionTemplate.clone();
  18135. // find "null" option
  18136. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  18137. if (children[i].value === '') {
  18138. emptyOption = nullOption = children.eq(i);
  18139. break;
  18140. }
  18141. }
  18142. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  18143. // required validator
  18144. if (multiple && (attr.required || attr.ngRequired)) {
  18145. var requiredValidator = function(value) {
  18146. ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
  18147. return value;
  18148. };
  18149. ngModelCtrl.$parsers.push(requiredValidator);
  18150. ngModelCtrl.$formatters.unshift(requiredValidator);
  18151. attr.$observe('required', function() {
  18152. requiredValidator(ngModelCtrl.$viewValue);
  18153. });
  18154. }
  18155. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  18156. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  18157. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  18158. ////////////////////////////
  18159. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  18160. ngModelCtrl.$render = function() {
  18161. var viewValue = ngModelCtrl.$viewValue;
  18162. if (selectCtrl.hasOption(viewValue)) {
  18163. if (unknownOption.parent()) unknownOption.remove();
  18164. selectElement.val(viewValue);
  18165. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  18166. } else {
  18167. if (isUndefined(viewValue) && emptyOption) {
  18168. selectElement.val('');
  18169. } else {
  18170. selectCtrl.renderUnknownOption(viewValue);
  18171. }
  18172. }
  18173. };
  18174. selectElement.on('change', function() {
  18175. scope.$apply(function() {
  18176. if (unknownOption.parent()) unknownOption.remove();
  18177. ngModelCtrl.$setViewValue(selectElement.val());
  18178. });
  18179. });
  18180. }
  18181. function setupAsMultiple(scope, selectElement, ctrl) {
  18182. var lastView;
  18183. ctrl.$render = function() {
  18184. var items = new HashMap(ctrl.$viewValue);
  18185. forEach(selectElement.find('option'), function(option) {
  18186. option.selected = isDefined(items.get(option.value));
  18187. });
  18188. };
  18189. // we have to do it on each watch since ngModel watches reference, but
  18190. // we need to work of an array, so we need to see if anything was inserted/removed
  18191. scope.$watch(function selectMultipleWatch() {
  18192. if (!equals(lastView, ctrl.$viewValue)) {
  18193. lastView = copy(ctrl.$viewValue);
  18194. ctrl.$render();
  18195. }
  18196. });
  18197. selectElement.on('change', function() {
  18198. scope.$apply(function() {
  18199. var array = [];
  18200. forEach(selectElement.find('option'), function(option) {
  18201. if (option.selected) {
  18202. array.push(option.value);
  18203. }
  18204. });
  18205. ctrl.$setViewValue(array);
  18206. });
  18207. });
  18208. }
  18209. function setupAsOptions(scope, selectElement, ctrl) {
  18210. var match;
  18211. if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  18212. throw ngOptionsMinErr('iexp',
  18213. "Expected expression in form of " +
  18214. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  18215. " but got '{0}'. Element: {1}",
  18216. optionsExp, startingTag(selectElement));
  18217. }
  18218. var displayFn = $parse(match[2] || match[1]),
  18219. valueName = match[4] || match[6],
  18220. keyName = match[5],
  18221. groupByFn = $parse(match[3] || ''),
  18222. valueFn = $parse(match[2] ? match[1] : valueName),
  18223. valuesFn = $parse(match[7]),
  18224. track = match[8],
  18225. trackFn = track ? $parse(match[8]) : null,
  18226. // This is an array of array of existing option groups in DOM.
  18227. // We try to reuse these if possible
  18228. // - optionGroupsCache[0] is the options with no option group
  18229. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  18230. optionGroupsCache = [[{element: selectElement, label:''}]];
  18231. if (nullOption) {
  18232. // compile the element since there might be bindings in it
  18233. $compile(nullOption)(scope);
  18234. // remove the class, which is added automatically because we recompile the element and it
  18235. // becomes the compilation root
  18236. nullOption.removeClass('ng-scope');
  18237. // we need to remove it before calling selectElement.empty() because otherwise IE will
  18238. // remove the label from the element. wtf?
  18239. nullOption.remove();
  18240. }
  18241. // clear contents, we'll add what's needed based on the model
  18242. selectElement.empty();
  18243. selectElement.on('change', function() {
  18244. scope.$apply(function() {
  18245. var optionGroup,
  18246. collection = valuesFn(scope) || [],
  18247. locals = {},
  18248. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  18249. if (multiple) {
  18250. value = [];
  18251. for (groupIndex = 0, groupLength = optionGroupsCache.length;
  18252. groupIndex < groupLength;
  18253. groupIndex++) {
  18254. // list of options for that group. (first item has the parent)
  18255. optionGroup = optionGroupsCache[groupIndex];
  18256. for(index = 1, length = optionGroup.length; index < length; index++) {
  18257. if ((optionElement = optionGroup[index].element)[0].selected) {
  18258. key = optionElement.val();
  18259. if (keyName) locals[keyName] = key;
  18260. if (trackFn) {
  18261. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  18262. locals[valueName] = collection[trackIndex];
  18263. if (trackFn(scope, locals) == key) break;
  18264. }
  18265. } else {
  18266. locals[valueName] = collection[key];
  18267. }
  18268. value.push(valueFn(scope, locals));
  18269. }
  18270. }
  18271. }
  18272. } else {
  18273. key = selectElement.val();
  18274. if (key == '?') {
  18275. value = undefined;
  18276. } else if (key === ''){
  18277. value = null;
  18278. } else {
  18279. if (trackFn) {
  18280. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  18281. locals[valueName] = collection[trackIndex];
  18282. if (trackFn(scope, locals) == key) {
  18283. value = valueFn(scope, locals);
  18284. break;
  18285. }
  18286. }
  18287. } else {
  18288. locals[valueName] = collection[key];
  18289. if (keyName) locals[keyName] = key;
  18290. value = valueFn(scope, locals);
  18291. }
  18292. }
  18293. }
  18294. ctrl.$setViewValue(value);
  18295. });
  18296. });
  18297. ctrl.$render = render;
  18298. // TODO(vojta): can't we optimize this ?
  18299. scope.$watch(render);
  18300. function render() {
  18301. // Temporary location for the option groups before we render them
  18302. var optionGroups = {'':[]},
  18303. optionGroupNames = [''],
  18304. optionGroupName,
  18305. optionGroup,
  18306. option,
  18307. existingParent, existingOptions, existingOption,
  18308. modelValue = ctrl.$modelValue,
  18309. values = valuesFn(scope) || [],
  18310. keys = keyName ? sortedKeys(values) : values,
  18311. key,
  18312. groupLength, length,
  18313. groupIndex, index,
  18314. locals = {},
  18315. selected,
  18316. selectedSet = false, // nothing is selected yet
  18317. lastElement,
  18318. element,
  18319. label;
  18320. if (multiple) {
  18321. if (trackFn && isArray(modelValue)) {
  18322. selectedSet = new HashMap([]);
  18323. for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
  18324. locals[valueName] = modelValue[trackIndex];
  18325. selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
  18326. }
  18327. } else {
  18328. selectedSet = new HashMap(modelValue);
  18329. }
  18330. }
  18331. // We now build up the list of options we need (we merge later)
  18332. for (index = 0; length = keys.length, index < length; index++) {
  18333. key = index;
  18334. if (keyName) {
  18335. key = keys[index];
  18336. if ( key.charAt(0) === '$' ) continue;
  18337. locals[keyName] = key;
  18338. }
  18339. locals[valueName] = values[key];
  18340. optionGroupName = groupByFn(scope, locals) || '';
  18341. if (!(optionGroup = optionGroups[optionGroupName])) {
  18342. optionGroup = optionGroups[optionGroupName] = [];
  18343. optionGroupNames.push(optionGroupName);
  18344. }
  18345. if (multiple) {
  18346. selected = isDefined(
  18347. selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
  18348. );
  18349. } else {
  18350. if (trackFn) {
  18351. var modelCast = {};
  18352. modelCast[valueName] = modelValue;
  18353. selected = trackFn(scope, modelCast) === trackFn(scope, locals);
  18354. } else {
  18355. selected = modelValue === valueFn(scope, locals);
  18356. }
  18357. selectedSet = selectedSet || selected; // see if at least one item is selected
  18358. }
  18359. label = displayFn(scope, locals); // what will be seen by the user
  18360. // doing displayFn(scope, locals) || '' overwrites zero values
  18361. label = isDefined(label) ? label : '';
  18362. optionGroup.push({
  18363. // either the index into array or key from object
  18364. id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
  18365. label: label,
  18366. selected: selected // determine if we should be selected
  18367. });
  18368. }
  18369. if (!multiple) {
  18370. if (nullOption || modelValue === null) {
  18371. // insert null option if we have a placeholder, or the model is null
  18372. optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
  18373. } else if (!selectedSet) {
  18374. // option could not be found, we have to insert the undefined item
  18375. optionGroups[''].unshift({id:'?', label:'', selected:true});
  18376. }
  18377. }
  18378. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  18379. for (groupIndex = 0, groupLength = optionGroupNames.length;
  18380. groupIndex < groupLength;
  18381. groupIndex++) {
  18382. // current option group name or '' if no group
  18383. optionGroupName = optionGroupNames[groupIndex];
  18384. // list of options for that group. (first item has the parent)
  18385. optionGroup = optionGroups[optionGroupName];
  18386. if (optionGroupsCache.length <= groupIndex) {
  18387. // we need to grow the optionGroups
  18388. existingParent = {
  18389. element: optGroupTemplate.clone().attr('label', optionGroupName),
  18390. label: optionGroup.label
  18391. };
  18392. existingOptions = [existingParent];
  18393. optionGroupsCache.push(existingOptions);
  18394. selectElement.append(existingParent.element);
  18395. } else {
  18396. existingOptions = optionGroupsCache[groupIndex];
  18397. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  18398. // update the OPTGROUP label if not the same.
  18399. if (existingParent.label != optionGroupName) {
  18400. existingParent.element.attr('label', existingParent.label = optionGroupName);
  18401. }
  18402. }
  18403. lastElement = null; // start at the beginning
  18404. for(index = 0, length = optionGroup.length; index < length; index++) {
  18405. option = optionGroup[index];
  18406. if ((existingOption = existingOptions[index+1])) {
  18407. // reuse elements
  18408. lastElement = existingOption.element;
  18409. if (existingOption.label !== option.label) {
  18410. lastElement.text(existingOption.label = option.label);
  18411. }
  18412. if (existingOption.id !== option.id) {
  18413. lastElement.val(existingOption.id = option.id);
  18414. }
  18415. // lastElement.prop('selected') provided by jQuery has side-effects
  18416. if (lastElement[0].selected !== option.selected) {
  18417. lastElement.prop('selected', (existingOption.selected = option.selected));
  18418. }
  18419. } else {
  18420. // grow elements
  18421. // if it's a null option
  18422. if (option.id === '' && nullOption) {
  18423. // put back the pre-compiled element
  18424. element = nullOption;
  18425. } else {
  18426. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  18427. // in this version of jQuery on some browser the .text() returns a string
  18428. // rather then the element.
  18429. (element = optionTemplate.clone())
  18430. .val(option.id)
  18431. .attr('selected', option.selected)
  18432. .text(option.label);
  18433. }
  18434. existingOptions.push(existingOption = {
  18435. element: element,
  18436. label: option.label,
  18437. id: option.id,
  18438. selected: option.selected
  18439. });
  18440. if (lastElement) {
  18441. lastElement.after(element);
  18442. } else {
  18443. existingParent.element.append(element);
  18444. }
  18445. lastElement = element;
  18446. }
  18447. }
  18448. // remove any excessive OPTIONs in a group
  18449. index++; // increment since the existingOptions[0] is parent element not OPTION
  18450. while(existingOptions.length > index) {
  18451. existingOptions.pop().element.remove();
  18452. }
  18453. }
  18454. // remove any excessive OPTGROUPs from select
  18455. while(optionGroupsCache.length > groupIndex) {
  18456. optionGroupsCache.pop()[0].element.remove();
  18457. }
  18458. }
  18459. }
  18460. }
  18461. };
  18462. }];
  18463. var optionDirective = ['$interpolate', function($interpolate) {
  18464. var nullSelectCtrl = {
  18465. addOption: noop,
  18466. removeOption: noop
  18467. };
  18468. return {
  18469. restrict: 'E',
  18470. priority: 100,
  18471. compile: function(element, attr) {
  18472. if (isUndefined(attr.value)) {
  18473. var interpolateFn = $interpolate(element.text(), true);
  18474. if (!interpolateFn) {
  18475. attr.$set('value', element.text());
  18476. }
  18477. }
  18478. return function (scope, element, attr) {
  18479. var selectCtrlName = '$selectController',
  18480. parent = element.parent(),
  18481. selectCtrl = parent.data(selectCtrlName) ||
  18482. parent.parent().data(selectCtrlName); // in case we are in optgroup
  18483. if (selectCtrl && selectCtrl.databound) {
  18484. // For some reason Opera defaults to true and if not overridden this messes up the repeater.
  18485. // We don't want the view to drive the initialization of the model anyway.
  18486. element.prop('selected', false);
  18487. } else {
  18488. selectCtrl = nullSelectCtrl;
  18489. }
  18490. if (interpolateFn) {
  18491. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  18492. attr.$set('value', newVal);
  18493. if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
  18494. selectCtrl.addOption(newVal);
  18495. });
  18496. } else {
  18497. selectCtrl.addOption(attr.value);
  18498. }
  18499. element.on('$destroy', function() {
  18500. selectCtrl.removeOption(attr.value);
  18501. });
  18502. };
  18503. }
  18504. };
  18505. }];
  18506. var styleDirective = valueFn({
  18507. restrict: 'E',
  18508. terminal: true
  18509. });
  18510. //try to bind to jquery now so that one can write angular.element().read()
  18511. //but we will rebind on bootstrap again.
  18512. bindJQuery();
  18513. publishExternalAPI(angular);
  18514. jqLite(document).ready(function() {
  18515. angularInit(document, bootstrap);
  18516. });
  18517. })(window, document);
  18518. !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-start{border-spacing:1px 1px;-ms-zoom:1.0001;}.ng-animate-active{border-spacing:0px 0px;-ms-zoom:1;}</style>');