angular.js 709 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560
  1. /**
  2. * @license AngularJS v1.2.9
  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.9/' +
  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. * It is worth nothing that `.forEach` does not iterate over inherited properties because it filters
  247. * using the `hasOwnProperty` method.
  248. *
  249. <pre>
  250. var values = {name: 'misko', gender: 'male'};
  251. var log = [];
  252. angular.forEach(values, function(value, key){
  253. this.push(key + ': ' + value);
  254. }, log);
  255. expect(log).toEqual(['name: misko', 'gender:male']);
  256. </pre>
  257. *
  258. * @param {Object|Array} obj Object to iterate over.
  259. * @param {Function} iterator Iterator function.
  260. * @param {Object=} context Object to become context (`this`) for the iterator function.
  261. * @returns {Object|Array} Reference to `obj`.
  262. */
  263. function forEach(obj, iterator, context) {
  264. var key;
  265. if (obj) {
  266. if (isFunction(obj)){
  267. for (key in obj) {
  268. // Need to check if hasOwnProperty exists,
  269. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  270. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  271. iterator.call(context, obj[key], key);
  272. }
  273. }
  274. } else if (obj.forEach && obj.forEach !== forEach) {
  275. obj.forEach(iterator, context);
  276. } else if (isArrayLike(obj)) {
  277. for (key = 0; key < obj.length; key++)
  278. iterator.call(context, obj[key], key);
  279. } else {
  280. for (key in obj) {
  281. if (obj.hasOwnProperty(key)) {
  282. iterator.call(context, obj[key], key);
  283. }
  284. }
  285. }
  286. }
  287. return obj;
  288. }
  289. function sortedKeys(obj) {
  290. var keys = [];
  291. for (var key in obj) {
  292. if (obj.hasOwnProperty(key)) {
  293. keys.push(key);
  294. }
  295. }
  296. return keys.sort();
  297. }
  298. function forEachSorted(obj, iterator, context) {
  299. var keys = sortedKeys(obj);
  300. for ( var i = 0; i < keys.length; i++) {
  301. iterator.call(context, obj[keys[i]], keys[i]);
  302. }
  303. return keys;
  304. }
  305. /**
  306. * when using forEach the params are value, key, but it is often useful to have key, value.
  307. * @param {function(string, *)} iteratorFn
  308. * @returns {function(*, string)}
  309. */
  310. function reverseParams(iteratorFn) {
  311. return function(value, key) { iteratorFn(key, value); };
  312. }
  313. /**
  314. * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
  315. * characters such as '012ABC'. The reason why we are not using simply a number counter is that
  316. * the number string gets longer over time, and it can also overflow, where as the nextId
  317. * will grow much slower, it is a string, and it will never overflow.
  318. *
  319. * @returns an unique alpha-numeric string
  320. */
  321. function nextUid() {
  322. var index = uid.length;
  323. var digit;
  324. while(index) {
  325. index--;
  326. digit = uid[index].charCodeAt(0);
  327. if (digit == 57 /*'9'*/) {
  328. uid[index] = 'A';
  329. return uid.join('');
  330. }
  331. if (digit == 90 /*'Z'*/) {
  332. uid[index] = '0';
  333. } else {
  334. uid[index] = String.fromCharCode(digit + 1);
  335. return uid.join('');
  336. }
  337. }
  338. uid.unshift('0');
  339. return uid.join('');
  340. }
  341. /**
  342. * Set or clear the hashkey for an object.
  343. * @param obj object
  344. * @param h the hashkey (!truthy to delete the hashkey)
  345. */
  346. function setHashKey(obj, h) {
  347. if (h) {
  348. obj.$$hashKey = h;
  349. }
  350. else {
  351. delete obj.$$hashKey;
  352. }
  353. }
  354. /**
  355. * @ngdoc function
  356. * @name angular.extend
  357. * @function
  358. *
  359. * @description
  360. * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
  361. * to `dst`. You can specify multiple `src` objects.
  362. *
  363. * @param {Object} dst Destination object.
  364. * @param {...Object} src Source object(s).
  365. * @returns {Object} Reference to `dst`.
  366. */
  367. function extend(dst) {
  368. var h = dst.$$hashKey;
  369. forEach(arguments, function(obj){
  370. if (obj !== dst) {
  371. forEach(obj, function(value, key){
  372. dst[key] = value;
  373. });
  374. }
  375. });
  376. setHashKey(dst,h);
  377. return dst;
  378. }
  379. function int(str) {
  380. return parseInt(str, 10);
  381. }
  382. function inherit(parent, extra) {
  383. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  384. }
  385. /**
  386. * @ngdoc function
  387. * @name angular.noop
  388. * @function
  389. *
  390. * @description
  391. * A function that performs no operations. This function can be useful when writing code in the
  392. * functional style.
  393. <pre>
  394. function foo(callback) {
  395. var result = calculateResult();
  396. (callback || angular.noop)(result);
  397. }
  398. </pre>
  399. */
  400. function noop() {}
  401. noop.$inject = [];
  402. /**
  403. * @ngdoc function
  404. * @name angular.identity
  405. * @function
  406. *
  407. * @description
  408. * A function that returns its first argument. This function is useful when writing code in the
  409. * functional style.
  410. *
  411. <pre>
  412. function transformer(transformationFn, value) {
  413. return (transformationFn || angular.identity)(value);
  414. };
  415. </pre>
  416. */
  417. function identity($) {return $;}
  418. identity.$inject = [];
  419. function valueFn(value) {return function() {return value;};}
  420. /**
  421. * @ngdoc function
  422. * @name angular.isUndefined
  423. * @function
  424. *
  425. * @description
  426. * Determines if a reference is undefined.
  427. *
  428. * @param {*} value Reference to check.
  429. * @returns {boolean} True if `value` is undefined.
  430. */
  431. function isUndefined(value){return typeof value === 'undefined';}
  432. /**
  433. * @ngdoc function
  434. * @name angular.isDefined
  435. * @function
  436. *
  437. * @description
  438. * Determines if a reference is defined.
  439. *
  440. * @param {*} value Reference to check.
  441. * @returns {boolean} True if `value` is defined.
  442. */
  443. function isDefined(value){return typeof value !== 'undefined';}
  444. /**
  445. * @ngdoc function
  446. * @name angular.isObject
  447. * @function
  448. *
  449. * @description
  450. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  451. * considered to be objects.
  452. *
  453. * @param {*} value Reference to check.
  454. * @returns {boolean} True if `value` is an `Object` but not `null`.
  455. */
  456. function isObject(value){return value != null && typeof value === 'object';}
  457. /**
  458. * @ngdoc function
  459. * @name angular.isString
  460. * @function
  461. *
  462. * @description
  463. * Determines if a reference is a `String`.
  464. *
  465. * @param {*} value Reference to check.
  466. * @returns {boolean} True if `value` is a `String`.
  467. */
  468. function isString(value){return typeof value === 'string';}
  469. /**
  470. * @ngdoc function
  471. * @name angular.isNumber
  472. * @function
  473. *
  474. * @description
  475. * Determines if a reference is a `Number`.
  476. *
  477. * @param {*} value Reference to check.
  478. * @returns {boolean} True if `value` is a `Number`.
  479. */
  480. function isNumber(value){return typeof value === 'number';}
  481. /**
  482. * @ngdoc function
  483. * @name angular.isDate
  484. * @function
  485. *
  486. * @description
  487. * Determines if a value is a date.
  488. *
  489. * @param {*} value Reference to check.
  490. * @returns {boolean} True if `value` is a `Date`.
  491. */
  492. function isDate(value){
  493. return toString.call(value) === '[object Date]';
  494. }
  495. /**
  496. * @ngdoc function
  497. * @name angular.isArray
  498. * @function
  499. *
  500. * @description
  501. * Determines if a reference is an `Array`.
  502. *
  503. * @param {*} value Reference to check.
  504. * @returns {boolean} True if `value` is an `Array`.
  505. */
  506. function isArray(value) {
  507. return toString.call(value) === '[object Array]';
  508. }
  509. /**
  510. * @ngdoc function
  511. * @name angular.isFunction
  512. * @function
  513. *
  514. * @description
  515. * Determines if a reference is a `Function`.
  516. *
  517. * @param {*} value Reference to check.
  518. * @returns {boolean} True if `value` is a `Function`.
  519. */
  520. function isFunction(value){return typeof value === 'function';}
  521. /**
  522. * Determines if a value is a regular expression object.
  523. *
  524. * @private
  525. * @param {*} value Reference to check.
  526. * @returns {boolean} True if `value` is a `RegExp`.
  527. */
  528. function isRegExp(value) {
  529. return toString.call(value) === '[object RegExp]';
  530. }
  531. /**
  532. * Checks if `obj` is a window object.
  533. *
  534. * @private
  535. * @param {*} obj Object to check
  536. * @returns {boolean} True if `obj` is a window obj.
  537. */
  538. function isWindow(obj) {
  539. return obj && obj.document && obj.location && obj.alert && obj.setInterval;
  540. }
  541. function isScope(obj) {
  542. return obj && obj.$evalAsync && obj.$watch;
  543. }
  544. function isFile(obj) {
  545. return toString.call(obj) === '[object File]';
  546. }
  547. function isBoolean(value) {
  548. return typeof value === 'boolean';
  549. }
  550. var trim = (function() {
  551. // native trim is way faster: http://jsperf.com/angular-trim-test
  552. // but IE doesn't have it... :-(
  553. // TODO: we should move this into IE/ES5 polyfill
  554. if (!String.prototype.trim) {
  555. return function(value) {
  556. return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
  557. };
  558. }
  559. return function(value) {
  560. return isString(value) ? value.trim() : value;
  561. };
  562. })();
  563. /**
  564. * @ngdoc function
  565. * @name angular.isElement
  566. * @function
  567. *
  568. * @description
  569. * Determines if a reference is a DOM element (or wrapped jQuery element).
  570. *
  571. * @param {*} value Reference to check.
  572. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  573. */
  574. function isElement(node) {
  575. return !!(node &&
  576. (node.nodeName // we are a direct element
  577. || (node.on && node.find))); // we have an on and find method part of jQuery API
  578. }
  579. /**
  580. * @param str 'key1,key2,...'
  581. * @returns {object} in the form of {key1:true, key2:true, ...}
  582. */
  583. function makeMap(str){
  584. var obj = {}, items = str.split(","), i;
  585. for ( i = 0; i < items.length; i++ )
  586. obj[ items[i] ] = true;
  587. return obj;
  588. }
  589. if (msie < 9) {
  590. nodeName_ = function(element) {
  591. element = element.nodeName ? element : element[0];
  592. return (element.scopeName && element.scopeName != 'HTML')
  593. ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
  594. };
  595. } else {
  596. nodeName_ = function(element) {
  597. return element.nodeName ? element.nodeName : element[0].nodeName;
  598. };
  599. }
  600. function map(obj, iterator, context) {
  601. var results = [];
  602. forEach(obj, function(value, index, list) {
  603. results.push(iterator.call(context, value, index, list));
  604. });
  605. return results;
  606. }
  607. /**
  608. * @description
  609. * Determines the number of elements in an array, the number of properties an object has, or
  610. * the length of a string.
  611. *
  612. * Note: This function is used to augment the Object type in Angular expressions. See
  613. * {@link angular.Object} for more information about Angular arrays.
  614. *
  615. * @param {Object|Array|string} obj Object, array, or string to inspect.
  616. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
  617. * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
  618. */
  619. function size(obj, ownPropsOnly) {
  620. var count = 0, key;
  621. if (isArray(obj) || isString(obj)) {
  622. return obj.length;
  623. } else if (isObject(obj)){
  624. for (key in obj)
  625. if (!ownPropsOnly || obj.hasOwnProperty(key))
  626. count++;
  627. }
  628. return count;
  629. }
  630. function includes(array, obj) {
  631. return indexOf(array, obj) != -1;
  632. }
  633. function indexOf(array, obj) {
  634. if (array.indexOf) return array.indexOf(obj);
  635. for (var i = 0; i < array.length; i++) {
  636. if (obj === array[i]) return i;
  637. }
  638. return -1;
  639. }
  640. function arrayRemove(array, value) {
  641. var index = indexOf(array, value);
  642. if (index >=0)
  643. array.splice(index, 1);
  644. return value;
  645. }
  646. function isLeafNode (node) {
  647. if (node) {
  648. switch (node.nodeName) {
  649. case "OPTION":
  650. case "PRE":
  651. case "TITLE":
  652. return true;
  653. }
  654. }
  655. return false;
  656. }
  657. /**
  658. * @ngdoc function
  659. * @name angular.copy
  660. * @function
  661. *
  662. * @description
  663. * Creates a deep copy of `source`, which should be an object or an array.
  664. *
  665. * * If no destination is supplied, a copy of the object or array is created.
  666. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  667. * are deleted and then all elements/properties from the source are copied to it.
  668. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  669. * * If `source` is identical to 'destination' an exception will be thrown.
  670. *
  671. * @param {*} source The source that will be used to make a copy.
  672. * Can be any type, including primitives, `null`, and `undefined`.
  673. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  674. * provided, must be of the same type as `source`.
  675. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  676. *
  677. * @example
  678. <doc:example>
  679. <doc:source>
  680. <div ng-controller="Controller">
  681. <form novalidate class="simple-form">
  682. Name: <input type="text" ng-model="user.name" /><br />
  683. E-mail: <input type="email" ng-model="user.email" /><br />
  684. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  685. <input type="radio" ng-model="user.gender" value="female" />female<br />
  686. <button ng-click="reset()">RESET</button>
  687. <button ng-click="update(user)">SAVE</button>
  688. </form>
  689. <pre>form = {{user | json}}</pre>
  690. <pre>master = {{master | json}}</pre>
  691. </div>
  692. <script>
  693. function Controller($scope) {
  694. $scope.master= {};
  695. $scope.update = function(user) {
  696. // Example with 1 argument
  697. $scope.master= angular.copy(user);
  698. };
  699. $scope.reset = function() {
  700. // Example with 2 arguments
  701. angular.copy($scope.master, $scope.user);
  702. };
  703. $scope.reset();
  704. }
  705. </script>
  706. </doc:source>
  707. </doc:example>
  708. */
  709. function copy(source, destination){
  710. if (isWindow(source) || isScope(source)) {
  711. throw ngMinErr('cpws',
  712. "Can't copy! Making copies of Window or Scope instances is not supported.");
  713. }
  714. if (!destination) {
  715. destination = source;
  716. if (source) {
  717. if (isArray(source)) {
  718. destination = copy(source, []);
  719. } else if (isDate(source)) {
  720. destination = new Date(source.getTime());
  721. } else if (isRegExp(source)) {
  722. destination = new RegExp(source.source);
  723. } else if (isObject(source)) {
  724. destination = copy(source, {});
  725. }
  726. }
  727. } else {
  728. if (source === destination) throw ngMinErr('cpi',
  729. "Can't copy! Source and destination are identical.");
  730. if (isArray(source)) {
  731. destination.length = 0;
  732. for ( var i = 0; i < source.length; i++) {
  733. destination.push(copy(source[i]));
  734. }
  735. } else {
  736. var h = destination.$$hashKey;
  737. forEach(destination, function(value, key){
  738. delete destination[key];
  739. });
  740. for ( var key in source) {
  741. destination[key] = copy(source[key]);
  742. }
  743. setHashKey(destination,h);
  744. }
  745. }
  746. return destination;
  747. }
  748. /**
  749. * Create a shallow copy of an object
  750. */
  751. function shallowCopy(src, dst) {
  752. dst = dst || {};
  753. for(var key in src) {
  754. // shallowCopy is only ever called by $compile nodeLinkFn, which has control over src
  755. // so we don't need to worry about using our custom hasOwnProperty here
  756. if (src.hasOwnProperty(key) && key.charAt(0) !== '$' && key.charAt(1) !== '$') {
  757. dst[key] = src[key];
  758. }
  759. }
  760. return dst;
  761. }
  762. /**
  763. * @ngdoc function
  764. * @name angular.equals
  765. * @function
  766. *
  767. * @description
  768. * Determines if two objects or two values are equivalent. Supports value types, regular
  769. * expressions, arrays and objects.
  770. *
  771. * Two objects or values are considered equivalent if at least one of the following is true:
  772. *
  773. * * Both objects or values pass `===` comparison.
  774. * * Both objects or values are of the same type and all of their properties are equal by
  775. * comparing them with `angular.equals`.
  776. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  777. * * Both values represent the same regular expression (In JavasScript,
  778. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  779. * representation matches).
  780. *
  781. * During a property comparison, properties of `function` type and properties with names
  782. * that begin with `$` are ignored.
  783. *
  784. * Scope and DOMWindow objects are being compared only by identify (`===`).
  785. *
  786. * @param {*} o1 Object or value to compare.
  787. * @param {*} o2 Object or value to compare.
  788. * @returns {boolean} True if arguments are equal.
  789. */
  790. function equals(o1, o2) {
  791. if (o1 === o2) return true;
  792. if (o1 === null || o2 === null) return false;
  793. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  794. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  795. if (t1 == t2) {
  796. if (t1 == 'object') {
  797. if (isArray(o1)) {
  798. if (!isArray(o2)) return false;
  799. if ((length = o1.length) == o2.length) {
  800. for(key=0; key<length; key++) {
  801. if (!equals(o1[key], o2[key])) return false;
  802. }
  803. return true;
  804. }
  805. } else if (isDate(o1)) {
  806. return isDate(o2) && o1.getTime() == o2.getTime();
  807. } else if (isRegExp(o1) && isRegExp(o2)) {
  808. return o1.toString() == o2.toString();
  809. } else {
  810. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  811. keySet = {};
  812. for(key in o1) {
  813. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  814. if (!equals(o1[key], o2[key])) return false;
  815. keySet[key] = true;
  816. }
  817. for(key in o2) {
  818. if (!keySet.hasOwnProperty(key) &&
  819. key.charAt(0) !== '$' &&
  820. o2[key] !== undefined &&
  821. !isFunction(o2[key])) return false;
  822. }
  823. return true;
  824. }
  825. }
  826. }
  827. return false;
  828. }
  829. function csp() {
  830. return (document.securityPolicy && document.securityPolicy.isActive) ||
  831. (document.querySelector &&
  832. !!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]')));
  833. }
  834. function concat(array1, array2, index) {
  835. return array1.concat(slice.call(array2, index));
  836. }
  837. function sliceArgs(args, startIndex) {
  838. return slice.call(args, startIndex || 0);
  839. }
  840. /* jshint -W101 */
  841. /**
  842. * @ngdoc function
  843. * @name angular.bind
  844. * @function
  845. *
  846. * @description
  847. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  848. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  849. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  850. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  851. *
  852. * @param {Object} self Context which `fn` should be evaluated in.
  853. * @param {function()} fn Function to be bound.
  854. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  855. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  856. */
  857. /* jshint +W101 */
  858. function bind(self, fn) {
  859. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  860. if (isFunction(fn) && !(fn instanceof RegExp)) {
  861. return curryArgs.length
  862. ? function() {
  863. return arguments.length
  864. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  865. : fn.apply(self, curryArgs);
  866. }
  867. : function() {
  868. return arguments.length
  869. ? fn.apply(self, arguments)
  870. : fn.call(self);
  871. };
  872. } else {
  873. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  874. return fn;
  875. }
  876. }
  877. function toJsonReplacer(key, value) {
  878. var val = value;
  879. if (typeof key === 'string' && key.charAt(0) === '$') {
  880. val = undefined;
  881. } else if (isWindow(value)) {
  882. val = '$WINDOW';
  883. } else if (value && document === value) {
  884. val = '$DOCUMENT';
  885. } else if (isScope(value)) {
  886. val = '$SCOPE';
  887. }
  888. return val;
  889. }
  890. /**
  891. * @ngdoc function
  892. * @name angular.toJson
  893. * @function
  894. *
  895. * @description
  896. * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
  897. * stripped since angular uses this notation internally.
  898. *
  899. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  900. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  901. * @returns {string|undefined} JSON-ified string representing `obj`.
  902. */
  903. function toJson(obj, pretty) {
  904. if (typeof obj === 'undefined') return undefined;
  905. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  906. }
  907. /**
  908. * @ngdoc function
  909. * @name angular.fromJson
  910. * @function
  911. *
  912. * @description
  913. * Deserializes a JSON string.
  914. *
  915. * @param {string} json JSON string to deserialize.
  916. * @returns {Object|Array|Date|string|number} Deserialized thingy.
  917. */
  918. function fromJson(json) {
  919. return isString(json)
  920. ? JSON.parse(json)
  921. : json;
  922. }
  923. function toBoolean(value) {
  924. if (typeof value === 'function') {
  925. value = true;
  926. } else if (value && value.length !== 0) {
  927. var v = lowercase("" + value);
  928. value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
  929. } else {
  930. value = false;
  931. }
  932. return value;
  933. }
  934. /**
  935. * @returns {string} Returns the string representation of the element.
  936. */
  937. function startingTag(element) {
  938. element = jqLite(element).clone();
  939. try {
  940. // turns out IE does not let you set .html() on elements which
  941. // are not allowed to have children. So we just ignore it.
  942. element.empty();
  943. } catch(e) {}
  944. // As Per DOM Standards
  945. var TEXT_NODE = 3;
  946. var elemHtml = jqLite('<div>').append(element).html();
  947. try {
  948. return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
  949. elemHtml.
  950. match(/^(<[^>]+>)/)[1].
  951. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  952. } catch(e) {
  953. return lowercase(elemHtml);
  954. }
  955. }
  956. /////////////////////////////////////////////////
  957. /**
  958. * Tries to decode the URI component without throwing an exception.
  959. *
  960. * @private
  961. * @param str value potential URI component to check.
  962. * @returns {boolean} True if `value` can be decoded
  963. * with the decodeURIComponent function.
  964. */
  965. function tryDecodeURIComponent(value) {
  966. try {
  967. return decodeURIComponent(value);
  968. } catch(e) {
  969. // Ignore any invalid uri component
  970. }
  971. }
  972. /**
  973. * Parses an escaped url query string into key-value pairs.
  974. * @returns Object.<(string|boolean)>
  975. */
  976. function parseKeyValue(/**string*/keyValue) {
  977. var obj = {}, key_value, key;
  978. forEach((keyValue || "").split('&'), function(keyValue){
  979. if ( keyValue ) {
  980. key_value = keyValue.split('=');
  981. key = tryDecodeURIComponent(key_value[0]);
  982. if ( isDefined(key) ) {
  983. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  984. if (!obj[key]) {
  985. obj[key] = val;
  986. } else if(isArray(obj[key])) {
  987. obj[key].push(val);
  988. } else {
  989. obj[key] = [obj[key],val];
  990. }
  991. }
  992. }
  993. });
  994. return obj;
  995. }
  996. function toKeyValue(obj) {
  997. var parts = [];
  998. forEach(obj, function(value, key) {
  999. if (isArray(value)) {
  1000. forEach(value, function(arrayValue) {
  1001. parts.push(encodeUriQuery(key, true) +
  1002. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1003. });
  1004. } else {
  1005. parts.push(encodeUriQuery(key, true) +
  1006. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1007. }
  1008. });
  1009. return parts.length ? parts.join('&') : '';
  1010. }
  1011. /**
  1012. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1013. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1014. * segments:
  1015. * segment = *pchar
  1016. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1017. * pct-encoded = "%" HEXDIG HEXDIG
  1018. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1019. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1020. * / "*" / "+" / "," / ";" / "="
  1021. */
  1022. function encodeUriSegment(val) {
  1023. return encodeUriQuery(val, true).
  1024. replace(/%26/gi, '&').
  1025. replace(/%3D/gi, '=').
  1026. replace(/%2B/gi, '+');
  1027. }
  1028. /**
  1029. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1030. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1031. * encoded per http://tools.ietf.org/html/rfc3986:
  1032. * query = *( pchar / "/" / "?" )
  1033. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1034. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1035. * pct-encoded = "%" HEXDIG HEXDIG
  1036. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1037. * / "*" / "+" / "," / ";" / "="
  1038. */
  1039. function encodeUriQuery(val, pctEncodeSpaces) {
  1040. return encodeURIComponent(val).
  1041. replace(/%40/gi, '@').
  1042. replace(/%3A/gi, ':').
  1043. replace(/%24/g, '$').
  1044. replace(/%2C/gi, ',').
  1045. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1046. }
  1047. /**
  1048. * @ngdoc directive
  1049. * @name ng.directive:ngApp
  1050. *
  1051. * @element ANY
  1052. * @param {angular.Module} ngApp an optional application
  1053. * {@link angular.module module} name to load.
  1054. *
  1055. * @description
  1056. *
  1057. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1058. * designates the **root element** of the application and is typically placed near the root element
  1059. * of the page - e.g. on the `<body>` or `<html>` tags.
  1060. *
  1061. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1062. * found in the document will be used to define the root element to auto-bootstrap as an
  1063. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1064. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1065. *
  1066. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1067. * module will be loaded into the {@link AUTO.$injector} when the application is bootstrapped and
  1068. * should contain the application code needed or have dependencies on other modules that will
  1069. * contain the code. See {@link angular.module} for more information.
  1070. *
  1071. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1072. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1073. * would not be resolved to `3`.
  1074. *
  1075. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1076. *
  1077. <example module="ngAppDemo">
  1078. <file name="index.html">
  1079. <div ng-controller="ngAppDemoController">
  1080. I can add: {{a}} + {{b}} = {{ a+b }}
  1081. </file>
  1082. <file name="script.js">
  1083. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1084. $scope.a = 1;
  1085. $scope.b = 2;
  1086. });
  1087. </file>
  1088. </example>
  1089. *
  1090. */
  1091. function angularInit(element, bootstrap) {
  1092. var elements = [element],
  1093. appElement,
  1094. module,
  1095. names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
  1096. NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
  1097. function append(element) {
  1098. element && elements.push(element);
  1099. }
  1100. forEach(names, function(name) {
  1101. names[name] = true;
  1102. append(document.getElementById(name));
  1103. name = name.replace(':', '\\:');
  1104. if (element.querySelectorAll) {
  1105. forEach(element.querySelectorAll('.' + name), append);
  1106. forEach(element.querySelectorAll('.' + name + '\\:'), append);
  1107. forEach(element.querySelectorAll('[' + name + ']'), append);
  1108. }
  1109. });
  1110. forEach(elements, function(element) {
  1111. if (!appElement) {
  1112. var className = ' ' + element.className + ' ';
  1113. var match = NG_APP_CLASS_REGEXP.exec(className);
  1114. if (match) {
  1115. appElement = element;
  1116. module = (match[2] || '').replace(/\s+/g, ',');
  1117. } else {
  1118. forEach(element.attributes, function(attr) {
  1119. if (!appElement && names[attr.name]) {
  1120. appElement = element;
  1121. module = attr.value;
  1122. }
  1123. });
  1124. }
  1125. }
  1126. });
  1127. if (appElement) {
  1128. bootstrap(appElement, module ? [module] : []);
  1129. }
  1130. }
  1131. /**
  1132. * @ngdoc function
  1133. * @name angular.bootstrap
  1134. * @description
  1135. * Use this function to manually start up angular application.
  1136. *
  1137. * See: {@link guide/bootstrap Bootstrap}
  1138. *
  1139. * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
  1140. * They must use {@link api/ng.directive:ngApp ngApp}.
  1141. *
  1142. * @param {Element} element DOM element which is the root of angular application.
  1143. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1144. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1145. * function that will be invoked by the injector as a run block.
  1146. * See: {@link angular.module modules}
  1147. * @returns {AUTO.$injector} Returns the newly created injector for this app.
  1148. */
  1149. function bootstrap(element, modules) {
  1150. var doBootstrap = function() {
  1151. element = jqLite(element);
  1152. if (element.injector()) {
  1153. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1154. throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
  1155. }
  1156. modules = modules || [];
  1157. modules.unshift(['$provide', function($provide) {
  1158. $provide.value('$rootElement', element);
  1159. }]);
  1160. modules.unshift('ng');
  1161. var injector = createInjector(modules);
  1162. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
  1163. function(scope, element, compile, injector, animate) {
  1164. scope.$apply(function() {
  1165. element.data('$injector', injector);
  1166. compile(element)(scope);
  1167. });
  1168. }]
  1169. );
  1170. return injector;
  1171. };
  1172. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1173. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1174. return doBootstrap();
  1175. }
  1176. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1177. angular.resumeBootstrap = function(extraModules) {
  1178. forEach(extraModules, function(module) {
  1179. modules.push(module);
  1180. });
  1181. doBootstrap();
  1182. };
  1183. }
  1184. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1185. function snake_case(name, separator){
  1186. separator = separator || '_';
  1187. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1188. return (pos ? separator : '') + letter.toLowerCase();
  1189. });
  1190. }
  1191. function bindJQuery() {
  1192. // bind to jQuery if present;
  1193. jQuery = window.jQuery;
  1194. // reset to jQuery or default to us.
  1195. if (jQuery) {
  1196. jqLite = jQuery;
  1197. extend(jQuery.fn, {
  1198. scope: JQLitePrototype.scope,
  1199. isolateScope: JQLitePrototype.isolateScope,
  1200. controller: JQLitePrototype.controller,
  1201. injector: JQLitePrototype.injector,
  1202. inheritedData: JQLitePrototype.inheritedData
  1203. });
  1204. // Method signature:
  1205. // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
  1206. jqLitePatchJQueryRemove('remove', true, true, false);
  1207. jqLitePatchJQueryRemove('empty', false, false, false);
  1208. jqLitePatchJQueryRemove('html', false, false, true);
  1209. } else {
  1210. jqLite = JQLite;
  1211. }
  1212. angular.element = jqLite;
  1213. }
  1214. /**
  1215. * throw error if the argument is falsy.
  1216. */
  1217. function assertArg(arg, name, reason) {
  1218. if (!arg) {
  1219. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1220. }
  1221. return arg;
  1222. }
  1223. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1224. if (acceptArrayAnnotation && isArray(arg)) {
  1225. arg = arg[arg.length - 1];
  1226. }
  1227. assertArg(isFunction(arg), name, 'not a function, got ' +
  1228. (arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1229. return arg;
  1230. }
  1231. /**
  1232. * throw error if the name given is hasOwnProperty
  1233. * @param {String} name the name to test
  1234. * @param {String} context the context in which the name is used, such as module or directive
  1235. */
  1236. function assertNotHasOwnProperty(name, context) {
  1237. if (name === 'hasOwnProperty') {
  1238. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1239. }
  1240. }
  1241. /**
  1242. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1243. * @param {Object} obj starting object
  1244. * @param {string} path path to traverse
  1245. * @param {boolean=true} bindFnToScope
  1246. * @returns value as accessible by path
  1247. */
  1248. //TODO(misko): this function needs to be removed
  1249. function getter(obj, path, bindFnToScope) {
  1250. if (!path) return obj;
  1251. var keys = path.split('.');
  1252. var key;
  1253. var lastInstance = obj;
  1254. var len = keys.length;
  1255. for (var i = 0; i < len; i++) {
  1256. key = keys[i];
  1257. if (obj) {
  1258. obj = (lastInstance = obj)[key];
  1259. }
  1260. }
  1261. if (!bindFnToScope && isFunction(obj)) {
  1262. return bind(lastInstance, obj);
  1263. }
  1264. return obj;
  1265. }
  1266. /**
  1267. * Return the DOM siblings between the first and last node in the given array.
  1268. * @param {Array} array like object
  1269. * @returns jQlite object containing the elements
  1270. */
  1271. function getBlockElements(nodes) {
  1272. var startNode = nodes[0],
  1273. endNode = nodes[nodes.length - 1];
  1274. if (startNode === endNode) {
  1275. return jqLite(startNode);
  1276. }
  1277. var element = startNode;
  1278. var elements = [element];
  1279. do {
  1280. element = element.nextSibling;
  1281. if (!element) break;
  1282. elements.push(element);
  1283. } while (element !== endNode);
  1284. return jqLite(elements);
  1285. }
  1286. /**
  1287. * @ngdoc interface
  1288. * @name angular.Module
  1289. * @description
  1290. *
  1291. * Interface for configuring angular {@link angular.module modules}.
  1292. */
  1293. function setupModuleLoader(window) {
  1294. var $injectorMinErr = minErr('$injector');
  1295. var ngMinErr = minErr('ng');
  1296. function ensure(obj, name, factory) {
  1297. return obj[name] || (obj[name] = factory());
  1298. }
  1299. var angular = ensure(window, 'angular', Object);
  1300. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1301. angular.$$minErr = angular.$$minErr || minErr;
  1302. return ensure(angular, 'module', function() {
  1303. /** @type {Object.<string, angular.Module>} */
  1304. var modules = {};
  1305. /**
  1306. * @ngdoc function
  1307. * @name angular.module
  1308. * @description
  1309. *
  1310. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1311. * modules.
  1312. * All modules (angular core or 3rd party) that should be available to an application must be
  1313. * registered using this mechanism.
  1314. *
  1315. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1316. * existing module (the name passed as the first argument to `module`) is retrieved.
  1317. *
  1318. *
  1319. * # Module
  1320. *
  1321. * A module is a collection of services, directives, filters, and configuration information.
  1322. * `angular.module` is used to configure the {@link AUTO.$injector $injector}.
  1323. *
  1324. * <pre>
  1325. * // Create a new module
  1326. * var myModule = angular.module('myModule', []);
  1327. *
  1328. * // register a new service
  1329. * myModule.value('appName', 'MyCoolApp');
  1330. *
  1331. * // configure existing services inside initialization blocks.
  1332. * myModule.config(function($locationProvider) {
  1333. * // Configure existing providers
  1334. * $locationProvider.hashPrefix('!');
  1335. * });
  1336. * </pre>
  1337. *
  1338. * Then you can create an injector and load your modules like this:
  1339. *
  1340. * <pre>
  1341. * var injector = angular.injector(['ng', 'MyModule'])
  1342. * </pre>
  1343. *
  1344. * However it's more likely that you'll just use
  1345. * {@link ng.directive:ngApp ngApp} or
  1346. * {@link angular.bootstrap} to simplify this process for you.
  1347. *
  1348. * @param {!string} name The name of the module to create or retrieve.
  1349. * @param {Array.<string>=} requires If specified then new module is being created. If
  1350. * unspecified then the the module is being retrieved for further configuration.
  1351. * @param {Function} configFn Optional configuration function for the module. Same as
  1352. * {@link angular.Module#methods_config Module#config()}.
  1353. * @returns {module} new module with the {@link angular.Module} api.
  1354. */
  1355. return function module(name, requires, configFn) {
  1356. var assertNotHasOwnProperty = function(name, context) {
  1357. if (name === 'hasOwnProperty') {
  1358. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1359. }
  1360. };
  1361. assertNotHasOwnProperty(name, 'module');
  1362. if (requires && modules.hasOwnProperty(name)) {
  1363. modules[name] = null;
  1364. }
  1365. return ensure(modules, name, function() {
  1366. if (!requires) {
  1367. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1368. "the module name or forgot to load it. If registering a module ensure that you " +
  1369. "specify the dependencies as the second argument.", name);
  1370. }
  1371. /** @type {!Array.<Array.<*>>} */
  1372. var invokeQueue = [];
  1373. /** @type {!Array.<Function>} */
  1374. var runBlocks = [];
  1375. var config = invokeLater('$injector', 'invoke');
  1376. /** @type {angular.Module} */
  1377. var moduleInstance = {
  1378. // Private state
  1379. _invokeQueue: invokeQueue,
  1380. _runBlocks: runBlocks,
  1381. /**
  1382. * @ngdoc property
  1383. * @name angular.Module#requires
  1384. * @propertyOf angular.Module
  1385. * @returns {Array.<string>} List of module names which must be loaded before this module.
  1386. * @description
  1387. * Holds the list of modules which the injector will load before the current module is
  1388. * loaded.
  1389. */
  1390. requires: requires,
  1391. /**
  1392. * @ngdoc property
  1393. * @name angular.Module#name
  1394. * @propertyOf angular.Module
  1395. * @returns {string} Name of the module.
  1396. * @description
  1397. */
  1398. name: name,
  1399. /**
  1400. * @ngdoc method
  1401. * @name angular.Module#provider
  1402. * @methodOf angular.Module
  1403. * @param {string} name service name
  1404. * @param {Function} providerType Construction function for creating new instance of the
  1405. * service.
  1406. * @description
  1407. * See {@link AUTO.$provide#provider $provide.provider()}.
  1408. */
  1409. provider: invokeLater('$provide', 'provider'),
  1410. /**
  1411. * @ngdoc method
  1412. * @name angular.Module#factory
  1413. * @methodOf angular.Module
  1414. * @param {string} name service name
  1415. * @param {Function} providerFunction Function for creating new instance of the service.
  1416. * @description
  1417. * See {@link AUTO.$provide#factory $provide.factory()}.
  1418. */
  1419. factory: invokeLater('$provide', 'factory'),
  1420. /**
  1421. * @ngdoc method
  1422. * @name angular.Module#service
  1423. * @methodOf angular.Module
  1424. * @param {string} name service name
  1425. * @param {Function} constructor A constructor function that will be instantiated.
  1426. * @description
  1427. * See {@link AUTO.$provide#service $provide.service()}.
  1428. */
  1429. service: invokeLater('$provide', 'service'),
  1430. /**
  1431. * @ngdoc method
  1432. * @name angular.Module#value
  1433. * @methodOf angular.Module
  1434. * @param {string} name service name
  1435. * @param {*} object Service instance object.
  1436. * @description
  1437. * See {@link AUTO.$provide#value $provide.value()}.
  1438. */
  1439. value: invokeLater('$provide', 'value'),
  1440. /**
  1441. * @ngdoc method
  1442. * @name angular.Module#constant
  1443. * @methodOf angular.Module
  1444. * @param {string} name constant name
  1445. * @param {*} object Constant value.
  1446. * @description
  1447. * Because the constant are fixed, they get applied before other provide methods.
  1448. * See {@link AUTO.$provide#constant $provide.constant()}.
  1449. */
  1450. constant: invokeLater('$provide', 'constant', 'unshift'),
  1451. /**
  1452. * @ngdoc method
  1453. * @name angular.Module#animation
  1454. * @methodOf angular.Module
  1455. * @param {string} name animation name
  1456. * @param {Function} animationFactory Factory function for creating new instance of an
  1457. * animation.
  1458. * @description
  1459. *
  1460. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1461. *
  1462. *
  1463. * Defines an animation hook that can be later used with
  1464. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1465. *
  1466. * <pre>
  1467. * module.animation('.animation-name', function($inject1, $inject2) {
  1468. * return {
  1469. * eventName : function(element, done) {
  1470. * //code to run the animation
  1471. * //once complete, then run done()
  1472. * return function cancellationFunction(element) {
  1473. * //code to cancel the animation
  1474. * }
  1475. * }
  1476. * }
  1477. * })
  1478. * </pre>
  1479. *
  1480. * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
  1481. * {@link ngAnimate ngAnimate module} for more information.
  1482. */
  1483. animation: invokeLater('$animateProvider', 'register'),
  1484. /**
  1485. * @ngdoc method
  1486. * @name angular.Module#filter
  1487. * @methodOf angular.Module
  1488. * @param {string} name Filter name.
  1489. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1490. * @description
  1491. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1492. */
  1493. filter: invokeLater('$filterProvider', 'register'),
  1494. /**
  1495. * @ngdoc method
  1496. * @name angular.Module#controller
  1497. * @methodOf angular.Module
  1498. * @param {string|Object} name Controller name, or an object map of controllers where the
  1499. * keys are the names and the values are the constructors.
  1500. * @param {Function} constructor Controller constructor function.
  1501. * @description
  1502. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1503. */
  1504. controller: invokeLater('$controllerProvider', 'register'),
  1505. /**
  1506. * @ngdoc method
  1507. * @name angular.Module#directive
  1508. * @methodOf angular.Module
  1509. * @param {string|Object} name Directive name, or an object map of directives where the
  1510. * keys are the names and the values are the factories.
  1511. * @param {Function} directiveFactory Factory function for creating new instance of
  1512. * directives.
  1513. * @description
  1514. * See {@link ng.$compileProvider#methods_directive $compileProvider.directive()}.
  1515. */
  1516. directive: invokeLater('$compileProvider', 'directive'),
  1517. /**
  1518. * @ngdoc method
  1519. * @name angular.Module#config
  1520. * @methodOf angular.Module
  1521. * @param {Function} configFn Execute this function on module load. Useful for service
  1522. * configuration.
  1523. * @description
  1524. * Use this method to register work which needs to be performed on module loading.
  1525. */
  1526. config: config,
  1527. /**
  1528. * @ngdoc method
  1529. * @name angular.Module#run
  1530. * @methodOf angular.Module
  1531. * @param {Function} initializationFn Execute this function after injector creation.
  1532. * Useful for application initialization.
  1533. * @description
  1534. * Use this method to register work which should be performed when the injector is done
  1535. * loading all modules.
  1536. */
  1537. run: function(block) {
  1538. runBlocks.push(block);
  1539. return this;
  1540. }
  1541. };
  1542. if (configFn) {
  1543. config(configFn);
  1544. }
  1545. return moduleInstance;
  1546. /**
  1547. * @param {string} provider
  1548. * @param {string} method
  1549. * @param {String=} insertMethod
  1550. * @returns {angular.Module}
  1551. */
  1552. function invokeLater(provider, method, insertMethod) {
  1553. return function() {
  1554. invokeQueue[insertMethod || 'push']([provider, method, arguments]);
  1555. return moduleInstance;
  1556. };
  1557. }
  1558. });
  1559. };
  1560. });
  1561. }
  1562. /* global
  1563. angularModule: true,
  1564. version: true,
  1565. $LocaleProvider,
  1566. $CompileProvider,
  1567. htmlAnchorDirective,
  1568. inputDirective,
  1569. inputDirective,
  1570. formDirective,
  1571. scriptDirective,
  1572. selectDirective,
  1573. styleDirective,
  1574. optionDirective,
  1575. ngBindDirective,
  1576. ngBindHtmlDirective,
  1577. ngBindTemplateDirective,
  1578. ngClassDirective,
  1579. ngClassEvenDirective,
  1580. ngClassOddDirective,
  1581. ngCspDirective,
  1582. ngCloakDirective,
  1583. ngControllerDirective,
  1584. ngFormDirective,
  1585. ngHideDirective,
  1586. ngIfDirective,
  1587. ngIncludeDirective,
  1588. ngIncludeFillContentDirective,
  1589. ngInitDirective,
  1590. ngNonBindableDirective,
  1591. ngPluralizeDirective,
  1592. ngRepeatDirective,
  1593. ngShowDirective,
  1594. ngStyleDirective,
  1595. ngSwitchDirective,
  1596. ngSwitchWhenDirective,
  1597. ngSwitchDefaultDirective,
  1598. ngOptionsDirective,
  1599. ngTranscludeDirective,
  1600. ngModelDirective,
  1601. ngListDirective,
  1602. ngChangeDirective,
  1603. requiredDirective,
  1604. requiredDirective,
  1605. ngValueDirective,
  1606. ngAttributeAliasDirectives,
  1607. ngEventDirectives,
  1608. $AnchorScrollProvider,
  1609. $AnimateProvider,
  1610. $BrowserProvider,
  1611. $CacheFactoryProvider,
  1612. $ControllerProvider,
  1613. $DocumentProvider,
  1614. $ExceptionHandlerProvider,
  1615. $FilterProvider,
  1616. $InterpolateProvider,
  1617. $IntervalProvider,
  1618. $HttpProvider,
  1619. $HttpBackendProvider,
  1620. $LocationProvider,
  1621. $LogProvider,
  1622. $ParseProvider,
  1623. $RootScopeProvider,
  1624. $QProvider,
  1625. $$SanitizeUriProvider,
  1626. $SceProvider,
  1627. $SceDelegateProvider,
  1628. $SnifferProvider,
  1629. $TemplateCacheProvider,
  1630. $TimeoutProvider,
  1631. $WindowProvider
  1632. */
  1633. /**
  1634. * @ngdoc property
  1635. * @name angular.version
  1636. * @description
  1637. * An object that contains information about the current AngularJS version. This object has the
  1638. * following properties:
  1639. *
  1640. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1641. * - `major` – `{number}` – Major version number, such as "0".
  1642. * - `minor` – `{number}` – Minor version number, such as "9".
  1643. * - `dot` – `{number}` – Dot version number, such as "18".
  1644. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1645. */
  1646. var version = {
  1647. full: '1.2.9', // all of these placeholder strings will be replaced by grunt's
  1648. major: 1, // package task
  1649. minor: 2,
  1650. dot: 9,
  1651. codeName: 'enchanted-articulacy'
  1652. };
  1653. function publishExternalAPI(angular){
  1654. extend(angular, {
  1655. 'bootstrap': bootstrap,
  1656. 'copy': copy,
  1657. 'extend': extend,
  1658. 'equals': equals,
  1659. 'element': jqLite,
  1660. 'forEach': forEach,
  1661. 'injector': createInjector,
  1662. 'noop':noop,
  1663. 'bind':bind,
  1664. 'toJson': toJson,
  1665. 'fromJson': fromJson,
  1666. 'identity':identity,
  1667. 'isUndefined': isUndefined,
  1668. 'isDefined': isDefined,
  1669. 'isString': isString,
  1670. 'isFunction': isFunction,
  1671. 'isObject': isObject,
  1672. 'isNumber': isNumber,
  1673. 'isElement': isElement,
  1674. 'isArray': isArray,
  1675. 'version': version,
  1676. 'isDate': isDate,
  1677. 'lowercase': lowercase,
  1678. 'uppercase': uppercase,
  1679. 'callbacks': {counter: 0},
  1680. '$$minErr': minErr,
  1681. '$$csp': csp
  1682. });
  1683. angularModule = setupModuleLoader(window);
  1684. try {
  1685. angularModule('ngLocale');
  1686. } catch (e) {
  1687. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1688. }
  1689. angularModule('ng', ['ngLocale'], ['$provide',
  1690. function ngModule($provide) {
  1691. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1692. $provide.provider({
  1693. $$sanitizeUri: $$SanitizeUriProvider
  1694. });
  1695. $provide.provider('$compile', $CompileProvider).
  1696. directive({
  1697. a: htmlAnchorDirective,
  1698. input: inputDirective,
  1699. textarea: inputDirective,
  1700. form: formDirective,
  1701. script: scriptDirective,
  1702. select: selectDirective,
  1703. style: styleDirective,
  1704. option: optionDirective,
  1705. ngBind: ngBindDirective,
  1706. ngBindHtml: ngBindHtmlDirective,
  1707. ngBindTemplate: ngBindTemplateDirective,
  1708. ngClass: ngClassDirective,
  1709. ngClassEven: ngClassEvenDirective,
  1710. ngClassOdd: ngClassOddDirective,
  1711. ngCloak: ngCloakDirective,
  1712. ngController: ngControllerDirective,
  1713. ngForm: ngFormDirective,
  1714. ngHide: ngHideDirective,
  1715. ngIf: ngIfDirective,
  1716. ngInclude: ngIncludeDirective,
  1717. ngInit: ngInitDirective,
  1718. ngNonBindable: ngNonBindableDirective,
  1719. ngPluralize: ngPluralizeDirective,
  1720. ngRepeat: ngRepeatDirective,
  1721. ngShow: ngShowDirective,
  1722. ngStyle: ngStyleDirective,
  1723. ngSwitch: ngSwitchDirective,
  1724. ngSwitchWhen: ngSwitchWhenDirective,
  1725. ngSwitchDefault: ngSwitchDefaultDirective,
  1726. ngOptions: ngOptionsDirective,
  1727. ngTransclude: ngTranscludeDirective,
  1728. ngModel: ngModelDirective,
  1729. ngList: ngListDirective,
  1730. ngChange: ngChangeDirective,
  1731. required: requiredDirective,
  1732. ngRequired: requiredDirective,
  1733. ngValue: ngValueDirective
  1734. }).
  1735. directive({
  1736. ngInclude: ngIncludeFillContentDirective
  1737. }).
  1738. directive(ngAttributeAliasDirectives).
  1739. directive(ngEventDirectives);
  1740. $provide.provider({
  1741. $anchorScroll: $AnchorScrollProvider,
  1742. $animate: $AnimateProvider,
  1743. $browser: $BrowserProvider,
  1744. $cacheFactory: $CacheFactoryProvider,
  1745. $controller: $ControllerProvider,
  1746. $document: $DocumentProvider,
  1747. $exceptionHandler: $ExceptionHandlerProvider,
  1748. $filter: $FilterProvider,
  1749. $interpolate: $InterpolateProvider,
  1750. $interval: $IntervalProvider,
  1751. $http: $HttpProvider,
  1752. $httpBackend: $HttpBackendProvider,
  1753. $location: $LocationProvider,
  1754. $log: $LogProvider,
  1755. $parse: $ParseProvider,
  1756. $rootScope: $RootScopeProvider,
  1757. $q: $QProvider,
  1758. $sce: $SceProvider,
  1759. $sceDelegate: $SceDelegateProvider,
  1760. $sniffer: $SnifferProvider,
  1761. $templateCache: $TemplateCacheProvider,
  1762. $timeout: $TimeoutProvider,
  1763. $window: $WindowProvider
  1764. });
  1765. }
  1766. ]);
  1767. }
  1768. /* global
  1769. -JQLitePrototype,
  1770. -addEventListenerFn,
  1771. -removeEventListenerFn,
  1772. -BOOLEAN_ATTR
  1773. */
  1774. //////////////////////////////////
  1775. //JQLite
  1776. //////////////////////////////////
  1777. /**
  1778. * @ngdoc function
  1779. * @name angular.element
  1780. * @function
  1781. *
  1782. * @description
  1783. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  1784. *
  1785. * If jQuery is available, `angular.element` is an alias for the
  1786. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  1787. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  1788. *
  1789. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  1790. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  1791. * commonly needed functionality with the goal of having a very small footprint.</div>
  1792. *
  1793. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  1794. *
  1795. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  1796. * jqLite; they are never raw DOM references.</div>
  1797. *
  1798. * ## Angular's jqLite
  1799. * jqLite provides only the following jQuery methods:
  1800. *
  1801. * - [`addClass()`](http://api.jquery.com/addClass/)
  1802. * - [`after()`](http://api.jquery.com/after/)
  1803. * - [`append()`](http://api.jquery.com/append/)
  1804. * - [`attr()`](http://api.jquery.com/attr/)
  1805. * - [`bind()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1806. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  1807. * - [`clone()`](http://api.jquery.com/clone/)
  1808. * - [`contents()`](http://api.jquery.com/contents/)
  1809. * - [`css()`](http://api.jquery.com/css/)
  1810. * - [`data()`](http://api.jquery.com/data/)
  1811. * - [`empty()`](http://api.jquery.com/empty/)
  1812. * - [`eq()`](http://api.jquery.com/eq/)
  1813. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  1814. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  1815. * - [`html()`](http://api.jquery.com/html/)
  1816. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  1817. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1818. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  1819. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  1820. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  1821. * - [`prepend()`](http://api.jquery.com/prepend/)
  1822. * - [`prop()`](http://api.jquery.com/prop/)
  1823. * - [`ready()`](http://api.jquery.com/ready/)
  1824. * - [`remove()`](http://api.jquery.com/remove/)
  1825. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  1826. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  1827. * - [`removeData()`](http://api.jquery.com/removeData/)
  1828. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  1829. * - [`text()`](http://api.jquery.com/text/)
  1830. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  1831. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  1832. * - [`unbind()`](http://api.jquery.com/off/) - Does not support namespaces
  1833. * - [`val()`](http://api.jquery.com/val/)
  1834. * - [`wrap()`](http://api.jquery.com/wrap/)
  1835. *
  1836. * ## jQuery/jqLite Extras
  1837. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  1838. *
  1839. * ### Events
  1840. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  1841. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  1842. * element before it is removed.
  1843. *
  1844. * ### Methods
  1845. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  1846. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  1847. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  1848. * `'ngModel'`).
  1849. * - `injector()` - retrieves the injector of the current element or its parent.
  1850. * - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
  1851. * element or its parent.
  1852. * - `isolateScope()` - retrieves an isolate {@link api/ng.$rootScope.Scope scope} if one is attached directly to the
  1853. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  1854. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  1855. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  1856. * parent element is reached.
  1857. *
  1858. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  1859. * @returns {Object} jQuery object.
  1860. */
  1861. var jqCache = JQLite.cache = {},
  1862. jqName = JQLite.expando = 'ng-' + new Date().getTime(),
  1863. jqId = 1,
  1864. addEventListenerFn = (window.document.addEventListener
  1865. ? function(element, type, fn) {element.addEventListener(type, fn, false);}
  1866. : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
  1867. removeEventListenerFn = (window.document.removeEventListener
  1868. ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
  1869. : function(element, type, fn) {element.detachEvent('on' + type, fn); });
  1870. function jqNextId() { return ++jqId; }
  1871. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  1872. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  1873. var jqLiteMinErr = minErr('jqLite');
  1874. /**
  1875. * Converts snake_case to camelCase.
  1876. * Also there is special case for Moz prefix starting with upper case letter.
  1877. * @param name Name to normalize
  1878. */
  1879. function camelCase(name) {
  1880. return name.
  1881. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  1882. return offset ? letter.toUpperCase() : letter;
  1883. }).
  1884. replace(MOZ_HACK_REGEXP, 'Moz$1');
  1885. }
  1886. /////////////////////////////////////////////
  1887. // jQuery mutation patch
  1888. //
  1889. // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
  1890. // $destroy event on all DOM nodes being removed.
  1891. //
  1892. /////////////////////////////////////////////
  1893. function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
  1894. var originalJqFn = jQuery.fn[name];
  1895. originalJqFn = originalJqFn.$original || originalJqFn;
  1896. removePatch.$original = originalJqFn;
  1897. jQuery.fn[name] = removePatch;
  1898. function removePatch(param) {
  1899. // jshint -W040
  1900. var list = filterElems && param ? [this.filter(param)] : [this],
  1901. fireEvent = dispatchThis,
  1902. set, setIndex, setLength,
  1903. element, childIndex, childLength, children;
  1904. if (!getterIfNoArguments || param != null) {
  1905. while(list.length) {
  1906. set = list.shift();
  1907. for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
  1908. element = jqLite(set[setIndex]);
  1909. if (fireEvent) {
  1910. element.triggerHandler('$destroy');
  1911. } else {
  1912. fireEvent = !fireEvent;
  1913. }
  1914. for(childIndex = 0, childLength = (children = element.children()).length;
  1915. childIndex < childLength;
  1916. childIndex++) {
  1917. list.push(jQuery(children[childIndex]));
  1918. }
  1919. }
  1920. }
  1921. }
  1922. return originalJqFn.apply(this, arguments);
  1923. }
  1924. }
  1925. /////////////////////////////////////////////
  1926. function JQLite(element) {
  1927. if (element instanceof JQLite) {
  1928. return element;
  1929. }
  1930. if (!(this instanceof JQLite)) {
  1931. if (isString(element) && element.charAt(0) != '<') {
  1932. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  1933. }
  1934. return new JQLite(element);
  1935. }
  1936. if (isString(element)) {
  1937. var div = document.createElement('div');
  1938. // Read about the NoScope elements here:
  1939. // http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
  1940. div.innerHTML = '<div>&#160;</div>' + element; // IE insanity to make NoScope elements work!
  1941. div.removeChild(div.firstChild); // remove the superfluous div
  1942. jqLiteAddNodes(this, div.childNodes);
  1943. var fragment = jqLite(document.createDocumentFragment());
  1944. fragment.append(this); // detach the elements from the temporary DOM div.
  1945. } else {
  1946. jqLiteAddNodes(this, element);
  1947. }
  1948. }
  1949. function jqLiteClone(element) {
  1950. return element.cloneNode(true);
  1951. }
  1952. function jqLiteDealoc(element){
  1953. jqLiteRemoveData(element);
  1954. for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
  1955. jqLiteDealoc(children[i]);
  1956. }
  1957. }
  1958. function jqLiteOff(element, type, fn, unsupported) {
  1959. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  1960. var events = jqLiteExpandoStore(element, 'events'),
  1961. handle = jqLiteExpandoStore(element, 'handle');
  1962. if (!handle) return; //no listeners registered
  1963. if (isUndefined(type)) {
  1964. forEach(events, function(eventHandler, type) {
  1965. removeEventListenerFn(element, type, eventHandler);
  1966. delete events[type];
  1967. });
  1968. } else {
  1969. forEach(type.split(' '), function(type) {
  1970. if (isUndefined(fn)) {
  1971. removeEventListenerFn(element, type, events[type]);
  1972. delete events[type];
  1973. } else {
  1974. arrayRemove(events[type] || [], fn);
  1975. }
  1976. });
  1977. }
  1978. }
  1979. function jqLiteRemoveData(element, name) {
  1980. var expandoId = element[jqName],
  1981. expandoStore = jqCache[expandoId];
  1982. if (expandoStore) {
  1983. if (name) {
  1984. delete jqCache[expandoId].data[name];
  1985. return;
  1986. }
  1987. if (expandoStore.handle) {
  1988. expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
  1989. jqLiteOff(element);
  1990. }
  1991. delete jqCache[expandoId];
  1992. element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
  1993. }
  1994. }
  1995. function jqLiteExpandoStore(element, key, value) {
  1996. var expandoId = element[jqName],
  1997. expandoStore = jqCache[expandoId || -1];
  1998. if (isDefined(value)) {
  1999. if (!expandoStore) {
  2000. element[jqName] = expandoId = jqNextId();
  2001. expandoStore = jqCache[expandoId] = {};
  2002. }
  2003. expandoStore[key] = value;
  2004. } else {
  2005. return expandoStore && expandoStore[key];
  2006. }
  2007. }
  2008. function jqLiteData(element, key, value) {
  2009. var data = jqLiteExpandoStore(element, 'data'),
  2010. isSetter = isDefined(value),
  2011. keyDefined = !isSetter && isDefined(key),
  2012. isSimpleGetter = keyDefined && !isObject(key);
  2013. if (!data && !isSimpleGetter) {
  2014. jqLiteExpandoStore(element, 'data', data = {});
  2015. }
  2016. if (isSetter) {
  2017. data[key] = value;
  2018. } else {
  2019. if (keyDefined) {
  2020. if (isSimpleGetter) {
  2021. // don't create data in this case.
  2022. return data && data[key];
  2023. } else {
  2024. extend(data, key);
  2025. }
  2026. } else {
  2027. return data;
  2028. }
  2029. }
  2030. }
  2031. function jqLiteHasClass(element, selector) {
  2032. if (!element.getAttribute) return false;
  2033. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2034. indexOf( " " + selector + " " ) > -1);
  2035. }
  2036. function jqLiteRemoveClass(element, cssClasses) {
  2037. if (cssClasses && element.setAttribute) {
  2038. forEach(cssClasses.split(' '), function(cssClass) {
  2039. element.setAttribute('class', trim(
  2040. (" " + (element.getAttribute('class') || '') + " ")
  2041. .replace(/[\n\t]/g, " ")
  2042. .replace(" " + trim(cssClass) + " ", " "))
  2043. );
  2044. });
  2045. }
  2046. }
  2047. function jqLiteAddClass(element, cssClasses) {
  2048. if (cssClasses && element.setAttribute) {
  2049. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2050. .replace(/[\n\t]/g, " ");
  2051. forEach(cssClasses.split(' '), function(cssClass) {
  2052. cssClass = trim(cssClass);
  2053. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2054. existingClasses += cssClass + ' ';
  2055. }
  2056. });
  2057. element.setAttribute('class', trim(existingClasses));
  2058. }
  2059. }
  2060. function jqLiteAddNodes(root, elements) {
  2061. if (elements) {
  2062. elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
  2063. ? elements
  2064. : [ elements ];
  2065. for(var i=0; i < elements.length; i++) {
  2066. root.push(elements[i]);
  2067. }
  2068. }
  2069. }
  2070. function jqLiteController(element, name) {
  2071. return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
  2072. }
  2073. function jqLiteInheritedData(element, name, value) {
  2074. element = jqLite(element);
  2075. // if element is the document object work with the html element instead
  2076. // this makes $(document).scope() possible
  2077. if(element[0].nodeType == 9) {
  2078. element = element.find('html');
  2079. }
  2080. var names = isArray(name) ? name : [name];
  2081. while (element.length) {
  2082. for (var i = 0, ii = names.length; i < ii; i++) {
  2083. if ((value = element.data(names[i])) !== undefined) return value;
  2084. }
  2085. element = element.parent();
  2086. }
  2087. }
  2088. function jqLiteEmpty(element) {
  2089. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2090. jqLiteDealoc(childNodes[i]);
  2091. }
  2092. while (element.firstChild) {
  2093. element.removeChild(element.firstChild);
  2094. }
  2095. }
  2096. //////////////////////////////////////////
  2097. // Functions which are declared directly.
  2098. //////////////////////////////////////////
  2099. var JQLitePrototype = JQLite.prototype = {
  2100. ready: function(fn) {
  2101. var fired = false;
  2102. function trigger() {
  2103. if (fired) return;
  2104. fired = true;
  2105. fn();
  2106. }
  2107. // check if document already is loaded
  2108. if (document.readyState === 'complete'){
  2109. setTimeout(trigger);
  2110. } else {
  2111. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2112. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2113. // jshint -W064
  2114. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2115. // jshint +W064
  2116. }
  2117. },
  2118. toString: function() {
  2119. var value = [];
  2120. forEach(this, function(e){ value.push('' + e);});
  2121. return '[' + value.join(', ') + ']';
  2122. },
  2123. eq: function(index) {
  2124. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2125. },
  2126. length: 0,
  2127. push: push,
  2128. sort: [].sort,
  2129. splice: [].splice
  2130. };
  2131. //////////////////////////////////////////
  2132. // Functions iterating getter/setters.
  2133. // these functions return self on setter and
  2134. // value on get.
  2135. //////////////////////////////////////////
  2136. var BOOLEAN_ATTR = {};
  2137. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2138. BOOLEAN_ATTR[lowercase(value)] = value;
  2139. });
  2140. var BOOLEAN_ELEMENTS = {};
  2141. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2142. BOOLEAN_ELEMENTS[uppercase(value)] = true;
  2143. });
  2144. function getBooleanAttrName(element, name) {
  2145. // check dom last since we will most likely fail on name
  2146. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2147. // booleanAttr is here twice to minimize DOM access
  2148. return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
  2149. }
  2150. forEach({
  2151. data: jqLiteData,
  2152. inheritedData: jqLiteInheritedData,
  2153. scope: function(element) {
  2154. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2155. return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2156. },
  2157. isolateScope: function(element) {
  2158. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2159. return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
  2160. },
  2161. controller: jqLiteController ,
  2162. injector: function(element) {
  2163. return jqLiteInheritedData(element, '$injector');
  2164. },
  2165. removeAttr: function(element,name) {
  2166. element.removeAttribute(name);
  2167. },
  2168. hasClass: jqLiteHasClass,
  2169. css: function(element, name, value) {
  2170. name = camelCase(name);
  2171. if (isDefined(value)) {
  2172. element.style[name] = value;
  2173. } else {
  2174. var val;
  2175. if (msie <= 8) {
  2176. // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
  2177. val = element.currentStyle && element.currentStyle[name];
  2178. if (val === '') val = 'auto';
  2179. }
  2180. val = val || element.style[name];
  2181. if (msie <= 8) {
  2182. // jquery weirdness :-/
  2183. val = (val === '') ? undefined : val;
  2184. }
  2185. return val;
  2186. }
  2187. },
  2188. attr: function(element, name, value){
  2189. var lowercasedName = lowercase(name);
  2190. if (BOOLEAN_ATTR[lowercasedName]) {
  2191. if (isDefined(value)) {
  2192. if (!!value) {
  2193. element[name] = true;
  2194. element.setAttribute(name, lowercasedName);
  2195. } else {
  2196. element[name] = false;
  2197. element.removeAttribute(lowercasedName);
  2198. }
  2199. } else {
  2200. return (element[name] ||
  2201. (element.attributes.getNamedItem(name)|| noop).specified)
  2202. ? lowercasedName
  2203. : undefined;
  2204. }
  2205. } else if (isDefined(value)) {
  2206. element.setAttribute(name, value);
  2207. } else if (element.getAttribute) {
  2208. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2209. // some elements (e.g. Document) don't have get attribute, so return undefined
  2210. var ret = element.getAttribute(name, 2);
  2211. // normalize non-existing attributes to undefined (as jQuery)
  2212. return ret === null ? undefined : ret;
  2213. }
  2214. },
  2215. prop: function(element, name, value) {
  2216. if (isDefined(value)) {
  2217. element[name] = value;
  2218. } else {
  2219. return element[name];
  2220. }
  2221. },
  2222. text: (function() {
  2223. var NODE_TYPE_TEXT_PROPERTY = [];
  2224. if (msie < 9) {
  2225. NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
  2226. NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
  2227. } else {
  2228. NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
  2229. NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
  2230. }
  2231. getText.$dv = '';
  2232. return getText;
  2233. function getText(element, value) {
  2234. var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
  2235. if (isUndefined(value)) {
  2236. return textProp ? element[textProp] : '';
  2237. }
  2238. element[textProp] = value;
  2239. }
  2240. })(),
  2241. val: function(element, value) {
  2242. if (isUndefined(value)) {
  2243. if (nodeName_(element) === 'SELECT' && element.multiple) {
  2244. var result = [];
  2245. forEach(element.options, function (option) {
  2246. if (option.selected) {
  2247. result.push(option.value || option.text);
  2248. }
  2249. });
  2250. return result.length === 0 ? null : result;
  2251. }
  2252. return element.value;
  2253. }
  2254. element.value = value;
  2255. },
  2256. html: function(element, value) {
  2257. if (isUndefined(value)) {
  2258. return element.innerHTML;
  2259. }
  2260. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2261. jqLiteDealoc(childNodes[i]);
  2262. }
  2263. element.innerHTML = value;
  2264. },
  2265. empty: jqLiteEmpty
  2266. }, function(fn, name){
  2267. /**
  2268. * Properties: writes return selection, reads return first value
  2269. */
  2270. JQLite.prototype[name] = function(arg1, arg2) {
  2271. var i, key;
  2272. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2273. // in a way that survives minification.
  2274. // jqLiteEmpty takes no arguments but is a setter.
  2275. if (fn !== jqLiteEmpty &&
  2276. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2277. if (isObject(arg1)) {
  2278. // we are a write, but the object properties are the key/values
  2279. for (i = 0; i < this.length; i++) {
  2280. if (fn === jqLiteData) {
  2281. // data() takes the whole object in jQuery
  2282. fn(this[i], arg1);
  2283. } else {
  2284. for (key in arg1) {
  2285. fn(this[i], key, arg1[key]);
  2286. }
  2287. }
  2288. }
  2289. // return self for chaining
  2290. return this;
  2291. } else {
  2292. // we are a read, so read the first child.
  2293. var value = fn.$dv;
  2294. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2295. var jj = (value === undefined) ? Math.min(this.length, 1) : this.length;
  2296. for (var j = 0; j < jj; j++) {
  2297. var nodeValue = fn(this[j], arg1, arg2);
  2298. value = value ? value + nodeValue : nodeValue;
  2299. }
  2300. return value;
  2301. }
  2302. } else {
  2303. // we are a write, so apply to all children
  2304. for (i = 0; i < this.length; i++) {
  2305. fn(this[i], arg1, arg2);
  2306. }
  2307. // return self for chaining
  2308. return this;
  2309. }
  2310. };
  2311. });
  2312. function createEventHandler(element, events) {
  2313. var eventHandler = function (event, type) {
  2314. if (!event.preventDefault) {
  2315. event.preventDefault = function() {
  2316. event.returnValue = false; //ie
  2317. };
  2318. }
  2319. if (!event.stopPropagation) {
  2320. event.stopPropagation = function() {
  2321. event.cancelBubble = true; //ie
  2322. };
  2323. }
  2324. if (!event.target) {
  2325. event.target = event.srcElement || document;
  2326. }
  2327. if (isUndefined(event.defaultPrevented)) {
  2328. var prevent = event.preventDefault;
  2329. event.preventDefault = function() {
  2330. event.defaultPrevented = true;
  2331. prevent.call(event);
  2332. };
  2333. event.defaultPrevented = false;
  2334. }
  2335. event.isDefaultPrevented = function() {
  2336. return event.defaultPrevented || event.returnValue === false;
  2337. };
  2338. // Copy event handlers in case event handlers array is modified during execution.
  2339. var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
  2340. forEach(eventHandlersCopy, function(fn) {
  2341. fn.call(element, event);
  2342. });
  2343. // Remove monkey-patched methods (IE),
  2344. // as they would cause memory leaks in IE8.
  2345. if (msie <= 8) {
  2346. // IE7/8 does not allow to delete property on native object
  2347. event.preventDefault = null;
  2348. event.stopPropagation = null;
  2349. event.isDefaultPrevented = null;
  2350. } else {
  2351. // It shouldn't affect normal browsers (native methods are defined on prototype).
  2352. delete event.preventDefault;
  2353. delete event.stopPropagation;
  2354. delete event.isDefaultPrevented;
  2355. }
  2356. };
  2357. eventHandler.elem = element;
  2358. return eventHandler;
  2359. }
  2360. //////////////////////////////////////////
  2361. // Functions iterating traversal.
  2362. // These functions chain results into a single
  2363. // selector.
  2364. //////////////////////////////////////////
  2365. forEach({
  2366. removeData: jqLiteRemoveData,
  2367. dealoc: jqLiteDealoc,
  2368. on: function onFn(element, type, fn, unsupported){
  2369. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2370. var events = jqLiteExpandoStore(element, 'events'),
  2371. handle = jqLiteExpandoStore(element, 'handle');
  2372. if (!events) jqLiteExpandoStore(element, 'events', events = {});
  2373. if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
  2374. forEach(type.split(' '), function(type){
  2375. var eventFns = events[type];
  2376. if (!eventFns) {
  2377. if (type == 'mouseenter' || type == 'mouseleave') {
  2378. var contains = document.body.contains || document.body.compareDocumentPosition ?
  2379. function( a, b ) {
  2380. // jshint bitwise: false
  2381. var adown = a.nodeType === 9 ? a.documentElement : a,
  2382. bup = b && b.parentNode;
  2383. return a === bup || !!( bup && bup.nodeType === 1 && (
  2384. adown.contains ?
  2385. adown.contains( bup ) :
  2386. a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
  2387. ));
  2388. } :
  2389. function( a, b ) {
  2390. if ( b ) {
  2391. while ( (b = b.parentNode) ) {
  2392. if ( b === a ) {
  2393. return true;
  2394. }
  2395. }
  2396. }
  2397. return false;
  2398. };
  2399. events[type] = [];
  2400. // Refer to jQuery's implementation of mouseenter & mouseleave
  2401. // Read about mouseenter and mouseleave:
  2402. // http://www.quirksmode.org/js/events_mouse.html#link8
  2403. var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
  2404. onFn(element, eventmap[type], function(event) {
  2405. var target = this, related = event.relatedTarget;
  2406. // For mousenter/leave call the handler if related is outside the target.
  2407. // NB: No relatedTarget if the mouse left/entered the browser window
  2408. if ( !related || (related !== target && !contains(target, related)) ){
  2409. handle(event, type);
  2410. }
  2411. });
  2412. } else {
  2413. addEventListenerFn(element, type, handle);
  2414. events[type] = [];
  2415. }
  2416. eventFns = events[type];
  2417. }
  2418. eventFns.push(fn);
  2419. });
  2420. },
  2421. off: jqLiteOff,
  2422. one: function(element, type, fn) {
  2423. element = jqLite(element);
  2424. //add the listener twice so that when it is called
  2425. //you can remove the original function and still be
  2426. //able to call element.off(ev, fn) normally
  2427. element.on(type, function onFn() {
  2428. element.off(type, fn);
  2429. element.off(type, onFn);
  2430. });
  2431. element.on(type, fn);
  2432. },
  2433. replaceWith: function(element, replaceNode) {
  2434. var index, parent = element.parentNode;
  2435. jqLiteDealoc(element);
  2436. forEach(new JQLite(replaceNode), function(node){
  2437. if (index) {
  2438. parent.insertBefore(node, index.nextSibling);
  2439. } else {
  2440. parent.replaceChild(node, element);
  2441. }
  2442. index = node;
  2443. });
  2444. },
  2445. children: function(element) {
  2446. var children = [];
  2447. forEach(element.childNodes, function(element){
  2448. if (element.nodeType === 1)
  2449. children.push(element);
  2450. });
  2451. return children;
  2452. },
  2453. contents: function(element) {
  2454. return element.childNodes || [];
  2455. },
  2456. append: function(element, node) {
  2457. forEach(new JQLite(node), function(child){
  2458. if (element.nodeType === 1 || element.nodeType === 11) {
  2459. element.appendChild(child);
  2460. }
  2461. });
  2462. },
  2463. prepend: function(element, node) {
  2464. if (element.nodeType === 1) {
  2465. var index = element.firstChild;
  2466. forEach(new JQLite(node), function(child){
  2467. element.insertBefore(child, index);
  2468. });
  2469. }
  2470. },
  2471. wrap: function(element, wrapNode) {
  2472. wrapNode = jqLite(wrapNode)[0];
  2473. var parent = element.parentNode;
  2474. if (parent) {
  2475. parent.replaceChild(wrapNode, element);
  2476. }
  2477. wrapNode.appendChild(element);
  2478. },
  2479. remove: function(element) {
  2480. jqLiteDealoc(element);
  2481. var parent = element.parentNode;
  2482. if (parent) parent.removeChild(element);
  2483. },
  2484. after: function(element, newElement) {
  2485. var index = element, parent = element.parentNode;
  2486. forEach(new JQLite(newElement), function(node){
  2487. parent.insertBefore(node, index.nextSibling);
  2488. index = node;
  2489. });
  2490. },
  2491. addClass: jqLiteAddClass,
  2492. removeClass: jqLiteRemoveClass,
  2493. toggleClass: function(element, selector, condition) {
  2494. if (isUndefined(condition)) {
  2495. condition = !jqLiteHasClass(element, selector);
  2496. }
  2497. (condition ? jqLiteAddClass : jqLiteRemoveClass)(element, selector);
  2498. },
  2499. parent: function(element) {
  2500. var parent = element.parentNode;
  2501. return parent && parent.nodeType !== 11 ? parent : null;
  2502. },
  2503. next: function(element) {
  2504. if (element.nextElementSibling) {
  2505. return element.nextElementSibling;
  2506. }
  2507. // IE8 doesn't have nextElementSibling
  2508. var elm = element.nextSibling;
  2509. while (elm != null && elm.nodeType !== 1) {
  2510. elm = elm.nextSibling;
  2511. }
  2512. return elm;
  2513. },
  2514. find: function(element, selector) {
  2515. if (element.getElementsByTagName) {
  2516. return element.getElementsByTagName(selector);
  2517. } else {
  2518. return [];
  2519. }
  2520. },
  2521. clone: jqLiteClone,
  2522. triggerHandler: function(element, eventName, eventData) {
  2523. var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
  2524. eventData = eventData || [];
  2525. var event = [{
  2526. preventDefault: noop,
  2527. stopPropagation: noop
  2528. }];
  2529. forEach(eventFns, function(fn) {
  2530. fn.apply(element, event.concat(eventData));
  2531. });
  2532. }
  2533. }, function(fn, name){
  2534. /**
  2535. * chaining functions
  2536. */
  2537. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2538. var value;
  2539. for(var i=0; i < this.length; i++) {
  2540. if (isUndefined(value)) {
  2541. value = fn(this[i], arg1, arg2, arg3);
  2542. if (isDefined(value)) {
  2543. // any function which returns a value needs to be wrapped
  2544. value = jqLite(value);
  2545. }
  2546. } else {
  2547. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2548. }
  2549. }
  2550. return isDefined(value) ? value : this;
  2551. };
  2552. // bind legacy bind/unbind to on/off
  2553. JQLite.prototype.bind = JQLite.prototype.on;
  2554. JQLite.prototype.unbind = JQLite.prototype.off;
  2555. });
  2556. /**
  2557. * Computes a hash of an 'obj'.
  2558. * Hash of a:
  2559. * string is string
  2560. * number is number as string
  2561. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2562. * that is also assigned to the $$hashKey property of the object.
  2563. *
  2564. * @param obj
  2565. * @returns {string} hash string such that the same input will have the same hash string.
  2566. * The resulting string key is in 'type:hashKey' format.
  2567. */
  2568. function hashKey(obj) {
  2569. var objType = typeof obj,
  2570. key;
  2571. if (objType == 'object' && obj !== null) {
  2572. if (typeof (key = obj.$$hashKey) == 'function') {
  2573. // must invoke on object to keep the right this
  2574. key = obj.$$hashKey();
  2575. } else if (key === undefined) {
  2576. key = obj.$$hashKey = nextUid();
  2577. }
  2578. } else {
  2579. key = obj;
  2580. }
  2581. return objType + ':' + key;
  2582. }
  2583. /**
  2584. * HashMap which can use objects as keys
  2585. */
  2586. function HashMap(array){
  2587. forEach(array, this.put, this);
  2588. }
  2589. HashMap.prototype = {
  2590. /**
  2591. * Store key value pair
  2592. * @param key key to store can be any type
  2593. * @param value value to store can be any type
  2594. */
  2595. put: function(key, value) {
  2596. this[hashKey(key)] = value;
  2597. },
  2598. /**
  2599. * @param key
  2600. * @returns the value for the key
  2601. */
  2602. get: function(key) {
  2603. return this[hashKey(key)];
  2604. },
  2605. /**
  2606. * Remove the key/value pair
  2607. * @param key
  2608. */
  2609. remove: function(key) {
  2610. var value = this[key = hashKey(key)];
  2611. delete this[key];
  2612. return value;
  2613. }
  2614. };
  2615. /**
  2616. * @ngdoc function
  2617. * @name angular.injector
  2618. * @function
  2619. *
  2620. * @description
  2621. * Creates an injector function that can be used for retrieving services as well as for
  2622. * dependency injection (see {@link guide/di dependency injection}).
  2623. *
  2624. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2625. * {@link angular.module}. The `ng` module must be explicitly added.
  2626. * @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
  2627. *
  2628. * @example
  2629. * Typical usage
  2630. * <pre>
  2631. * // create an injector
  2632. * var $injector = angular.injector(['ng']);
  2633. *
  2634. * // use the injector to kick off your application
  2635. * // use the type inference to auto inject arguments, or use implicit injection
  2636. * $injector.invoke(function($rootScope, $compile, $document){
  2637. * $compile($document)($rootScope);
  2638. * $rootScope.$digest();
  2639. * });
  2640. * </pre>
  2641. *
  2642. * Sometimes you want to get access to the injector of a currently running Angular app
  2643. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2644. * application has been bootstrapped. You can do this using extra `injector()` added
  2645. * to JQuery/jqLite elements. See {@link angular.element}.
  2646. *
  2647. * *This is fairly rare but could be the case if a third party library is injecting the
  2648. * markup.*
  2649. *
  2650. * In the following example a new block of HTML containing a `ng-controller`
  2651. * directive is added to the end of the document body by JQuery. We then compile and link
  2652. * it into the current AngularJS scope.
  2653. *
  2654. * <pre>
  2655. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2656. * $(document.body).append($div);
  2657. *
  2658. * angular.element(document).injector().invoke(function($compile) {
  2659. * var scope = angular.element($div).scope();
  2660. * $compile($div)(scope);
  2661. * });
  2662. * </pre>
  2663. */
  2664. /**
  2665. * @ngdoc overview
  2666. * @name AUTO
  2667. * @description
  2668. *
  2669. * Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
  2670. */
  2671. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  2672. var FN_ARG_SPLIT = /,/;
  2673. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  2674. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  2675. var $injectorMinErr = minErr('$injector');
  2676. function annotate(fn) {
  2677. var $inject,
  2678. fnText,
  2679. argDecl,
  2680. last;
  2681. if (typeof fn == 'function') {
  2682. if (!($inject = fn.$inject)) {
  2683. $inject = [];
  2684. if (fn.length) {
  2685. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  2686. argDecl = fnText.match(FN_ARGS);
  2687. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
  2688. arg.replace(FN_ARG, function(all, underscore, name){
  2689. $inject.push(name);
  2690. });
  2691. });
  2692. }
  2693. fn.$inject = $inject;
  2694. }
  2695. } else if (isArray(fn)) {
  2696. last = fn.length - 1;
  2697. assertArgFn(fn[last], 'fn');
  2698. $inject = fn.slice(0, last);
  2699. } else {
  2700. assertArgFn(fn, 'fn', true);
  2701. }
  2702. return $inject;
  2703. }
  2704. ///////////////////////////////////////
  2705. /**
  2706. * @ngdoc object
  2707. * @name AUTO.$injector
  2708. * @function
  2709. *
  2710. * @description
  2711. *
  2712. * `$injector` is used to retrieve object instances as defined by
  2713. * {@link AUTO.$provide provider}, instantiate types, invoke methods,
  2714. * and load modules.
  2715. *
  2716. * The following always holds true:
  2717. *
  2718. * <pre>
  2719. * var $injector = angular.injector();
  2720. * expect($injector.get('$injector')).toBe($injector);
  2721. * expect($injector.invoke(function($injector){
  2722. * return $injector;
  2723. * }).toBe($injector);
  2724. * </pre>
  2725. *
  2726. * # Injection Function Annotation
  2727. *
  2728. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  2729. * following are all valid ways of annotating function with injection arguments and are equivalent.
  2730. *
  2731. * <pre>
  2732. * // inferred (only works if code not minified/obfuscated)
  2733. * $injector.invoke(function(serviceA){});
  2734. *
  2735. * // annotated
  2736. * function explicit(serviceA) {};
  2737. * explicit.$inject = ['serviceA'];
  2738. * $injector.invoke(explicit);
  2739. *
  2740. * // inline
  2741. * $injector.invoke(['serviceA', function(serviceA){}]);
  2742. * </pre>
  2743. *
  2744. * ## Inference
  2745. *
  2746. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  2747. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  2748. * minification, and obfuscation tools since these tools change the argument names.
  2749. *
  2750. * ## `$inject` Annotation
  2751. * By adding a `$inject` property onto a function the injection parameters can be specified.
  2752. *
  2753. * ## Inline
  2754. * As an array of injection names, where the last item in the array is the function to call.
  2755. */
  2756. /**
  2757. * @ngdoc method
  2758. * @name AUTO.$injector#get
  2759. * @methodOf AUTO.$injector
  2760. *
  2761. * @description
  2762. * Return an instance of the service.
  2763. *
  2764. * @param {string} name The name of the instance to retrieve.
  2765. * @return {*} The instance.
  2766. */
  2767. /**
  2768. * @ngdoc method
  2769. * @name AUTO.$injector#invoke
  2770. * @methodOf AUTO.$injector
  2771. *
  2772. * @description
  2773. * Invoke the method and supply the method arguments from the `$injector`.
  2774. *
  2775. * @param {!function} fn The function to invoke. Function parameters are injected according to the
  2776. * {@link guide/di $inject Annotation} rules.
  2777. * @param {Object=} self The `this` for the invoked method.
  2778. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2779. * object first, before the `$injector` is consulted.
  2780. * @returns {*} the value returned by the invoked `fn` function.
  2781. */
  2782. /**
  2783. * @ngdoc method
  2784. * @name AUTO.$injector#has
  2785. * @methodOf AUTO.$injector
  2786. *
  2787. * @description
  2788. * Allows the user to query if the particular service exist.
  2789. *
  2790. * @param {string} Name of the service to query.
  2791. * @returns {boolean} returns true if injector has given service.
  2792. */
  2793. /**
  2794. * @ngdoc method
  2795. * @name AUTO.$injector#instantiate
  2796. * @methodOf AUTO.$injector
  2797. * @description
  2798. * Create a new instance of JS type. The method takes a constructor function invokes the new
  2799. * operator and supplies all of the arguments to the constructor function as specified by the
  2800. * constructor annotation.
  2801. *
  2802. * @param {function} Type Annotated constructor function.
  2803. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2804. * object first, before the `$injector` is consulted.
  2805. * @returns {Object} new instance of `Type`.
  2806. */
  2807. /**
  2808. * @ngdoc method
  2809. * @name AUTO.$injector#annotate
  2810. * @methodOf AUTO.$injector
  2811. *
  2812. * @description
  2813. * Returns an array of service names which the function is requesting for injection. This API is
  2814. * used by the injector to determine which services need to be injected into the function when the
  2815. * function is invoked. There are three ways in which the function can be annotated with the needed
  2816. * dependencies.
  2817. *
  2818. * # Argument names
  2819. *
  2820. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  2821. * by converting the function into a string using `toString()` method and extracting the argument
  2822. * names.
  2823. * <pre>
  2824. * // Given
  2825. * function MyController($scope, $route) {
  2826. * // ...
  2827. * }
  2828. *
  2829. * // Then
  2830. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  2831. * </pre>
  2832. *
  2833. * This method does not work with code minification / obfuscation. For this reason the following
  2834. * annotation strategies are supported.
  2835. *
  2836. * # The `$inject` property
  2837. *
  2838. * If a function has an `$inject` property and its value is an array of strings, then the strings
  2839. * represent names of services to be injected into the function.
  2840. * <pre>
  2841. * // Given
  2842. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  2843. * // ...
  2844. * }
  2845. * // Define function dependencies
  2846. * MyController['$inject'] = ['$scope', '$route'];
  2847. *
  2848. * // Then
  2849. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  2850. * </pre>
  2851. *
  2852. * # The array notation
  2853. *
  2854. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  2855. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  2856. * a way that survives minification is a better choice:
  2857. *
  2858. * <pre>
  2859. * // We wish to write this (not minification / obfuscation safe)
  2860. * injector.invoke(function($compile, $rootScope) {
  2861. * // ...
  2862. * });
  2863. *
  2864. * // We are forced to write break inlining
  2865. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  2866. * // ...
  2867. * };
  2868. * tmpFn.$inject = ['$compile', '$rootScope'];
  2869. * injector.invoke(tmpFn);
  2870. *
  2871. * // To better support inline function the inline annotation is supported
  2872. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  2873. * // ...
  2874. * }]);
  2875. *
  2876. * // Therefore
  2877. * expect(injector.annotate(
  2878. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  2879. * ).toEqual(['$compile', '$rootScope']);
  2880. * </pre>
  2881. *
  2882. * @param {function|Array.<string|Function>} fn Function for which dependent service names need to
  2883. * be retrieved as described above.
  2884. *
  2885. * @returns {Array.<string>} The names of the services which the function requires.
  2886. */
  2887. /**
  2888. * @ngdoc object
  2889. * @name AUTO.$provide
  2890. *
  2891. * @description
  2892. *
  2893. * The {@link AUTO.$provide $provide} service has a number of methods for registering components
  2894. * with the {@link AUTO.$injector $injector}. Many of these functions are also exposed on
  2895. * {@link angular.Module}.
  2896. *
  2897. * An Angular **service** is a singleton object created by a **service factory**. These **service
  2898. * factories** are functions which, in turn, are created by a **service provider**.
  2899. * The **service providers** are constructor functions. When instantiated they must contain a
  2900. * property called `$get`, which holds the **service factory** function.
  2901. *
  2902. * When you request a service, the {@link AUTO.$injector $injector} is responsible for finding the
  2903. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  2904. * function to get the instance of the **service**.
  2905. *
  2906. * Often services have no configuration options and there is no need to add methods to the service
  2907. * provider. The provider will be no more than a constructor function with a `$get` property. For
  2908. * these cases the {@link AUTO.$provide $provide} service has additional helper methods to register
  2909. * services without specifying a provider.
  2910. *
  2911. * * {@link AUTO.$provide#methods_provider provider(provider)} - registers a **service provider** with the
  2912. * {@link AUTO.$injector $injector}
  2913. * * {@link AUTO.$provide#methods_constant constant(obj)} - registers a value/object that can be accessed by
  2914. * providers and services.
  2915. * * {@link AUTO.$provide#methods_value value(obj)} - registers a value/object that can only be accessed by
  2916. * services, not providers.
  2917. * * {@link AUTO.$provide#methods_factory factory(fn)} - registers a service **factory function**, `fn`,
  2918. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  2919. * given factory function.
  2920. * * {@link AUTO.$provide#methods_service service(class)} - registers a **constructor function**, `class` that
  2921. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  2922. * a new object using the given constructor function.
  2923. *
  2924. * See the individual methods for more information and examples.
  2925. */
  2926. /**
  2927. * @ngdoc method
  2928. * @name AUTO.$provide#provider
  2929. * @methodOf AUTO.$provide
  2930. * @description
  2931. *
  2932. * Register a **provider function** with the {@link AUTO.$injector $injector}. Provider functions
  2933. * are constructor functions, whose instances are responsible for "providing" a factory for a
  2934. * service.
  2935. *
  2936. * Service provider names start with the name of the service they provide followed by `Provider`.
  2937. * For example, the {@link ng.$log $log} service has a provider called
  2938. * {@link ng.$logProvider $logProvider}.
  2939. *
  2940. * Service provider objects can have additional methods which allow configuration of the provider
  2941. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  2942. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  2943. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  2944. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  2945. * console or not.
  2946. *
  2947. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  2948. 'Provider'` key.
  2949. * @param {(Object|function())} provider If the provider is:
  2950. *
  2951. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  2952. * {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be
  2953. * created.
  2954. * - `Constructor`: a new instance of the provider will be created using
  2955. * {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as
  2956. * `object`.
  2957. *
  2958. * @returns {Object} registered provider instance
  2959. * @example
  2960. *
  2961. * The following example shows how to create a simple event tracking service and register it using
  2962. * {@link AUTO.$provide#methods_provider $provide.provider()}.
  2963. *
  2964. * <pre>
  2965. * // Define the eventTracker provider
  2966. * function EventTrackerProvider() {
  2967. * var trackingUrl = '/track';
  2968. *
  2969. * // A provider method for configuring where the tracked events should been saved
  2970. * this.setTrackingUrl = function(url) {
  2971. * trackingUrl = url;
  2972. * };
  2973. *
  2974. * // The service factory function
  2975. * this.$get = ['$http', function($http) {
  2976. * var trackedEvents = {};
  2977. * return {
  2978. * // Call this to track an event
  2979. * event: function(event) {
  2980. * var count = trackedEvents[event] || 0;
  2981. * count += 1;
  2982. * trackedEvents[event] = count;
  2983. * return count;
  2984. * },
  2985. * // Call this to save the tracked events to the trackingUrl
  2986. * save: function() {
  2987. * $http.post(trackingUrl, trackedEvents);
  2988. * }
  2989. * };
  2990. * }];
  2991. * }
  2992. *
  2993. * describe('eventTracker', function() {
  2994. * var postSpy;
  2995. *
  2996. * beforeEach(module(function($provide) {
  2997. * // Register the eventTracker provider
  2998. * $provide.provider('eventTracker', EventTrackerProvider);
  2999. * }));
  3000. *
  3001. * beforeEach(module(function(eventTrackerProvider) {
  3002. * // Configure eventTracker provider
  3003. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3004. * }));
  3005. *
  3006. * it('tracks events', inject(function(eventTracker) {
  3007. * expect(eventTracker.event('login')).toEqual(1);
  3008. * expect(eventTracker.event('login')).toEqual(2);
  3009. * }));
  3010. *
  3011. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3012. * postSpy = spyOn($http, 'post');
  3013. * eventTracker.event('login');
  3014. * eventTracker.save();
  3015. * expect(postSpy).toHaveBeenCalled();
  3016. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3017. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3018. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3019. * }));
  3020. * });
  3021. * </pre>
  3022. */
  3023. /**
  3024. * @ngdoc method
  3025. * @name AUTO.$provide#factory
  3026. * @methodOf AUTO.$provide
  3027. * @description
  3028. *
  3029. * Register a **service factory**, which will be called to return the service instance.
  3030. * This is short for registering a service where its provider consists of only a `$get` property,
  3031. * which is the given service factory function.
  3032. * You should use {@link AUTO.$provide#factory $provide.factory(getFn)} if you do not need to
  3033. * configure your service in a provider.
  3034. *
  3035. * @param {string} name The name of the instance.
  3036. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3037. * for `$provide.provider(name, {$get: $getFn})`.
  3038. * @returns {Object} registered provider instance
  3039. *
  3040. * @example
  3041. * Here is an example of registering a service
  3042. * <pre>
  3043. * $provide.factory('ping', ['$http', function($http) {
  3044. * return function ping() {
  3045. * return $http.send('/ping');
  3046. * };
  3047. * }]);
  3048. * </pre>
  3049. * You would then inject and use this service like this:
  3050. * <pre>
  3051. * someModule.controller('Ctrl', ['ping', function(ping) {
  3052. * ping();
  3053. * }]);
  3054. * </pre>
  3055. */
  3056. /**
  3057. * @ngdoc method
  3058. * @name AUTO.$provide#service
  3059. * @methodOf AUTO.$provide
  3060. * @description
  3061. *
  3062. * Register a **service constructor**, which will be invoked with `new` to create the service
  3063. * instance.
  3064. * This is short for registering a service where its provider's `$get` property is the service
  3065. * constructor function that will be used to instantiate the service instance.
  3066. *
  3067. * You should use {@link AUTO.$provide#methods_service $provide.service(class)} if you define your service
  3068. * as a type/class.
  3069. *
  3070. * @param {string} name The name of the instance.
  3071. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3072. * @returns {Object} registered provider instance
  3073. *
  3074. * @example
  3075. * Here is an example of registering a service using
  3076. * {@link AUTO.$provide#methods_service $provide.service(class)}.
  3077. * <pre>
  3078. * $provide.service('ping', ['$http', function($http) {
  3079. * var Ping = function() {
  3080. * this.$http = $http;
  3081. * };
  3082. *
  3083. * Ping.prototype.send = function() {
  3084. * return this.$http.get('/ping');
  3085. * };
  3086. *
  3087. * return Ping;
  3088. * }]);
  3089. * </pre>
  3090. * You would then inject and use this service like this:
  3091. * <pre>
  3092. * someModule.controller('Ctrl', ['ping', function(ping) {
  3093. * ping.send();
  3094. * }]);
  3095. * </pre>
  3096. */
  3097. /**
  3098. * @ngdoc method
  3099. * @name AUTO.$provide#value
  3100. * @methodOf AUTO.$provide
  3101. * @description
  3102. *
  3103. * Register a **value service** with the {@link AUTO.$injector $injector}, such as a string, a
  3104. * number, an array, an object or a function. This is short for registering a service where its
  3105. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3106. * service**.
  3107. *
  3108. * Value services are similar to constant services, except that they cannot be injected into a
  3109. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3110. * an Angular
  3111. * {@link AUTO.$provide#decorator decorator}.
  3112. *
  3113. * @param {string} name The name of the instance.
  3114. * @param {*} value The value.
  3115. * @returns {Object} registered provider instance
  3116. *
  3117. * @example
  3118. * Here are some examples of creating value services.
  3119. * <pre>
  3120. * $provide.value('ADMIN_USER', 'admin');
  3121. *
  3122. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3123. *
  3124. * $provide.value('halfOf', function(value) {
  3125. * return value / 2;
  3126. * });
  3127. * </pre>
  3128. */
  3129. /**
  3130. * @ngdoc method
  3131. * @name AUTO.$provide#constant
  3132. * @methodOf AUTO.$provide
  3133. * @description
  3134. *
  3135. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3136. * with the {@link AUTO.$injector $injector}. Unlike {@link AUTO.$provide#value value} it can be
  3137. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3138. * be overridden by an Angular {@link AUTO.$provide#decorator decorator}.
  3139. *
  3140. * @param {string} name The name of the constant.
  3141. * @param {*} value The constant value.
  3142. * @returns {Object} registered instance
  3143. *
  3144. * @example
  3145. * Here a some examples of creating constants:
  3146. * <pre>
  3147. * $provide.constant('SHARD_HEIGHT', 306);
  3148. *
  3149. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3150. *
  3151. * $provide.constant('double', function(value) {
  3152. * return value * 2;
  3153. * });
  3154. * </pre>
  3155. */
  3156. /**
  3157. * @ngdoc method
  3158. * @name AUTO.$provide#decorator
  3159. * @methodOf AUTO.$provide
  3160. * @description
  3161. *
  3162. * Register a **service decorator** with the {@link AUTO.$injector $injector}. A service decorator
  3163. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3164. * service. The object returned by the decorator may be the original service, or a new service
  3165. * object which replaces or wraps and delegates to the original service.
  3166. *
  3167. * @param {string} name The name of the service to decorate.
  3168. * @param {function()} decorator This function will be invoked when the service needs to be
  3169. * instantiated and should return the decorated service instance. The function is called using
  3170. * the {@link AUTO.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3171. * Local injection arguments:
  3172. *
  3173. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3174. * decorated or delegated to.
  3175. *
  3176. * @example
  3177. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3178. * calls to {@link ng.$log#error $log.warn()}.
  3179. * <pre>
  3180. * $provider.decorator('$log', ['$delegate', function($delegate) {
  3181. * $delegate.warn = $delegate.error;
  3182. * return $delegate;
  3183. * }]);
  3184. * </pre>
  3185. */
  3186. function createInjector(modulesToLoad) {
  3187. var INSTANTIATING = {},
  3188. providerSuffix = 'Provider',
  3189. path = [],
  3190. loadedModules = new HashMap(),
  3191. providerCache = {
  3192. $provide: {
  3193. provider: supportObject(provider),
  3194. factory: supportObject(factory),
  3195. service: supportObject(service),
  3196. value: supportObject(value),
  3197. constant: supportObject(constant),
  3198. decorator: decorator
  3199. }
  3200. },
  3201. providerInjector = (providerCache.$injector =
  3202. createInternalInjector(providerCache, function() {
  3203. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3204. })),
  3205. instanceCache = {},
  3206. instanceInjector = (instanceCache.$injector =
  3207. createInternalInjector(instanceCache, function(servicename) {
  3208. var provider = providerInjector.get(servicename + providerSuffix);
  3209. return instanceInjector.invoke(provider.$get, provider);
  3210. }));
  3211. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3212. return instanceInjector;
  3213. ////////////////////////////////////
  3214. // $provider
  3215. ////////////////////////////////////
  3216. function supportObject(delegate) {
  3217. return function(key, value) {
  3218. if (isObject(key)) {
  3219. forEach(key, reverseParams(delegate));
  3220. } else {
  3221. return delegate(key, value);
  3222. }
  3223. };
  3224. }
  3225. function provider(name, provider_) {
  3226. assertNotHasOwnProperty(name, 'service');
  3227. if (isFunction(provider_) || isArray(provider_)) {
  3228. provider_ = providerInjector.instantiate(provider_);
  3229. }
  3230. if (!provider_.$get) {
  3231. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3232. }
  3233. return providerCache[name + providerSuffix] = provider_;
  3234. }
  3235. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
  3236. function service(name, constructor) {
  3237. return factory(name, ['$injector', function($injector) {
  3238. return $injector.instantiate(constructor);
  3239. }]);
  3240. }
  3241. function value(name, val) { return factory(name, valueFn(val)); }
  3242. function constant(name, value) {
  3243. assertNotHasOwnProperty(name, 'constant');
  3244. providerCache[name] = value;
  3245. instanceCache[name] = value;
  3246. }
  3247. function decorator(serviceName, decorFn) {
  3248. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3249. orig$get = origProvider.$get;
  3250. origProvider.$get = function() {
  3251. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3252. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3253. };
  3254. }
  3255. ////////////////////////////////////
  3256. // Module Loading
  3257. ////////////////////////////////////
  3258. function loadModules(modulesToLoad){
  3259. var runBlocks = [], moduleFn, invokeQueue, i, ii;
  3260. forEach(modulesToLoad, function(module) {
  3261. if (loadedModules.get(module)) return;
  3262. loadedModules.put(module, true);
  3263. try {
  3264. if (isString(module)) {
  3265. moduleFn = angularModule(module);
  3266. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3267. for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
  3268. var invokeArgs = invokeQueue[i],
  3269. provider = providerInjector.get(invokeArgs[0]);
  3270. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3271. }
  3272. } else if (isFunction(module)) {
  3273. runBlocks.push(providerInjector.invoke(module));
  3274. } else if (isArray(module)) {
  3275. runBlocks.push(providerInjector.invoke(module));
  3276. } else {
  3277. assertArgFn(module, 'module');
  3278. }
  3279. } catch (e) {
  3280. if (isArray(module)) {
  3281. module = module[module.length - 1];
  3282. }
  3283. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3284. // Safari & FF's stack traces don't contain error.message content
  3285. // unlike those of Chrome and IE
  3286. // So if stack doesn't contain message, we create a new string that contains both.
  3287. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3288. /* jshint -W022 */
  3289. e = e.message + '\n' + e.stack;
  3290. }
  3291. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3292. module, e.stack || e.message || e);
  3293. }
  3294. });
  3295. return runBlocks;
  3296. }
  3297. ////////////////////////////////////
  3298. // internal Injector
  3299. ////////////////////////////////////
  3300. function createInternalInjector(cache, factory) {
  3301. function getService(serviceName) {
  3302. if (cache.hasOwnProperty(serviceName)) {
  3303. if (cache[serviceName] === INSTANTIATING) {
  3304. throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- '));
  3305. }
  3306. return cache[serviceName];
  3307. } else {
  3308. try {
  3309. path.unshift(serviceName);
  3310. cache[serviceName] = INSTANTIATING;
  3311. return cache[serviceName] = factory(serviceName);
  3312. } catch (err) {
  3313. if (cache[serviceName] === INSTANTIATING) {
  3314. delete cache[serviceName];
  3315. }
  3316. throw err;
  3317. } finally {
  3318. path.shift();
  3319. }
  3320. }
  3321. }
  3322. function invoke(fn, self, locals){
  3323. var args = [],
  3324. $inject = annotate(fn),
  3325. length, i,
  3326. key;
  3327. for(i = 0, length = $inject.length; i < length; i++) {
  3328. key = $inject[i];
  3329. if (typeof key !== 'string') {
  3330. throw $injectorMinErr('itkn',
  3331. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3332. }
  3333. args.push(
  3334. locals && locals.hasOwnProperty(key)
  3335. ? locals[key]
  3336. : getService(key)
  3337. );
  3338. }
  3339. if (!fn.$inject) {
  3340. // this means that we must be an array.
  3341. fn = fn[length];
  3342. }
  3343. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3344. // #5388
  3345. return fn.apply(self, args);
  3346. }
  3347. function instantiate(Type, locals) {
  3348. var Constructor = function() {},
  3349. instance, returnedValue;
  3350. // Check if Type is annotated and use just the given function at n-1 as parameter
  3351. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3352. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3353. instance = new Constructor();
  3354. returnedValue = invoke(Type, instance, locals);
  3355. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3356. }
  3357. return {
  3358. invoke: invoke,
  3359. instantiate: instantiate,
  3360. get: getService,
  3361. annotate: annotate,
  3362. has: function(name) {
  3363. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3364. }
  3365. };
  3366. }
  3367. }
  3368. /**
  3369. * @ngdoc function
  3370. * @name ng.$anchorScroll
  3371. * @requires $window
  3372. * @requires $location
  3373. * @requires $rootScope
  3374. *
  3375. * @description
  3376. * When called, it checks current value of `$location.hash()` and scroll to related element,
  3377. * according to rules specified in
  3378. * {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
  3379. *
  3380. * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
  3381. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
  3382. *
  3383. * @example
  3384. <example>
  3385. <file name="index.html">
  3386. <div id="scrollArea" ng-controller="ScrollCtrl">
  3387. <a ng-click="gotoBottom()">Go to bottom</a>
  3388. <a id="bottom"></a> You're at the bottom!
  3389. </div>
  3390. </file>
  3391. <file name="script.js">
  3392. function ScrollCtrl($scope, $location, $anchorScroll) {
  3393. $scope.gotoBottom = function (){
  3394. // set the location.hash to the id of
  3395. // the element you wish to scroll to.
  3396. $location.hash('bottom');
  3397. // call $anchorScroll()
  3398. $anchorScroll();
  3399. }
  3400. }
  3401. </file>
  3402. <file name="style.css">
  3403. #scrollArea {
  3404. height: 350px;
  3405. overflow: auto;
  3406. }
  3407. #bottom {
  3408. display: block;
  3409. margin-top: 2000px;
  3410. }
  3411. </file>
  3412. </example>
  3413. */
  3414. function $AnchorScrollProvider() {
  3415. var autoScrollingEnabled = true;
  3416. this.disableAutoScrolling = function() {
  3417. autoScrollingEnabled = false;
  3418. };
  3419. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3420. var document = $window.document;
  3421. // helper function to get first anchor from a NodeList
  3422. // can't use filter.filter, as it accepts only instances of Array
  3423. // and IE can't convert NodeList to an array using [].slice
  3424. // TODO(vojta): use filter if we change it to accept lists as well
  3425. function getFirstAnchor(list) {
  3426. var result = null;
  3427. forEach(list, function(element) {
  3428. if (!result && lowercase(element.nodeName) === 'a') result = element;
  3429. });
  3430. return result;
  3431. }
  3432. function scroll() {
  3433. var hash = $location.hash(), elm;
  3434. // empty hash, scroll to the top of the page
  3435. if (!hash) $window.scrollTo(0, 0);
  3436. // element with given id
  3437. else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
  3438. // first anchor with given name :-D
  3439. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
  3440. // no element and hash == 'top', scroll to the top of the page
  3441. else if (hash === 'top') $window.scrollTo(0, 0);
  3442. }
  3443. // does not scroll when user clicks on anchor link that is currently on
  3444. // (no url change, no $location.hash() change), browser native does scroll
  3445. if (autoScrollingEnabled) {
  3446. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3447. function autoScrollWatchAction() {
  3448. $rootScope.$evalAsync(scroll);
  3449. });
  3450. }
  3451. return scroll;
  3452. }];
  3453. }
  3454. var $animateMinErr = minErr('$animate');
  3455. /**
  3456. * @ngdoc object
  3457. * @name ng.$animateProvider
  3458. *
  3459. * @description
  3460. * Default implementation of $animate that doesn't perform any animations, instead just
  3461. * synchronously performs DOM
  3462. * updates and calls done() callbacks.
  3463. *
  3464. * In order to enable animations the ngAnimate module has to be loaded.
  3465. *
  3466. * To see the functional implementation check out src/ngAnimate/animate.js
  3467. */
  3468. var $AnimateProvider = ['$provide', function($provide) {
  3469. this.$$selectors = {};
  3470. /**
  3471. * @ngdoc function
  3472. * @name ng.$animateProvider#register
  3473. * @methodOf ng.$animateProvider
  3474. *
  3475. * @description
  3476. * Registers a new injectable animation factory function. The factory function produces the
  3477. * animation object which contains callback functions for each event that is expected to be
  3478. * animated.
  3479. *
  3480. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3481. * must be called once the element animation is complete. If a function is returned then the
  3482. * animation service will use this function to cancel the animation whenever a cancel event is
  3483. * triggered.
  3484. *
  3485. *
  3486. *<pre>
  3487. * return {
  3488. * eventFn : function(element, done) {
  3489. * //code to run the animation
  3490. * //once complete, then run done()
  3491. * return function cancellationFunction() {
  3492. * //code to cancel the animation
  3493. * }
  3494. * }
  3495. * }
  3496. *</pre>
  3497. *
  3498. * @param {string} name The name of the animation.
  3499. * @param {function} factory The factory function that will be executed to return the animation
  3500. * object.
  3501. */
  3502. this.register = function(name, factory) {
  3503. var key = name + '-animation';
  3504. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  3505. "Expecting class selector starting with '.' got '{0}'.", name);
  3506. this.$$selectors[name.substr(1)] = key;
  3507. $provide.factory(key, factory);
  3508. };
  3509. /**
  3510. * @ngdoc function
  3511. * @name ng.$animateProvider#classNameFilter
  3512. * @methodOf ng.$animateProvider
  3513. *
  3514. * @description
  3515. * Sets and/or returns the CSS class regular expression that is checked when performing
  3516. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  3517. * therefore enable $animate to attempt to perform an animation on any element.
  3518. * When setting the classNameFilter value, animations will only be performed on elements
  3519. * that successfully match the filter expression. This in turn can boost performance
  3520. * for low-powered devices as well as applications containing a lot of structural operations.
  3521. * @param {RegExp=} expression The className expression which will be checked against all animations
  3522. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  3523. */
  3524. this.classNameFilter = function(expression) {
  3525. if(arguments.length === 1) {
  3526. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  3527. }
  3528. return this.$$classNameFilter;
  3529. };
  3530. this.$get = ['$timeout', function($timeout) {
  3531. /**
  3532. *
  3533. * @ngdoc object
  3534. * @name ng.$animate
  3535. * @description The $animate service provides rudimentary DOM manipulation functions to
  3536. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  3537. * This service is the core service used by the ngAnimate $animator service which provides
  3538. * high-level animation hooks for CSS and JavaScript.
  3539. *
  3540. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  3541. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  3542. * manipulation operations.
  3543. *
  3544. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  3545. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  3546. * page}.
  3547. */
  3548. return {
  3549. /**
  3550. *
  3551. * @ngdoc function
  3552. * @name ng.$animate#enter
  3553. * @methodOf ng.$animate
  3554. * @function
  3555. * @description Inserts the element into the DOM either after the `after` element or within
  3556. * the `parent` element. Once complete, the done() callback will be fired (if provided).
  3557. * @param {jQuery/jqLite element} element the element which will be inserted into the DOM
  3558. * @param {jQuery/jqLite element} parent the parent element which will append the element as
  3559. * a child (if the after element is not present)
  3560. * @param {jQuery/jqLite element} after the sibling element which will append the element
  3561. * after itself
  3562. * @param {function=} done callback function that will be called after the element has been
  3563. * inserted into the DOM
  3564. */
  3565. enter : function(element, parent, after, done) {
  3566. if (after) {
  3567. after.after(element);
  3568. } else {
  3569. if (!parent || !parent[0]) {
  3570. parent = after.parent();
  3571. }
  3572. parent.append(element);
  3573. }
  3574. done && $timeout(done, 0, false);
  3575. },
  3576. /**
  3577. *
  3578. * @ngdoc function
  3579. * @name ng.$animate#leave
  3580. * @methodOf ng.$animate
  3581. * @function
  3582. * @description Removes the element from the DOM. Once complete, the done() callback will be
  3583. * fired (if provided).
  3584. * @param {jQuery/jqLite element} element the element which will be removed from the DOM
  3585. * @param {function=} done callback function that will be called after the element has been
  3586. * removed from the DOM
  3587. */
  3588. leave : function(element, done) {
  3589. element.remove();
  3590. done && $timeout(done, 0, false);
  3591. },
  3592. /**
  3593. *
  3594. * @ngdoc function
  3595. * @name ng.$animate#move
  3596. * @methodOf ng.$animate
  3597. * @function
  3598. * @description Moves the position of the provided element within the DOM to be placed
  3599. * either after the `after` element or inside of the `parent` element. Once complete, the
  3600. * done() callback will be fired (if provided).
  3601. *
  3602. * @param {jQuery/jqLite element} element the element which will be moved around within the
  3603. * DOM
  3604. * @param {jQuery/jqLite element} parent the parent element where the element will be
  3605. * inserted into (if the after element is not present)
  3606. * @param {jQuery/jqLite element} after the sibling element where the element will be
  3607. * positioned next to
  3608. * @param {function=} done the callback function (if provided) that will be fired after the
  3609. * element has been moved to its new position
  3610. */
  3611. move : function(element, parent, after, done) {
  3612. // Do not remove element before insert. Removing will cause data associated with the
  3613. // element to be dropped. Insert will implicitly do the remove.
  3614. this.enter(element, parent, after, done);
  3615. },
  3616. /**
  3617. *
  3618. * @ngdoc function
  3619. * @name ng.$animate#addClass
  3620. * @methodOf ng.$animate
  3621. * @function
  3622. * @description Adds the provided className CSS class value to the provided element. Once
  3623. * complete, the done() callback will be fired (if provided).
  3624. * @param {jQuery/jqLite element} element the element which will have the className value
  3625. * added to it
  3626. * @param {string} className the CSS class which will be added to the element
  3627. * @param {function=} done the callback function (if provided) that will be fired after the
  3628. * className value has been added to the element
  3629. */
  3630. addClass : function(element, className, done) {
  3631. className = isString(className) ?
  3632. className :
  3633. isArray(className) ? className.join(' ') : '';
  3634. forEach(element, function (element) {
  3635. jqLiteAddClass(element, className);
  3636. });
  3637. done && $timeout(done, 0, false);
  3638. },
  3639. /**
  3640. *
  3641. * @ngdoc function
  3642. * @name ng.$animate#removeClass
  3643. * @methodOf ng.$animate
  3644. * @function
  3645. * @description Removes the provided className CSS class value from the provided element.
  3646. * Once complete, the done() callback will be fired (if provided).
  3647. * @param {jQuery/jqLite element} element the element which will have the className value
  3648. * removed from it
  3649. * @param {string} className the CSS class which will be removed from the element
  3650. * @param {function=} done the callback function (if provided) that will be fired after the
  3651. * className value has been removed from the element
  3652. */
  3653. removeClass : function(element, className, done) {
  3654. className = isString(className) ?
  3655. className :
  3656. isArray(className) ? className.join(' ') : '';
  3657. forEach(element, function (element) {
  3658. jqLiteRemoveClass(element, className);
  3659. });
  3660. done && $timeout(done, 0, false);
  3661. },
  3662. enabled : noop
  3663. };
  3664. }];
  3665. }];
  3666. /**
  3667. * ! This is a private undocumented service !
  3668. *
  3669. * @name ng.$browser
  3670. * @requires $log
  3671. * @description
  3672. * This object has two goals:
  3673. *
  3674. * - hide all the global state in the browser caused by the window object
  3675. * - abstract away all the browser specific features and inconsistencies
  3676. *
  3677. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  3678. * service, which can be used for convenient testing of the application without the interaction with
  3679. * the real browser apis.
  3680. */
  3681. /**
  3682. * @param {object} window The global window object.
  3683. * @param {object} document jQuery wrapped document.
  3684. * @param {function()} XHR XMLHttpRequest constructor.
  3685. * @param {object} $log console.log or an object with the same interface.
  3686. * @param {object} $sniffer $sniffer service
  3687. */
  3688. function Browser(window, document, $log, $sniffer) {
  3689. var self = this,
  3690. rawDocument = document[0],
  3691. location = window.location,
  3692. history = window.history,
  3693. setTimeout = window.setTimeout,
  3694. clearTimeout = window.clearTimeout,
  3695. pendingDeferIds = {};
  3696. self.isMock = false;
  3697. var outstandingRequestCount = 0;
  3698. var outstandingRequestCallbacks = [];
  3699. // TODO(vojta): remove this temporary api
  3700. self.$$completeOutstandingRequest = completeOutstandingRequest;
  3701. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  3702. /**
  3703. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  3704. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  3705. */
  3706. function completeOutstandingRequest(fn) {
  3707. try {
  3708. fn.apply(null, sliceArgs(arguments, 1));
  3709. } finally {
  3710. outstandingRequestCount--;
  3711. if (outstandingRequestCount === 0) {
  3712. while(outstandingRequestCallbacks.length) {
  3713. try {
  3714. outstandingRequestCallbacks.pop()();
  3715. } catch (e) {
  3716. $log.error(e);
  3717. }
  3718. }
  3719. }
  3720. }
  3721. }
  3722. /**
  3723. * @private
  3724. * Note: this method is used only by scenario runner
  3725. * TODO(vojta): prefix this method with $$ ?
  3726. * @param {function()} callback Function that will be called when no outstanding request
  3727. */
  3728. self.notifyWhenNoOutstandingRequests = function(callback) {
  3729. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  3730. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  3731. // regular poller would result in flaky tests.
  3732. forEach(pollFns, function(pollFn){ pollFn(); });
  3733. if (outstandingRequestCount === 0) {
  3734. callback();
  3735. } else {
  3736. outstandingRequestCallbacks.push(callback);
  3737. }
  3738. };
  3739. //////////////////////////////////////////////////////////////
  3740. // Poll Watcher API
  3741. //////////////////////////////////////////////////////////////
  3742. var pollFns = [],
  3743. pollTimeout;
  3744. /**
  3745. * @name ng.$browser#addPollFn
  3746. * @methodOf ng.$browser
  3747. *
  3748. * @param {function()} fn Poll function to add
  3749. *
  3750. * @description
  3751. * Adds a function to the list of functions that poller periodically executes,
  3752. * and starts polling if not started yet.
  3753. *
  3754. * @returns {function()} the added function
  3755. */
  3756. self.addPollFn = function(fn) {
  3757. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  3758. pollFns.push(fn);
  3759. return fn;
  3760. };
  3761. /**
  3762. * @param {number} interval How often should browser call poll functions (ms)
  3763. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  3764. *
  3765. * @description
  3766. * Configures the poller to run in the specified intervals, using the specified
  3767. * setTimeout fn and kicks it off.
  3768. */
  3769. function startPoller(interval, setTimeout) {
  3770. (function check() {
  3771. forEach(pollFns, function(pollFn){ pollFn(); });
  3772. pollTimeout = setTimeout(check, interval);
  3773. })();
  3774. }
  3775. //////////////////////////////////////////////////////////////
  3776. // URL API
  3777. //////////////////////////////////////////////////////////////
  3778. var lastBrowserUrl = location.href,
  3779. baseElement = document.find('base'),
  3780. newLocation = null;
  3781. /**
  3782. * @name ng.$browser#url
  3783. * @methodOf ng.$browser
  3784. *
  3785. * @description
  3786. * GETTER:
  3787. * Without any argument, this method just returns current value of location.href.
  3788. *
  3789. * SETTER:
  3790. * With at least one argument, this method sets url to new value.
  3791. * If html5 history api supported, pushState/replaceState is used, otherwise
  3792. * location.href/location.replace is used.
  3793. * Returns its own instance to allow chaining
  3794. *
  3795. * NOTE: this api is intended for use only by the $location service. Please use the
  3796. * {@link ng.$location $location service} to change url.
  3797. *
  3798. * @param {string} url New url (when used as setter)
  3799. * @param {boolean=} replace Should new url replace current history record ?
  3800. */
  3801. self.url = function(url, replace) {
  3802. // Android Browser BFCache causes location, history reference to become stale.
  3803. if (location !== window.location) location = window.location;
  3804. if (history !== window.history) history = window.history;
  3805. // setter
  3806. if (url) {
  3807. if (lastBrowserUrl == url) return;
  3808. lastBrowserUrl = url;
  3809. if ($sniffer.history) {
  3810. if (replace) history.replaceState(null, '', url);
  3811. else {
  3812. history.pushState(null, '', url);
  3813. // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
  3814. baseElement.attr('href', baseElement.attr('href'));
  3815. }
  3816. } else {
  3817. newLocation = url;
  3818. if (replace) {
  3819. location.replace(url);
  3820. } else {
  3821. location.href = url;
  3822. }
  3823. }
  3824. return self;
  3825. // getter
  3826. } else {
  3827. // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
  3828. // methods not updating location.href synchronously.
  3829. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  3830. return newLocation || location.href.replace(/%27/g,"'");
  3831. }
  3832. };
  3833. var urlChangeListeners = [],
  3834. urlChangeInit = false;
  3835. function fireUrlChange() {
  3836. newLocation = null;
  3837. if (lastBrowserUrl == self.url()) return;
  3838. lastBrowserUrl = self.url();
  3839. forEach(urlChangeListeners, function(listener) {
  3840. listener(self.url());
  3841. });
  3842. }
  3843. /**
  3844. * @name ng.$browser#onUrlChange
  3845. * @methodOf ng.$browser
  3846. * @TODO(vojta): refactor to use node's syntax for events
  3847. *
  3848. * @description
  3849. * Register callback function that will be called, when url changes.
  3850. *
  3851. * It's only called when the url is changed from outside of angular:
  3852. * - user types different url into address bar
  3853. * - user clicks on history (forward/back) button
  3854. * - user clicks on a link
  3855. *
  3856. * It's not called when url is changed by $browser.url() method
  3857. *
  3858. * The listener gets called with new url as parameter.
  3859. *
  3860. * NOTE: this api is intended for use only by the $location service. Please use the
  3861. * {@link ng.$location $location service} to monitor url changes in angular apps.
  3862. *
  3863. * @param {function(string)} listener Listener function to be called when url changes.
  3864. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  3865. */
  3866. self.onUrlChange = function(callback) {
  3867. if (!urlChangeInit) {
  3868. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  3869. // don't fire popstate when user change the address bar and don't fire hashchange when url
  3870. // changed by push/replaceState
  3871. // html5 history api - popstate event
  3872. if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
  3873. // hashchange event
  3874. if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
  3875. // polling
  3876. else self.addPollFn(fireUrlChange);
  3877. urlChangeInit = true;
  3878. }
  3879. urlChangeListeners.push(callback);
  3880. return callback;
  3881. };
  3882. //////////////////////////////////////////////////////////////
  3883. // Misc API
  3884. //////////////////////////////////////////////////////////////
  3885. /**
  3886. * @name ng.$browser#baseHref
  3887. * @methodOf ng.$browser
  3888. *
  3889. * @description
  3890. * Returns current <base href>
  3891. * (always relative - without domain)
  3892. *
  3893. * @returns {string=} current <base href>
  3894. */
  3895. self.baseHref = function() {
  3896. var href = baseElement.attr('href');
  3897. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  3898. };
  3899. //////////////////////////////////////////////////////////////
  3900. // Cookies API
  3901. //////////////////////////////////////////////////////////////
  3902. var lastCookies = {};
  3903. var lastCookieString = '';
  3904. var cookiePath = self.baseHref();
  3905. /**
  3906. * @name ng.$browser#cookies
  3907. * @methodOf ng.$browser
  3908. *
  3909. * @param {string=} name Cookie name
  3910. * @param {string=} value Cookie value
  3911. *
  3912. * @description
  3913. * The cookies method provides a 'private' low level access to browser cookies.
  3914. * It is not meant to be used directly, use the $cookie service instead.
  3915. *
  3916. * The return values vary depending on the arguments that the method was called with as follows:
  3917. *
  3918. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  3919. * it
  3920. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  3921. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  3922. * way)
  3923. *
  3924. * @returns {Object} Hash of all cookies (if called without any parameter)
  3925. */
  3926. self.cookies = function(name, value) {
  3927. /* global escape: false, unescape: false */
  3928. var cookieLength, cookieArray, cookie, i, index;
  3929. if (name) {
  3930. if (value === undefined) {
  3931. rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
  3932. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  3933. } else {
  3934. if (isString(value)) {
  3935. cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
  3936. ';path=' + cookiePath).length + 1;
  3937. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  3938. // - 300 cookies
  3939. // - 20 cookies per unique domain
  3940. // - 4096 bytes per cookie
  3941. if (cookieLength > 4096) {
  3942. $log.warn("Cookie '"+ name +
  3943. "' possibly not set or overflowed because it was too large ("+
  3944. cookieLength + " > 4096 bytes)!");
  3945. }
  3946. }
  3947. }
  3948. } else {
  3949. if (rawDocument.cookie !== lastCookieString) {
  3950. lastCookieString = rawDocument.cookie;
  3951. cookieArray = lastCookieString.split("; ");
  3952. lastCookies = {};
  3953. for (i = 0; i < cookieArray.length; i++) {
  3954. cookie = cookieArray[i];
  3955. index = cookie.indexOf('=');
  3956. if (index > 0) { //ignore nameless cookies
  3957. name = unescape(cookie.substring(0, index));
  3958. // the first value that is seen for a cookie is the most
  3959. // specific one. values for the same cookie name that
  3960. // follow are for less specific paths.
  3961. if (lastCookies[name] === undefined) {
  3962. lastCookies[name] = unescape(cookie.substring(index + 1));
  3963. }
  3964. }
  3965. }
  3966. }
  3967. return lastCookies;
  3968. }
  3969. };
  3970. /**
  3971. * @name ng.$browser#defer
  3972. * @methodOf ng.$browser
  3973. * @param {function()} fn A function, who's execution should be deferred.
  3974. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  3975. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  3976. *
  3977. * @description
  3978. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  3979. *
  3980. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  3981. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  3982. * via `$browser.defer.flush()`.
  3983. *
  3984. */
  3985. self.defer = function(fn, delay) {
  3986. var timeoutId;
  3987. outstandingRequestCount++;
  3988. timeoutId = setTimeout(function() {
  3989. delete pendingDeferIds[timeoutId];
  3990. completeOutstandingRequest(fn);
  3991. }, delay || 0);
  3992. pendingDeferIds[timeoutId] = true;
  3993. return timeoutId;
  3994. };
  3995. /**
  3996. * @name ng.$browser#defer.cancel
  3997. * @methodOf ng.$browser.defer
  3998. *
  3999. * @description
  4000. * Cancels a deferred task identified with `deferId`.
  4001. *
  4002. * @param {*} deferId Token returned by the `$browser.defer` function.
  4003. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4004. * canceled.
  4005. */
  4006. self.defer.cancel = function(deferId) {
  4007. if (pendingDeferIds[deferId]) {
  4008. delete pendingDeferIds[deferId];
  4009. clearTimeout(deferId);
  4010. completeOutstandingRequest(noop);
  4011. return true;
  4012. }
  4013. return false;
  4014. };
  4015. }
  4016. function $BrowserProvider(){
  4017. this.$get = ['$window', '$log', '$sniffer', '$document',
  4018. function( $window, $log, $sniffer, $document){
  4019. return new Browser($window, $document, $log, $sniffer);
  4020. }];
  4021. }
  4022. /**
  4023. * @ngdoc object
  4024. * @name ng.$cacheFactory
  4025. *
  4026. * @description
  4027. * Factory that constructs cache objects and gives access to them.
  4028. *
  4029. * <pre>
  4030. *
  4031. * var cache = $cacheFactory('cacheId');
  4032. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4033. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4034. *
  4035. * cache.put("key", "value");
  4036. * cache.put("another key", "another value");
  4037. *
  4038. * // We've specified no options on creation
  4039. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4040. *
  4041. * </pre>
  4042. *
  4043. *
  4044. * @param {string} cacheId Name or id of the newly created cache.
  4045. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4046. *
  4047. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4048. *
  4049. * @returns {object} Newly created cache object with the following set of methods:
  4050. *
  4051. * - `{object}` `info()` — Returns id, size, and options of cache.
  4052. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4053. * it.
  4054. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4055. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4056. * - `{void}` `removeAll()` — Removes all cached values.
  4057. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4058. *
  4059. */
  4060. function $CacheFactoryProvider() {
  4061. this.$get = function() {
  4062. var caches = {};
  4063. function cacheFactory(cacheId, options) {
  4064. if (cacheId in caches) {
  4065. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4066. }
  4067. var size = 0,
  4068. stats = extend({}, options, {id: cacheId}),
  4069. data = {},
  4070. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4071. lruHash = {},
  4072. freshEnd = null,
  4073. staleEnd = null;
  4074. return caches[cacheId] = {
  4075. put: function(key, value) {
  4076. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4077. refresh(lruEntry);
  4078. if (isUndefined(value)) return;
  4079. if (!(key in data)) size++;
  4080. data[key] = value;
  4081. if (size > capacity) {
  4082. this.remove(staleEnd.key);
  4083. }
  4084. return value;
  4085. },
  4086. get: function(key) {
  4087. var lruEntry = lruHash[key];
  4088. if (!lruEntry) return;
  4089. refresh(lruEntry);
  4090. return data[key];
  4091. },
  4092. remove: function(key) {
  4093. var lruEntry = lruHash[key];
  4094. if (!lruEntry) return;
  4095. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4096. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4097. link(lruEntry.n,lruEntry.p);
  4098. delete lruHash[key];
  4099. delete data[key];
  4100. size--;
  4101. },
  4102. removeAll: function() {
  4103. data = {};
  4104. size = 0;
  4105. lruHash = {};
  4106. freshEnd = staleEnd = null;
  4107. },
  4108. destroy: function() {
  4109. data = null;
  4110. stats = null;
  4111. lruHash = null;
  4112. delete caches[cacheId];
  4113. },
  4114. info: function() {
  4115. return extend({}, stats, {size: size});
  4116. }
  4117. };
  4118. /**
  4119. * makes the `entry` the freshEnd of the LRU linked list
  4120. */
  4121. function refresh(entry) {
  4122. if (entry != freshEnd) {
  4123. if (!staleEnd) {
  4124. staleEnd = entry;
  4125. } else if (staleEnd == entry) {
  4126. staleEnd = entry.n;
  4127. }
  4128. link(entry.n, entry.p);
  4129. link(entry, freshEnd);
  4130. freshEnd = entry;
  4131. freshEnd.n = null;
  4132. }
  4133. }
  4134. /**
  4135. * bidirectionally links two entries of the LRU linked list
  4136. */
  4137. function link(nextEntry, prevEntry) {
  4138. if (nextEntry != prevEntry) {
  4139. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4140. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4141. }
  4142. }
  4143. }
  4144. /**
  4145. * @ngdoc method
  4146. * @name ng.$cacheFactory#info
  4147. * @methodOf ng.$cacheFactory
  4148. *
  4149. * @description
  4150. * Get information about all the of the caches that have been created
  4151. *
  4152. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  4153. */
  4154. cacheFactory.info = function() {
  4155. var info = {};
  4156. forEach(caches, function(cache, cacheId) {
  4157. info[cacheId] = cache.info();
  4158. });
  4159. return info;
  4160. };
  4161. /**
  4162. * @ngdoc method
  4163. * @name ng.$cacheFactory#get
  4164. * @methodOf ng.$cacheFactory
  4165. *
  4166. * @description
  4167. * Get access to a cache object by the `cacheId` used when it was created.
  4168. *
  4169. * @param {string} cacheId Name or id of a cache to access.
  4170. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  4171. */
  4172. cacheFactory.get = function(cacheId) {
  4173. return caches[cacheId];
  4174. };
  4175. return cacheFactory;
  4176. };
  4177. }
  4178. /**
  4179. * @ngdoc object
  4180. * @name ng.$templateCache
  4181. *
  4182. * @description
  4183. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  4184. * can load templates directly into the cache in a `script` tag, or by consuming the
  4185. * `$templateCache` service directly.
  4186. *
  4187. * Adding via the `script` tag:
  4188. * <pre>
  4189. * <html ng-app>
  4190. * <head>
  4191. * <script type="text/ng-template" id="templateId.html">
  4192. * This is the content of the template
  4193. * </script>
  4194. * </head>
  4195. * ...
  4196. * </html>
  4197. * </pre>
  4198. *
  4199. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  4200. * the document, but it must be below the `ng-app` definition.
  4201. *
  4202. * Adding via the $templateCache service:
  4203. *
  4204. * <pre>
  4205. * var myApp = angular.module('myApp', []);
  4206. * myApp.run(function($templateCache) {
  4207. * $templateCache.put('templateId.html', 'This is the content of the template');
  4208. * });
  4209. * </pre>
  4210. *
  4211. * To retrieve the template later, simply use it in your HTML:
  4212. * <pre>
  4213. * <div ng-include=" 'templateId.html' "></div>
  4214. * </pre>
  4215. *
  4216. * or get it via Javascript:
  4217. * <pre>
  4218. * $templateCache.get('templateId.html')
  4219. * </pre>
  4220. *
  4221. * See {@link ng.$cacheFactory $cacheFactory}.
  4222. *
  4223. */
  4224. function $TemplateCacheProvider() {
  4225. this.$get = ['$cacheFactory', function($cacheFactory) {
  4226. return $cacheFactory('templates');
  4227. }];
  4228. }
  4229. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  4230. *
  4231. * DOM-related variables:
  4232. *
  4233. * - "node" - DOM Node
  4234. * - "element" - DOM Element or Node
  4235. * - "$node" or "$element" - jqLite-wrapped node or element
  4236. *
  4237. *
  4238. * Compiler related stuff:
  4239. *
  4240. * - "linkFn" - linking fn of a single directive
  4241. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  4242. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  4243. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  4244. */
  4245. /**
  4246. * @ngdoc function
  4247. * @name ng.$compile
  4248. * @function
  4249. *
  4250. * @description
  4251. * Compiles an HTML string or DOM into a template and produces a template function, which
  4252. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  4253. *
  4254. * The compilation is a process of walking the DOM tree and matching DOM elements to
  4255. * {@link ng.$compileProvider#methods_directive directives}.
  4256. *
  4257. * <div class="alert alert-warning">
  4258. * **Note:** This document is an in-depth reference of all directive options.
  4259. * For a gentle introduction to directives with examples of common use cases,
  4260. * see the {@link guide/directive directive guide}.
  4261. * </div>
  4262. *
  4263. * ## Comprehensive Directive API
  4264. *
  4265. * There are many different options for a directive.
  4266. *
  4267. * The difference resides in the return value of the factory function.
  4268. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  4269. * or just the `postLink` function (all other properties will have the default values).
  4270. *
  4271. * <div class="alert alert-success">
  4272. * **Best Practice:** It's recommended to use the "directive definition object" form.
  4273. * </div>
  4274. *
  4275. * Here's an example directive declared with a Directive Definition Object:
  4276. *
  4277. * <pre>
  4278. * var myModule = angular.module(...);
  4279. *
  4280. * myModule.directive('directiveName', function factory(injectables) {
  4281. * var directiveDefinitionObject = {
  4282. * priority: 0,
  4283. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  4284. * // or
  4285. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  4286. * replace: false,
  4287. * transclude: false,
  4288. * restrict: 'A',
  4289. * scope: false,
  4290. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  4291. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  4292. * compile: function compile(tElement, tAttrs, transclude) {
  4293. * return {
  4294. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4295. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4296. * }
  4297. * // or
  4298. * // return function postLink( ... ) { ... }
  4299. * },
  4300. * // or
  4301. * // link: {
  4302. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4303. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4304. * // }
  4305. * // or
  4306. * // link: function postLink( ... ) { ... }
  4307. * };
  4308. * return directiveDefinitionObject;
  4309. * });
  4310. * </pre>
  4311. *
  4312. * <div class="alert alert-warning">
  4313. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  4314. * </div>
  4315. *
  4316. * Therefore the above can be simplified as:
  4317. *
  4318. * <pre>
  4319. * var myModule = angular.module(...);
  4320. *
  4321. * myModule.directive('directiveName', function factory(injectables) {
  4322. * var directiveDefinitionObject = {
  4323. * link: function postLink(scope, iElement, iAttrs) { ... }
  4324. * };
  4325. * return directiveDefinitionObject;
  4326. * // or
  4327. * // return function postLink(scope, iElement, iAttrs) { ... }
  4328. * });
  4329. * </pre>
  4330. *
  4331. *
  4332. *
  4333. * ### Directive Definition Object
  4334. *
  4335. * The directive definition object provides instructions to the {@link api/ng.$compile
  4336. * compiler}. The attributes are:
  4337. *
  4338. * #### `priority`
  4339. * When there are multiple directives defined on a single DOM element, sometimes it
  4340. * is necessary to specify the order in which the directives are applied. The `priority` is used
  4341. * to sort the directives before their `compile` functions get called. Priority is defined as a
  4342. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  4343. * are also run in priority order, but post-link functions are run in reverse order. The order
  4344. * of directives with the same priority is undefined. The default priority is `0`.
  4345. *
  4346. * #### `terminal`
  4347. * If set to true then the current `priority` will be the last set of directives
  4348. * which will execute (any directives at the current priority will still execute
  4349. * as the order of execution on same `priority` is undefined).
  4350. *
  4351. * #### `scope`
  4352. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  4353. * same element request a new scope, only one new scope is created. The new scope rule does not
  4354. * apply for the root of the template since the root of the template always gets a new scope.
  4355. *
  4356. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  4357. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  4358. * when creating reusable components, which should not accidentally read or modify data in the
  4359. * parent scope.
  4360. *
  4361. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  4362. * derived from the parent scope. These local properties are useful for aliasing values for
  4363. * templates. Locals definition is a hash of local scope property to its source:
  4364. *
  4365. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  4366. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  4367. * attribute name is assumed to be the same as the local name.
  4368. * Given `<widget my-attr="hello {{name}}">` and widget definition
  4369. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  4370. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  4371. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  4372. * component scope).
  4373. *
  4374. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  4375. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  4376. * name is specified then the attribute name is assumed to be the same as the local name.
  4377. * Given `<widget my-attr="parentModel">` and widget definition of
  4378. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  4379. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  4380. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  4381. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  4382. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  4383. *
  4384. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  4385. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  4386. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  4387. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  4388. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  4389. * pass data from the isolated scope via an expression and to the parent scope, this can be
  4390. * done by passing a map of local variable names and values into the expression wrapper fn.
  4391. * For example, if the expression is `increment(amount)` then we can specify the amount value
  4392. * by calling the `localFn` as `localFn({amount: 22})`.
  4393. *
  4394. *
  4395. *
  4396. * #### `controller`
  4397. * Controller constructor function. The controller is instantiated before the
  4398. * pre-linking phase and it is shared with other directives (see
  4399. * `require` attribute). This allows the directives to communicate with each other and augment
  4400. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  4401. *
  4402. * * `$scope` - Current scope associated with the element
  4403. * * `$element` - Current element
  4404. * * `$attrs` - Current attributes object for the element
  4405. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  4406. * The scope can be overridden by an optional first argument.
  4407. * `function([scope], cloneLinkingFn)`.
  4408. *
  4409. *
  4410. * #### `require`
  4411. * Require another directive and inject its controller as the fourth argument to the linking function. The
  4412. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  4413. * injected argument will be an array in corresponding order. If no such directive can be
  4414. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  4415. *
  4416. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  4417. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  4418. * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  4419. * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
  4420. * `link` fn if not found.
  4421. *
  4422. *
  4423. * #### `controllerAs`
  4424. * Controller alias at the directive scope. An alias for the controller so it
  4425. * can be referenced at the directive template. The directive needs to define a scope for this
  4426. * configuration to be used. Useful in the case when directive is used as component.
  4427. *
  4428. *
  4429. * #### `restrict`
  4430. * String of subset of `EACM` which restricts the directive to a specific directive
  4431. * declaration style. If omitted, the default (attributes only) is used.
  4432. *
  4433. * * `E` - Element name: `<my-directive></my-directive>`
  4434. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  4435. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  4436. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  4437. *
  4438. *
  4439. * #### `template`
  4440. * replace the current element with the contents of the HTML. The replacement process
  4441. * migrates all of the attributes / classes from the old element to the new one. See the
  4442. * {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  4443. * Directives Guide} for an example.
  4444. *
  4445. * You can specify `template` as a string representing the template or as a function which takes
  4446. * two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
  4447. * returns a string value representing the template.
  4448. *
  4449. *
  4450. * #### `templateUrl`
  4451. * Same as `template` but the template is loaded from the specified URL. Because
  4452. * the template loading is asynchronous the compilation/linking is suspended until the template
  4453. * is loaded.
  4454. *
  4455. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  4456. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  4457. * a string value representing the url. In either case, the template URL is passed through {@link
  4458. * api/ng.$sce#methods_getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  4459. *
  4460. *
  4461. * #### `replace`
  4462. * specify where the template should be inserted. Defaults to `false`.
  4463. *
  4464. * * `true` - the template will replace the current element.
  4465. * * `false` - the template will replace the contents of the current element.
  4466. *
  4467. *
  4468. * #### `transclude`
  4469. * compile the content of the element and make it available to the directive.
  4470. * Typically used with {@link api/ng.directive:ngTransclude
  4471. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  4472. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  4473. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  4474. * scope. This makes it possible for the widget to have private state, and the transclusion to
  4475. * be bound to the parent (pre-`isolate`) scope.
  4476. *
  4477. * * `true` - transclude the content of the directive.
  4478. * * `'element'` - transclude the whole element including any directives defined at lower priority.
  4479. *
  4480. *
  4481. * #### `compile`
  4482. *
  4483. * <pre>
  4484. * function compile(tElement, tAttrs, transclude) { ... }
  4485. * </pre>
  4486. *
  4487. * The compile function deals with transforming the template DOM. Since most directives do not do
  4488. * template transformation, it is not used often. Examples that require compile functions are
  4489. * directives that transform template DOM, such as {@link
  4490. * api/ng.directive:ngRepeat ngRepeat}, or load the contents
  4491. * asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The
  4492. * compile function takes the following arguments.
  4493. *
  4494. * * `tElement` - template element - The element where the directive has been declared. It is
  4495. * safe to do template transformation on the element and child elements only.
  4496. *
  4497. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  4498. * between all directive compile functions.
  4499. *
  4500. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  4501. *
  4502. * <div class="alert alert-warning">
  4503. * **Note:** The template instance and the link instance may be different objects if the template has
  4504. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  4505. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  4506. * should be done in a linking function rather than in a compile function.
  4507. * </div>
  4508. *
  4509. * <div class="alert alert-error">
  4510. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  4511. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  4512. * to the link function instead.
  4513. * </div>
  4514. * A compile function can have a return value which can be either a function or an object.
  4515. *
  4516. * * returning a (post-link) function - is equivalent to registering the linking function via the
  4517. * `link` property of the config object when the compile function is empty.
  4518. *
  4519. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  4520. * control when a linking function should be called during the linking phase. See info about
  4521. * pre-linking and post-linking functions below.
  4522. *
  4523. *
  4524. * #### `link`
  4525. * This property is used only if the `compile` property is not defined.
  4526. *
  4527. * <pre>
  4528. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  4529. * </pre>
  4530. *
  4531. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  4532. * executed after the template has been cloned. This is where most of the directive logic will be
  4533. * put.
  4534. *
  4535. * * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the
  4536. * directive for registering {@link api/ng.$rootScope.Scope#methods_$watch watches}.
  4537. *
  4538. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  4539. * manipulate the children of the element only in `postLink` function since the children have
  4540. * already been linked.
  4541. *
  4542. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  4543. * between all directive linking functions.
  4544. *
  4545. * * `controller` - a controller instance - A controller instance if at least one directive on the
  4546. * element defines a controller. The controller is shared among all the directives, which allows
  4547. * the directives to use the controllers as a communication channel.
  4548. *
  4549. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  4550. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  4551. * parameter of directive controllers.
  4552. * `function([scope], cloneLinkingFn)`.
  4553. *
  4554. *
  4555. * #### Pre-linking function
  4556. *
  4557. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  4558. * compiler linking function will fail to locate the correct elements for linking.
  4559. *
  4560. * #### Post-linking function
  4561. *
  4562. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  4563. *
  4564. * <a name="Attributes"></a>
  4565. * ### Attributes
  4566. *
  4567. * The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  4568. * `link()` or `compile()` functions. It has a variety of uses.
  4569. *
  4570. * accessing *Normalized attribute names:*
  4571. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  4572. * the attributes object allows for normalized access to
  4573. * the attributes.
  4574. *
  4575. * * *Directive inter-communication:* All directives share the same instance of the attributes
  4576. * object which allows the directives to use the attributes object as inter directive
  4577. * communication.
  4578. *
  4579. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  4580. * allowing other directives to read the interpolated value.
  4581. *
  4582. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  4583. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  4584. * the only way to easily get the actual value because during the linking phase the interpolation
  4585. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  4586. *
  4587. * <pre>
  4588. * function linkingFn(scope, elm, attrs, ctrl) {
  4589. * // get the attribute value
  4590. * console.log(attrs.ngModel);
  4591. *
  4592. * // change the attribute
  4593. * attrs.$set('ngModel', 'new value');
  4594. *
  4595. * // observe changes to interpolated attribute
  4596. * attrs.$observe('ngModel', function(value) {
  4597. * console.log('ngModel has changed value to ' + value);
  4598. * });
  4599. * }
  4600. * </pre>
  4601. *
  4602. * Below is an example using `$compileProvider`.
  4603. *
  4604. * <div class="alert alert-warning">
  4605. * **Note**: Typically directives are registered with `module.directive`. The example below is
  4606. * to illustrate how `$compile` works.
  4607. * </div>
  4608. *
  4609. <doc:example module="compile">
  4610. <doc:source>
  4611. <script>
  4612. angular.module('compile', [], function($compileProvider) {
  4613. // configure new 'compile' directive by passing a directive
  4614. // factory function. The factory function injects the '$compile'
  4615. $compileProvider.directive('compile', function($compile) {
  4616. // directive factory creates a link function
  4617. return function(scope, element, attrs) {
  4618. scope.$watch(
  4619. function(scope) {
  4620. // watch the 'compile' expression for changes
  4621. return scope.$eval(attrs.compile);
  4622. },
  4623. function(value) {
  4624. // when the 'compile' expression changes
  4625. // assign it into the current DOM
  4626. element.html(value);
  4627. // compile the new DOM and link it to the current
  4628. // scope.
  4629. // NOTE: we only compile .childNodes so that
  4630. // we don't get into infinite loop compiling ourselves
  4631. $compile(element.contents())(scope);
  4632. }
  4633. );
  4634. };
  4635. })
  4636. });
  4637. function Ctrl($scope) {
  4638. $scope.name = 'Angular';
  4639. $scope.html = 'Hello {{name}}';
  4640. }
  4641. </script>
  4642. <div ng-controller="Ctrl">
  4643. <input ng-model="name"> <br>
  4644. <textarea ng-model="html"></textarea> <br>
  4645. <div compile="html"></div>
  4646. </div>
  4647. </doc:source>
  4648. <doc:scenario>
  4649. it('should auto compile', function() {
  4650. expect(element('div[compile]').text()).toBe('Hello Angular');
  4651. input('html').enter('{{name}}!');
  4652. expect(element('div[compile]').text()).toBe('Angular!');
  4653. });
  4654. </doc:scenario>
  4655. </doc:example>
  4656. *
  4657. *
  4658. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  4659. * @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
  4660. * @param {number} maxPriority only apply directives lower then given priority (Only effects the
  4661. * root element(s), not their children)
  4662. * @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
  4663. * (a DOM element/tree) to a scope. Where:
  4664. *
  4665. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  4666. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  4667. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  4668. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  4669. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  4670. *
  4671. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  4672. * * `scope` - is the current scope with which the linking function is working with.
  4673. *
  4674. * Calling the linking function returns the element of the template. It is either the original
  4675. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  4676. *
  4677. * After linking the view is not updated until after a call to $digest which typically is done by
  4678. * Angular automatically.
  4679. *
  4680. * If you need access to the bound view, there are two ways to do it:
  4681. *
  4682. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  4683. * before you send them to the compiler and keep this reference around.
  4684. * <pre>
  4685. * var element = $compile('<p>{{total}}</p>')(scope);
  4686. * </pre>
  4687. *
  4688. * - if on the other hand, you need the element to be cloned, the view reference from the original
  4689. * example would not point to the clone, but rather to the original template that was cloned. In
  4690. * this case, you can access the clone via the cloneAttachFn:
  4691. * <pre>
  4692. * var templateElement = angular.element('<p>{{total}}</p>'),
  4693. * scope = ....;
  4694. *
  4695. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  4696. * //attach the clone to DOM document at the right place
  4697. * });
  4698. *
  4699. * //now we have reference to the cloned DOM via `clonedElement`
  4700. * </pre>
  4701. *
  4702. *
  4703. * For information on how the compiler works, see the
  4704. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  4705. */
  4706. var $compileMinErr = minErr('$compile');
  4707. /**
  4708. * @ngdoc service
  4709. * @name ng.$compileProvider
  4710. * @function
  4711. *
  4712. * @description
  4713. */
  4714. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  4715. function $CompileProvider($provide, $$sanitizeUriProvider) {
  4716. var hasDirectives = {},
  4717. Suffix = 'Directive',
  4718. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
  4719. CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/;
  4720. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  4721. // The assumption is that future DOM event attribute names will begin with
  4722. // 'on' and be composed of only English letters.
  4723. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  4724. /**
  4725. * @ngdoc function
  4726. * @name ng.$compileProvider#directive
  4727. * @methodOf ng.$compileProvider
  4728. * @function
  4729. *
  4730. * @description
  4731. * Register a new directive with the compiler.
  4732. *
  4733. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  4734. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  4735. * names and the values are the factories.
  4736. * @param {function|Array} directiveFactory An injectable directive factory function. See
  4737. * {@link guide/directive} for more info.
  4738. * @returns {ng.$compileProvider} Self for chaining.
  4739. */
  4740. this.directive = function registerDirective(name, directiveFactory) {
  4741. assertNotHasOwnProperty(name, 'directive');
  4742. if (isString(name)) {
  4743. assertArg(directiveFactory, 'directiveFactory');
  4744. if (!hasDirectives.hasOwnProperty(name)) {
  4745. hasDirectives[name] = [];
  4746. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  4747. function($injector, $exceptionHandler) {
  4748. var directives = [];
  4749. forEach(hasDirectives[name], function(directiveFactory, index) {
  4750. try {
  4751. var directive = $injector.invoke(directiveFactory);
  4752. if (isFunction(directive)) {
  4753. directive = { compile: valueFn(directive) };
  4754. } else if (!directive.compile && directive.link) {
  4755. directive.compile = valueFn(directive.link);
  4756. }
  4757. directive.priority = directive.priority || 0;
  4758. directive.index = index;
  4759. directive.name = directive.name || name;
  4760. directive.require = directive.require || (directive.controller && directive.name);
  4761. directive.restrict = directive.restrict || 'A';
  4762. directives.push(directive);
  4763. } catch (e) {
  4764. $exceptionHandler(e);
  4765. }
  4766. });
  4767. return directives;
  4768. }]);
  4769. }
  4770. hasDirectives[name].push(directiveFactory);
  4771. } else {
  4772. forEach(name, reverseParams(registerDirective));
  4773. }
  4774. return this;
  4775. };
  4776. /**
  4777. * @ngdoc function
  4778. * @name ng.$compileProvider#aHrefSanitizationWhitelist
  4779. * @methodOf ng.$compileProvider
  4780. * @function
  4781. *
  4782. * @description
  4783. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  4784. * urls during a[href] sanitization.
  4785. *
  4786. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  4787. *
  4788. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  4789. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  4790. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  4791. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  4792. *
  4793. * @param {RegExp=} regexp New regexp to whitelist urls with.
  4794. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  4795. * chaining otherwise.
  4796. */
  4797. this.aHrefSanitizationWhitelist = function(regexp) {
  4798. if (isDefined(regexp)) {
  4799. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  4800. return this;
  4801. } else {
  4802. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  4803. }
  4804. };
  4805. /**
  4806. * @ngdoc function
  4807. * @name ng.$compileProvider#imgSrcSanitizationWhitelist
  4808. * @methodOf ng.$compileProvider
  4809. * @function
  4810. *
  4811. * @description
  4812. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  4813. * urls during img[src] sanitization.
  4814. *
  4815. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  4816. *
  4817. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  4818. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  4819. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  4820. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  4821. *
  4822. * @param {RegExp=} regexp New regexp to whitelist urls with.
  4823. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  4824. * chaining otherwise.
  4825. */
  4826. this.imgSrcSanitizationWhitelist = function(regexp) {
  4827. if (isDefined(regexp)) {
  4828. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  4829. return this;
  4830. } else {
  4831. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  4832. }
  4833. };
  4834. this.$get = [
  4835. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  4836. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  4837. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  4838. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  4839. var Attributes = function(element, attr) {
  4840. this.$$element = element;
  4841. this.$attr = attr || {};
  4842. };
  4843. Attributes.prototype = {
  4844. $normalize: directiveNormalize,
  4845. /**
  4846. * @ngdoc function
  4847. * @name ng.$compile.directive.Attributes#$addClass
  4848. * @methodOf ng.$compile.directive.Attributes
  4849. * @function
  4850. *
  4851. * @description
  4852. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  4853. * are enabled then an animation will be triggered for the class addition.
  4854. *
  4855. * @param {string} classVal The className value that will be added to the element
  4856. */
  4857. $addClass : function(classVal) {
  4858. if(classVal && classVal.length > 0) {
  4859. $animate.addClass(this.$$element, classVal);
  4860. }
  4861. },
  4862. /**
  4863. * @ngdoc function
  4864. * @name ng.$compile.directive.Attributes#$removeClass
  4865. * @methodOf ng.$compile.directive.Attributes
  4866. * @function
  4867. *
  4868. * @description
  4869. * Removes the CSS class value specified by the classVal parameter from the element. If
  4870. * animations are enabled then an animation will be triggered for the class removal.
  4871. *
  4872. * @param {string} classVal The className value that will be removed from the element
  4873. */
  4874. $removeClass : function(classVal) {
  4875. if(classVal && classVal.length > 0) {
  4876. $animate.removeClass(this.$$element, classVal);
  4877. }
  4878. },
  4879. /**
  4880. * @ngdoc function
  4881. * @name ng.$compile.directive.Attributes#$updateClass
  4882. * @methodOf ng.$compile.directive.Attributes
  4883. * @function
  4884. *
  4885. * @description
  4886. * Adds and removes the appropriate CSS class values to the element based on the difference
  4887. * between the new and old CSS class values (specified as newClasses and oldClasses).
  4888. *
  4889. * @param {string} newClasses The current CSS className value
  4890. * @param {string} oldClasses The former CSS className value
  4891. */
  4892. $updateClass : function(newClasses, oldClasses) {
  4893. this.$removeClass(tokenDifference(oldClasses, newClasses));
  4894. this.$addClass(tokenDifference(newClasses, oldClasses));
  4895. },
  4896. /**
  4897. * Set a normalized attribute on the element in a way such that all directives
  4898. * can share the attribute. This function properly handles boolean attributes.
  4899. * @param {string} key Normalized key. (ie ngAttribute)
  4900. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  4901. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  4902. * Defaults to true.
  4903. * @param {string=} attrName Optional none normalized name. Defaults to key.
  4904. */
  4905. $set: function(key, value, writeAttr, attrName) {
  4906. // TODO: decide whether or not to throw an error if "class"
  4907. //is set through this function since it may cause $updateClass to
  4908. //become unstable.
  4909. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  4910. normalizedVal,
  4911. nodeName;
  4912. if (booleanKey) {
  4913. this.$$element.prop(key, value);
  4914. attrName = booleanKey;
  4915. }
  4916. this[key] = value;
  4917. // translate normalized key to actual key
  4918. if (attrName) {
  4919. this.$attr[key] = attrName;
  4920. } else {
  4921. attrName = this.$attr[key];
  4922. if (!attrName) {
  4923. this.$attr[key] = attrName = snake_case(key, '-');
  4924. }
  4925. }
  4926. nodeName = nodeName_(this.$$element);
  4927. // sanitize a[href] and img[src] values
  4928. if ((nodeName === 'A' && key === 'href') ||
  4929. (nodeName === 'IMG' && key === 'src')) {
  4930. this[key] = value = $$sanitizeUri(value, key === 'src');
  4931. }
  4932. if (writeAttr !== false) {
  4933. if (value === null || value === undefined) {
  4934. this.$$element.removeAttr(attrName);
  4935. } else {
  4936. this.$$element.attr(attrName, value);
  4937. }
  4938. }
  4939. // fire observers
  4940. var $$observers = this.$$observers;
  4941. $$observers && forEach($$observers[key], function(fn) {
  4942. try {
  4943. fn(value);
  4944. } catch (e) {
  4945. $exceptionHandler(e);
  4946. }
  4947. });
  4948. },
  4949. /**
  4950. * @ngdoc function
  4951. * @name ng.$compile.directive.Attributes#$observe
  4952. * @methodOf ng.$compile.directive.Attributes
  4953. * @function
  4954. *
  4955. * @description
  4956. * Observes an interpolated attribute.
  4957. *
  4958. * The observer function will be invoked once during the next `$digest` following
  4959. * compilation. The observer is then invoked whenever the interpolated value
  4960. * changes.
  4961. *
  4962. * @param {string} key Normalized key. (ie ngAttribute) .
  4963. * @param {function(interpolatedValue)} fn Function that will be called whenever
  4964. the interpolated value of the attribute changes.
  4965. * See the {@link guide/directive#Attributes Directives} guide for more info.
  4966. * @returns {function()} the `fn` parameter.
  4967. */
  4968. $observe: function(key, fn) {
  4969. var attrs = this,
  4970. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  4971. listeners = ($$observers[key] || ($$observers[key] = []));
  4972. listeners.push(fn);
  4973. $rootScope.$evalAsync(function() {
  4974. if (!listeners.$$inter) {
  4975. // no one registered attribute interpolation function, so lets call it manually
  4976. fn(attrs[key]);
  4977. }
  4978. });
  4979. return fn;
  4980. }
  4981. };
  4982. var startSymbol = $interpolate.startSymbol(),
  4983. endSymbol = $interpolate.endSymbol(),
  4984. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  4985. ? identity
  4986. : function denormalizeTemplate(template) {
  4987. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  4988. },
  4989. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  4990. return compile;
  4991. //================================
  4992. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  4993. previousCompileContext) {
  4994. if (!($compileNodes instanceof jqLite)) {
  4995. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  4996. // modify it.
  4997. $compileNodes = jqLite($compileNodes);
  4998. }
  4999. // We can not compile top level text elements since text nodes can be merged and we will
  5000. // not be able to attach scope data to them, so we will wrap them in <span>
  5001. forEach($compileNodes, function(node, index){
  5002. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  5003. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  5004. }
  5005. });
  5006. var compositeLinkFn =
  5007. compileNodes($compileNodes, transcludeFn, $compileNodes,
  5008. maxPriority, ignoreDirective, previousCompileContext);
  5009. safeAddClass($compileNodes, 'ng-scope');
  5010. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers){
  5011. assertArg(scope, 'scope');
  5012. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  5013. // and sometimes changes the structure of the DOM.
  5014. var $linkNode = cloneConnectFn
  5015. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  5016. : $compileNodes;
  5017. forEach(transcludeControllers, function(instance, name) {
  5018. $linkNode.data('$' + name + 'Controller', instance);
  5019. });
  5020. // Attach scope only to non-text nodes.
  5021. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  5022. var node = $linkNode[i],
  5023. nodeType = node.nodeType;
  5024. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  5025. $linkNode.eq(i).data('$scope', scope);
  5026. }
  5027. }
  5028. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  5029. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
  5030. return $linkNode;
  5031. };
  5032. }
  5033. function safeAddClass($element, className) {
  5034. try {
  5035. $element.addClass(className);
  5036. } catch(e) {
  5037. // ignore, since it means that we are trying to set class on
  5038. // SVG element, where class name is read-only.
  5039. }
  5040. }
  5041. /**
  5042. * Compile function matches each node in nodeList against the directives. Once all directives
  5043. * for a particular node are collected their compile functions are executed. The compile
  5044. * functions return values - the linking functions - are combined into a composite linking
  5045. * function, which is the a linking function for the node.
  5046. *
  5047. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  5048. * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
  5049. * scope argument is auto-generated to the new child of the transcluded parent scope.
  5050. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  5051. * the rootElement must be set the jqLite collection of the compile root. This is
  5052. * needed so that the jqLite collection items can be replaced with widgets.
  5053. * @param {number=} maxPriority Max directive priority.
  5054. * @returns {?function} A composite linking function of all of the matched directives or null.
  5055. */
  5056. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  5057. previousCompileContext) {
  5058. var linkFns = [],
  5059. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  5060. for (var i = 0; i < nodeList.length; i++) {
  5061. attrs = new Attributes();
  5062. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  5063. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  5064. ignoreDirective);
  5065. nodeLinkFn = (directives.length)
  5066. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  5067. null, [], [], previousCompileContext)
  5068. : null;
  5069. if (nodeLinkFn && nodeLinkFn.scope) {
  5070. safeAddClass(jqLite(nodeList[i]), 'ng-scope');
  5071. }
  5072. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  5073. !(childNodes = nodeList[i].childNodes) ||
  5074. !childNodes.length)
  5075. ? null
  5076. : compileNodes(childNodes,
  5077. nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
  5078. linkFns.push(nodeLinkFn, childLinkFn);
  5079. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  5080. //use the previous context only for the first element in the virtual group
  5081. previousCompileContext = null;
  5082. }
  5083. // return a linking function if we have found anything, null otherwise
  5084. return linkFnFound ? compositeLinkFn : null;
  5085. function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
  5086. var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n;
  5087. // copy nodeList so that linking doesn't break due to live list updates.
  5088. var nodeListLength = nodeList.length,
  5089. stableNodeList = new Array(nodeListLength);
  5090. for (i = 0; i < nodeListLength; i++) {
  5091. stableNodeList[i] = nodeList[i];
  5092. }
  5093. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  5094. node = stableNodeList[n];
  5095. nodeLinkFn = linkFns[i++];
  5096. childLinkFn = linkFns[i++];
  5097. $node = jqLite(node);
  5098. if (nodeLinkFn) {
  5099. if (nodeLinkFn.scope) {
  5100. childScope = scope.$new();
  5101. $node.data('$scope', childScope);
  5102. } else {
  5103. childScope = scope;
  5104. }
  5105. childTranscludeFn = nodeLinkFn.transclude;
  5106. if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
  5107. nodeLinkFn(childLinkFn, childScope, node, $rootElement,
  5108. createBoundTranscludeFn(scope, childTranscludeFn || transcludeFn)
  5109. );
  5110. } else {
  5111. nodeLinkFn(childLinkFn, childScope, node, $rootElement, boundTranscludeFn);
  5112. }
  5113. } else if (childLinkFn) {
  5114. childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
  5115. }
  5116. }
  5117. }
  5118. }
  5119. function createBoundTranscludeFn(scope, transcludeFn) {
  5120. return function boundTranscludeFn(transcludedScope, cloneFn, controllers) {
  5121. var scopeCreated = false;
  5122. if (!transcludedScope) {
  5123. transcludedScope = scope.$new();
  5124. transcludedScope.$$transcluded = true;
  5125. scopeCreated = true;
  5126. }
  5127. var clone = transcludeFn(transcludedScope, cloneFn, controllers);
  5128. if (scopeCreated) {
  5129. clone.on('$destroy', bind(transcludedScope, transcludedScope.$destroy));
  5130. }
  5131. return clone;
  5132. };
  5133. }
  5134. /**
  5135. * Looks for directives on the given node and adds them to the directive collection which is
  5136. * sorted.
  5137. *
  5138. * @param node Node to search.
  5139. * @param directives An array to which the directives are added to. This array is sorted before
  5140. * the function returns.
  5141. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  5142. * @param {number=} maxPriority Max directive priority.
  5143. */
  5144. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  5145. var nodeType = node.nodeType,
  5146. attrsMap = attrs.$attr,
  5147. match,
  5148. className;
  5149. switch(nodeType) {
  5150. case 1: /* Element */
  5151. // use the node name: <directive>
  5152. addDirective(directives,
  5153. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  5154. // iterate over the attributes
  5155. for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
  5156. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  5157. var attrStartName = false;
  5158. var attrEndName = false;
  5159. attr = nAttrs[j];
  5160. if (!msie || msie >= 8 || attr.specified) {
  5161. name = attr.name;
  5162. // support ngAttr attribute binding
  5163. ngAttrName = directiveNormalize(name);
  5164. if (NG_ATTR_BINDING.test(ngAttrName)) {
  5165. name = snake_case(ngAttrName.substr(6), '-');
  5166. }
  5167. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  5168. if (ngAttrName === directiveNName + 'Start') {
  5169. attrStartName = name;
  5170. attrEndName = name.substr(0, name.length - 5) + 'end';
  5171. name = name.substr(0, name.length - 6);
  5172. }
  5173. nName = directiveNormalize(name.toLowerCase());
  5174. attrsMap[nName] = name;
  5175. attrs[nName] = value = trim(attr.value);
  5176. if (getBooleanAttrName(node, nName)) {
  5177. attrs[nName] = true; // presence means true
  5178. }
  5179. addAttrInterpolateDirective(node, directives, value, nName);
  5180. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  5181. attrEndName);
  5182. }
  5183. }
  5184. // use class as directive
  5185. className = node.className;
  5186. if (isString(className) && className !== '') {
  5187. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  5188. nName = directiveNormalize(match[2]);
  5189. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  5190. attrs[nName] = trim(match[3]);
  5191. }
  5192. className = className.substr(match.index + match[0].length);
  5193. }
  5194. }
  5195. break;
  5196. case 3: /* Text Node */
  5197. addTextInterpolateDirective(directives, node.nodeValue);
  5198. break;
  5199. case 8: /* Comment */
  5200. try {
  5201. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  5202. if (match) {
  5203. nName = directiveNormalize(match[1]);
  5204. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  5205. attrs[nName] = trim(match[2]);
  5206. }
  5207. }
  5208. } catch (e) {
  5209. // turns out that under some circumstances IE9 throws errors when one attempts to read
  5210. // comment's node value.
  5211. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  5212. }
  5213. break;
  5214. }
  5215. directives.sort(byPriority);
  5216. return directives;
  5217. }
  5218. /**
  5219. * Given a node with an directive-start it collects all of the siblings until it finds
  5220. * directive-end.
  5221. * @param node
  5222. * @param attrStart
  5223. * @param attrEnd
  5224. * @returns {*}
  5225. */
  5226. function groupScan(node, attrStart, attrEnd) {
  5227. var nodes = [];
  5228. var depth = 0;
  5229. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  5230. var startNode = node;
  5231. do {
  5232. if (!node) {
  5233. throw $compileMinErr('uterdir',
  5234. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  5235. attrStart, attrEnd);
  5236. }
  5237. if (node.nodeType == 1 /** Element **/) {
  5238. if (node.hasAttribute(attrStart)) depth++;
  5239. if (node.hasAttribute(attrEnd)) depth--;
  5240. }
  5241. nodes.push(node);
  5242. node = node.nextSibling;
  5243. } while (depth > 0);
  5244. } else {
  5245. nodes.push(node);
  5246. }
  5247. return jqLite(nodes);
  5248. }
  5249. /**
  5250. * Wrapper for linking function which converts normal linking function into a grouped
  5251. * linking function.
  5252. * @param linkFn
  5253. * @param attrStart
  5254. * @param attrEnd
  5255. * @returns {Function}
  5256. */
  5257. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  5258. return function(scope, element, attrs, controllers, transcludeFn) {
  5259. element = groupScan(element[0], attrStart, attrEnd);
  5260. return linkFn(scope, element, attrs, controllers, transcludeFn);
  5261. };
  5262. }
  5263. /**
  5264. * Once the directives have been collected, their compile functions are executed. This method
  5265. * is responsible for inlining directive templates as well as terminating the application
  5266. * of the directives if the terminal directive has been reached.
  5267. *
  5268. * @param {Array} directives Array of collected directives to execute their compile function.
  5269. * this needs to be pre-sorted by priority order.
  5270. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  5271. * @param {Object} templateAttrs The shared attribute function
  5272. * @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
  5273. * scope argument is auto-generated to the new
  5274. * child of the transcluded parent scope.
  5275. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  5276. * argument has the root jqLite array so that we can replace nodes
  5277. * on it.
  5278. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  5279. * compiling the transclusion.
  5280. * @param {Array.<Function>} preLinkFns
  5281. * @param {Array.<Function>} postLinkFns
  5282. * @param {Object} previousCompileContext Context used for previous compilation of the current
  5283. * node
  5284. * @returns linkFn
  5285. */
  5286. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  5287. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  5288. previousCompileContext) {
  5289. previousCompileContext = previousCompileContext || {};
  5290. var terminalPriority = -Number.MAX_VALUE,
  5291. newScopeDirective,
  5292. controllerDirectives = previousCompileContext.controllerDirectives,
  5293. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  5294. templateDirective = previousCompileContext.templateDirective,
  5295. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  5296. hasTranscludeDirective = false,
  5297. hasElementTranscludeDirective = false,
  5298. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  5299. directive,
  5300. directiveName,
  5301. $template,
  5302. replaceDirective = originalReplaceDirective,
  5303. childTranscludeFn = transcludeFn,
  5304. linkFn,
  5305. directiveValue;
  5306. // executes all directives on the current element
  5307. for(var i = 0, ii = directives.length; i < ii; i++) {
  5308. directive = directives[i];
  5309. var attrStart = directive.$$start;
  5310. var attrEnd = directive.$$end;
  5311. // collect multiblock sections
  5312. if (attrStart) {
  5313. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  5314. }
  5315. $template = undefined;
  5316. if (terminalPriority > directive.priority) {
  5317. break; // prevent further processing of directives
  5318. }
  5319. if (directiveValue = directive.scope) {
  5320. newScopeDirective = newScopeDirective || directive;
  5321. // skip the check for directives with async templates, we'll check the derived sync
  5322. // directive when the template arrives
  5323. if (!directive.templateUrl) {
  5324. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  5325. $compileNode);
  5326. if (isObject(directiveValue)) {
  5327. newIsolateScopeDirective = directive;
  5328. }
  5329. }
  5330. }
  5331. directiveName = directive.name;
  5332. if (!directive.templateUrl && directive.controller) {
  5333. directiveValue = directive.controller;
  5334. controllerDirectives = controllerDirectives || {};
  5335. assertNoDuplicate("'" + directiveName + "' controller",
  5336. controllerDirectives[directiveName], directive, $compileNode);
  5337. controllerDirectives[directiveName] = directive;
  5338. }
  5339. if (directiveValue = directive.transclude) {
  5340. hasTranscludeDirective = true;
  5341. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  5342. // This option should only be used by directives that know how to how to safely handle element transclusion,
  5343. // where the transcluded nodes are added or replaced after linking.
  5344. if (!directive.$$tlb) {
  5345. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  5346. nonTlbTranscludeDirective = directive;
  5347. }
  5348. if (directiveValue == 'element') {
  5349. hasElementTranscludeDirective = true;
  5350. terminalPriority = directive.priority;
  5351. $template = groupScan(compileNode, attrStart, attrEnd);
  5352. $compileNode = templateAttrs.$$element =
  5353. jqLite(document.createComment(' ' + directiveName + ': ' +
  5354. templateAttrs[directiveName] + ' '));
  5355. compileNode = $compileNode[0];
  5356. replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
  5357. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  5358. replaceDirective && replaceDirective.name, {
  5359. // Don't pass in:
  5360. // - controllerDirectives - otherwise we'll create duplicates controllers
  5361. // - newIsolateScopeDirective or templateDirective - combining templates with
  5362. // element transclusion doesn't make sense.
  5363. //
  5364. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  5365. // on the same element more than once.
  5366. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5367. });
  5368. } else {
  5369. $template = jqLite(jqLiteClone(compileNode)).contents();
  5370. $compileNode.empty(); // clear contents
  5371. childTranscludeFn = compile($template, transcludeFn);
  5372. }
  5373. }
  5374. if (directive.template) {
  5375. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5376. templateDirective = directive;
  5377. directiveValue = (isFunction(directive.template))
  5378. ? directive.template($compileNode, templateAttrs)
  5379. : directive.template;
  5380. directiveValue = denormalizeTemplate(directiveValue);
  5381. if (directive.replace) {
  5382. replaceDirective = directive;
  5383. $template = jqLite('<div>' +
  5384. trim(directiveValue) +
  5385. '</div>').contents();
  5386. compileNode = $template[0];
  5387. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5388. throw $compileMinErr('tplrt',
  5389. "Template for directive '{0}' must have exactly one root element. {1}",
  5390. directiveName, '');
  5391. }
  5392. replaceWith(jqCollection, $compileNode, compileNode);
  5393. var newTemplateAttrs = {$attr: {}};
  5394. // combine directives from the original node and from the template:
  5395. // - take the array of directives for this element
  5396. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  5397. // - collect directives from the template and sort them by priority
  5398. // - combine directives as: processed + template + unprocessed
  5399. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  5400. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  5401. if (newIsolateScopeDirective) {
  5402. markDirectivesAsIsolate(templateDirectives);
  5403. }
  5404. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  5405. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  5406. ii = directives.length;
  5407. } else {
  5408. $compileNode.html(directiveValue);
  5409. }
  5410. }
  5411. if (directive.templateUrl) {
  5412. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5413. templateDirective = directive;
  5414. if (directive.replace) {
  5415. replaceDirective = directive;
  5416. }
  5417. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  5418. templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, {
  5419. controllerDirectives: controllerDirectives,
  5420. newIsolateScopeDirective: newIsolateScopeDirective,
  5421. templateDirective: templateDirective,
  5422. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5423. });
  5424. ii = directives.length;
  5425. } else if (directive.compile) {
  5426. try {
  5427. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  5428. if (isFunction(linkFn)) {
  5429. addLinkFns(null, linkFn, attrStart, attrEnd);
  5430. } else if (linkFn) {
  5431. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  5432. }
  5433. } catch (e) {
  5434. $exceptionHandler(e, startingTag($compileNode));
  5435. }
  5436. }
  5437. if (directive.terminal) {
  5438. nodeLinkFn.terminal = true;
  5439. terminalPriority = Math.max(terminalPriority, directive.priority);
  5440. }
  5441. }
  5442. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  5443. nodeLinkFn.transclude = hasTranscludeDirective && childTranscludeFn;
  5444. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  5445. return nodeLinkFn;
  5446. ////////////////////
  5447. function addLinkFns(pre, post, attrStart, attrEnd) {
  5448. if (pre) {
  5449. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  5450. pre.require = directive.require;
  5451. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5452. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  5453. }
  5454. preLinkFns.push(pre);
  5455. }
  5456. if (post) {
  5457. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  5458. post.require = directive.require;
  5459. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5460. post = cloneAndAnnotateFn(post, {isolateScope: true});
  5461. }
  5462. postLinkFns.push(post);
  5463. }
  5464. }
  5465. function getControllers(require, $element, elementControllers) {
  5466. var value, retrievalMethod = 'data', optional = false;
  5467. if (isString(require)) {
  5468. while((value = require.charAt(0)) == '^' || value == '?') {
  5469. require = require.substr(1);
  5470. if (value == '^') {
  5471. retrievalMethod = 'inheritedData';
  5472. }
  5473. optional = optional || value == '?';
  5474. }
  5475. value = null;
  5476. if (elementControllers && retrievalMethod === 'data') {
  5477. value = elementControllers[require];
  5478. }
  5479. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  5480. if (!value && !optional) {
  5481. throw $compileMinErr('ctreq',
  5482. "Controller '{0}', required by directive '{1}', can't be found!",
  5483. require, directiveName);
  5484. }
  5485. return value;
  5486. } else if (isArray(require)) {
  5487. value = [];
  5488. forEach(require, function(require) {
  5489. value.push(getControllers(require, $element, elementControllers));
  5490. });
  5491. }
  5492. return value;
  5493. }
  5494. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  5495. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  5496. if (compileNode === linkNode) {
  5497. attrs = templateAttrs;
  5498. } else {
  5499. attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  5500. }
  5501. $element = attrs.$$element;
  5502. if (newIsolateScopeDirective) {
  5503. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5504. var $linkNode = jqLite(linkNode);
  5505. isolateScope = scope.$new(true);
  5506. if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  5507. $linkNode.data('$isolateScope', isolateScope) ;
  5508. } else {
  5509. $linkNode.data('$isolateScopeNoTemplate', isolateScope);
  5510. }
  5511. safeAddClass($linkNode, 'ng-isolate-scope');
  5512. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  5513. var match = definition.match(LOCAL_REGEXP) || [],
  5514. attrName = match[3] || scopeName,
  5515. optional = (match[2] == '?'),
  5516. mode = match[1], // @, =, or &
  5517. lastValue,
  5518. parentGet, parentSet, compare;
  5519. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  5520. switch (mode) {
  5521. case '@':
  5522. attrs.$observe(attrName, function(value) {
  5523. isolateScope[scopeName] = value;
  5524. });
  5525. attrs.$$observers[attrName].$$scope = scope;
  5526. if( attrs[attrName] ) {
  5527. // If the attribute has been provided then we trigger an interpolation to ensure
  5528. // the value is there for use in the link fn
  5529. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  5530. }
  5531. break;
  5532. case '=':
  5533. if (optional && !attrs[attrName]) {
  5534. return;
  5535. }
  5536. parentGet = $parse(attrs[attrName]);
  5537. if (parentGet.literal) {
  5538. compare = equals;
  5539. } else {
  5540. compare = function(a,b) { return a === b; };
  5541. }
  5542. parentSet = parentGet.assign || function() {
  5543. // reset the change, or we will throw this exception on every $digest
  5544. lastValue = isolateScope[scopeName] = parentGet(scope);
  5545. throw $compileMinErr('nonassign',
  5546. "Expression '{0}' used with directive '{1}' is non-assignable!",
  5547. attrs[attrName], newIsolateScopeDirective.name);
  5548. };
  5549. lastValue = isolateScope[scopeName] = parentGet(scope);
  5550. isolateScope.$watch(function parentValueWatch() {
  5551. var parentValue = parentGet(scope);
  5552. if (!compare(parentValue, isolateScope[scopeName])) {
  5553. // we are out of sync and need to copy
  5554. if (!compare(parentValue, lastValue)) {
  5555. // parent changed and it has precedence
  5556. isolateScope[scopeName] = parentValue;
  5557. } else {
  5558. // if the parent can be assigned then do so
  5559. parentSet(scope, parentValue = isolateScope[scopeName]);
  5560. }
  5561. }
  5562. return lastValue = parentValue;
  5563. }, null, parentGet.literal);
  5564. break;
  5565. case '&':
  5566. parentGet = $parse(attrs[attrName]);
  5567. isolateScope[scopeName] = function(locals) {
  5568. return parentGet(scope, locals);
  5569. };
  5570. break;
  5571. default:
  5572. throw $compileMinErr('iscp',
  5573. "Invalid isolate scope definition for directive '{0}'." +
  5574. " Definition: {... {1}: '{2}' ...}",
  5575. newIsolateScopeDirective.name, scopeName, definition);
  5576. }
  5577. });
  5578. }
  5579. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  5580. if (controllerDirectives) {
  5581. forEach(controllerDirectives, function(directive) {
  5582. var locals = {
  5583. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  5584. $element: $element,
  5585. $attrs: attrs,
  5586. $transclude: transcludeFn
  5587. }, controllerInstance;
  5588. controller = directive.controller;
  5589. if (controller == '@') {
  5590. controller = attrs[directive.name];
  5591. }
  5592. controllerInstance = $controller(controller, locals);
  5593. // For directives with element transclusion the element is a comment,
  5594. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  5595. // clean up (http://bugs.jquery.com/ticket/8335).
  5596. // Instead, we save the controllers for the element in a local hash and attach to .data
  5597. // later, once we have the actual element.
  5598. elementControllers[directive.name] = controllerInstance;
  5599. if (!hasElementTranscludeDirective) {
  5600. $element.data('$' + directive.name + 'Controller', controllerInstance);
  5601. }
  5602. if (directive.controllerAs) {
  5603. locals.$scope[directive.controllerAs] = controllerInstance;
  5604. }
  5605. });
  5606. }
  5607. // PRELINKING
  5608. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  5609. try {
  5610. linkFn = preLinkFns[i];
  5611. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  5612. linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
  5613. } catch (e) {
  5614. $exceptionHandler(e, startingTag($element));
  5615. }
  5616. }
  5617. // RECURSION
  5618. // We only pass the isolate scope, if the isolate directive has a template,
  5619. // otherwise the child elements do not belong to the isolate directive.
  5620. var scopeToChild = scope;
  5621. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  5622. scopeToChild = isolateScope;
  5623. }
  5624. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  5625. // POSTLINKING
  5626. for(i = postLinkFns.length - 1; i >= 0; i--) {
  5627. try {
  5628. linkFn = postLinkFns[i];
  5629. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  5630. linkFn.require && getControllers(linkFn.require, $element, elementControllers), transcludeFn);
  5631. } catch (e) {
  5632. $exceptionHandler(e, startingTag($element));
  5633. }
  5634. }
  5635. // This is the function that is injected as `$transclude`.
  5636. function controllersBoundTransclude(scope, cloneAttachFn) {
  5637. var transcludeControllers;
  5638. // no scope passed
  5639. if (arguments.length < 2) {
  5640. cloneAttachFn = scope;
  5641. scope = undefined;
  5642. }
  5643. if (hasElementTranscludeDirective) {
  5644. transcludeControllers = elementControllers;
  5645. }
  5646. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  5647. }
  5648. }
  5649. }
  5650. function markDirectivesAsIsolate(directives) {
  5651. // mark all directives as needing isolate scope.
  5652. for (var j = 0, jj = directives.length; j < jj; j++) {
  5653. directives[j] = inherit(directives[j], {$$isolateScope: true});
  5654. }
  5655. }
  5656. /**
  5657. * looks up the directive and decorates it with exception handling and proper parameters. We
  5658. * call this the boundDirective.
  5659. *
  5660. * @param {string} name name of the directive to look up.
  5661. * @param {string} location The directive must be found in specific format.
  5662. * String containing any of theses characters:
  5663. *
  5664. * * `E`: element name
  5665. * * `A': attribute
  5666. * * `C`: class
  5667. * * `M`: comment
  5668. * @returns true if directive was added.
  5669. */
  5670. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  5671. endAttrName) {
  5672. if (name === ignoreDirective) return null;
  5673. var match = null;
  5674. if (hasDirectives.hasOwnProperty(name)) {
  5675. for(var directive, directives = $injector.get(name + Suffix),
  5676. i = 0, ii = directives.length; i<ii; i++) {
  5677. try {
  5678. directive = directives[i];
  5679. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  5680. directive.restrict.indexOf(location) != -1) {
  5681. if (startAttrName) {
  5682. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  5683. }
  5684. tDirectives.push(directive);
  5685. match = directive;
  5686. }
  5687. } catch(e) { $exceptionHandler(e); }
  5688. }
  5689. }
  5690. return match;
  5691. }
  5692. /**
  5693. * When the element is replaced with HTML template then the new attributes
  5694. * on the template need to be merged with the existing attributes in the DOM.
  5695. * The desired effect is to have both of the attributes present.
  5696. *
  5697. * @param {object} dst destination attributes (original DOM)
  5698. * @param {object} src source attributes (from the directive template)
  5699. */
  5700. function mergeTemplateAttributes(dst, src) {
  5701. var srcAttr = src.$attr,
  5702. dstAttr = dst.$attr,
  5703. $element = dst.$$element;
  5704. // reapply the old attributes to the new element
  5705. forEach(dst, function(value, key) {
  5706. if (key.charAt(0) != '$') {
  5707. if (src[key]) {
  5708. value += (key === 'style' ? ';' : ' ') + src[key];
  5709. }
  5710. dst.$set(key, value, true, srcAttr[key]);
  5711. }
  5712. });
  5713. // copy the new attributes on the old attrs object
  5714. forEach(src, function(value, key) {
  5715. if (key == 'class') {
  5716. safeAddClass($element, value);
  5717. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  5718. } else if (key == 'style') {
  5719. $element.attr('style', $element.attr('style') + ';' + value);
  5720. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  5721. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  5722. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  5723. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  5724. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  5725. dst[key] = value;
  5726. dstAttr[key] = srcAttr[key];
  5727. }
  5728. });
  5729. }
  5730. function compileTemplateUrl(directives, $compileNode, tAttrs,
  5731. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  5732. var linkQueue = [],
  5733. afterTemplateNodeLinkFn,
  5734. afterTemplateChildLinkFn,
  5735. beforeTemplateCompileNode = $compileNode[0],
  5736. origAsyncDirective = directives.shift(),
  5737. // The fact that we have to copy and patch the directive seems wrong!
  5738. derivedSyncDirective = extend({}, origAsyncDirective, {
  5739. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  5740. }),
  5741. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  5742. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  5743. : origAsyncDirective.templateUrl;
  5744. $compileNode.empty();
  5745. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  5746. success(function(content) {
  5747. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  5748. content = denormalizeTemplate(content);
  5749. if (origAsyncDirective.replace) {
  5750. $template = jqLite('<div>' + trim(content) + '</div>').contents();
  5751. compileNode = $template[0];
  5752. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5753. throw $compileMinErr('tplrt',
  5754. "Template for directive '{0}' must have exactly one root element. {1}",
  5755. origAsyncDirective.name, templateUrl);
  5756. }
  5757. tempTemplateAttrs = {$attr: {}};
  5758. replaceWith($rootElement, $compileNode, compileNode);
  5759. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  5760. if (isObject(origAsyncDirective.scope)) {
  5761. markDirectivesAsIsolate(templateDirectives);
  5762. }
  5763. directives = templateDirectives.concat(directives);
  5764. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  5765. } else {
  5766. compileNode = beforeTemplateCompileNode;
  5767. $compileNode.html(content);
  5768. }
  5769. directives.unshift(derivedSyncDirective);
  5770. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  5771. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  5772. previousCompileContext);
  5773. forEach($rootElement, function(node, i) {
  5774. if (node == compileNode) {
  5775. $rootElement[i] = $compileNode[0];
  5776. }
  5777. });
  5778. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  5779. while(linkQueue.length) {
  5780. var scope = linkQueue.shift(),
  5781. beforeTemplateLinkNode = linkQueue.shift(),
  5782. linkRootElement = linkQueue.shift(),
  5783. boundTranscludeFn = linkQueue.shift(),
  5784. linkNode = $compileNode[0];
  5785. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  5786. // it was cloned therefore we have to clone as well.
  5787. linkNode = jqLiteClone(compileNode);
  5788. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  5789. }
  5790. if (afterTemplateNodeLinkFn.transclude) {
  5791. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude);
  5792. } else {
  5793. childBoundTranscludeFn = boundTranscludeFn;
  5794. }
  5795. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  5796. childBoundTranscludeFn);
  5797. }
  5798. linkQueue = null;
  5799. }).
  5800. error(function(response, code, headers, config) {
  5801. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  5802. });
  5803. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  5804. if (linkQueue) {
  5805. linkQueue.push(scope);
  5806. linkQueue.push(node);
  5807. linkQueue.push(rootElement);
  5808. linkQueue.push(boundTranscludeFn);
  5809. } else {
  5810. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, boundTranscludeFn);
  5811. }
  5812. };
  5813. }
  5814. /**
  5815. * Sorting function for bound directives.
  5816. */
  5817. function byPriority(a, b) {
  5818. var diff = b.priority - a.priority;
  5819. if (diff !== 0) return diff;
  5820. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  5821. return a.index - b.index;
  5822. }
  5823. function assertNoDuplicate(what, previousDirective, directive, element) {
  5824. if (previousDirective) {
  5825. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  5826. previousDirective.name, directive.name, what, startingTag(element));
  5827. }
  5828. }
  5829. function addTextInterpolateDirective(directives, text) {
  5830. var interpolateFn = $interpolate(text, true);
  5831. if (interpolateFn) {
  5832. directives.push({
  5833. priority: 0,
  5834. compile: valueFn(function textInterpolateLinkFn(scope, node) {
  5835. var parent = node.parent(),
  5836. bindings = parent.data('$binding') || [];
  5837. bindings.push(interpolateFn);
  5838. safeAddClass(parent.data('$binding', bindings), 'ng-binding');
  5839. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  5840. node[0].nodeValue = value;
  5841. });
  5842. })
  5843. });
  5844. }
  5845. }
  5846. function getTrustedContext(node, attrNormalizedName) {
  5847. if (attrNormalizedName == "srcdoc") {
  5848. return $sce.HTML;
  5849. }
  5850. var tag = nodeName_(node);
  5851. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  5852. if (attrNormalizedName == "xlinkHref" ||
  5853. (tag == "FORM" && attrNormalizedName == "action") ||
  5854. (tag != "IMG" && (attrNormalizedName == "src" ||
  5855. attrNormalizedName == "ngSrc"))) {
  5856. return $sce.RESOURCE_URL;
  5857. }
  5858. }
  5859. function addAttrInterpolateDirective(node, directives, value, name) {
  5860. var interpolateFn = $interpolate(value, true);
  5861. // no interpolation found -> ignore
  5862. if (!interpolateFn) return;
  5863. if (name === "multiple" && nodeName_(node) === "SELECT") {
  5864. throw $compileMinErr("selmulti",
  5865. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  5866. startingTag(node));
  5867. }
  5868. directives.push({
  5869. priority: 100,
  5870. compile: function() {
  5871. return {
  5872. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  5873. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  5874. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  5875. throw $compileMinErr('nodomevents',
  5876. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  5877. "ng- versions (such as ng-click instead of onclick) instead.");
  5878. }
  5879. // we need to interpolate again, in case the attribute value has been updated
  5880. // (e.g. by another directive's compile function)
  5881. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  5882. // if attribute was updated so that there is no interpolation going on we don't want to
  5883. // register any observers
  5884. if (!interpolateFn) return;
  5885. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  5886. // actual attr value
  5887. attr[name] = interpolateFn(scope);
  5888. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  5889. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  5890. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  5891. //special case for class attribute addition + removal
  5892. //so that class changes can tap into the animation
  5893. //hooks provided by the $animate service. Be sure to
  5894. //skip animations when the first digest occurs (when
  5895. //both the new and the old values are the same) since
  5896. //the CSS classes are the non-interpolated values
  5897. if(name === 'class' && newValue != oldValue) {
  5898. attr.$updateClass(newValue, oldValue);
  5899. } else {
  5900. attr.$set(name, newValue);
  5901. }
  5902. });
  5903. }
  5904. };
  5905. }
  5906. });
  5907. }
  5908. /**
  5909. * This is a special jqLite.replaceWith, which can replace items which
  5910. * have no parents, provided that the containing jqLite collection is provided.
  5911. *
  5912. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  5913. * in the root of the tree.
  5914. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  5915. * the shell, but replace its DOM node reference.
  5916. * @param {Node} newNode The new DOM node.
  5917. */
  5918. function replaceWith($rootElement, elementsToRemove, newNode) {
  5919. var firstElementToRemove = elementsToRemove[0],
  5920. removeCount = elementsToRemove.length,
  5921. parent = firstElementToRemove.parentNode,
  5922. i, ii;
  5923. if ($rootElement) {
  5924. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  5925. if ($rootElement[i] == firstElementToRemove) {
  5926. $rootElement[i++] = newNode;
  5927. for (var j = i, j2 = j + removeCount - 1,
  5928. jj = $rootElement.length;
  5929. j < jj; j++, j2++) {
  5930. if (j2 < jj) {
  5931. $rootElement[j] = $rootElement[j2];
  5932. } else {
  5933. delete $rootElement[j];
  5934. }
  5935. }
  5936. $rootElement.length -= removeCount - 1;
  5937. break;
  5938. }
  5939. }
  5940. }
  5941. if (parent) {
  5942. parent.replaceChild(newNode, firstElementToRemove);
  5943. }
  5944. var fragment = document.createDocumentFragment();
  5945. fragment.appendChild(firstElementToRemove);
  5946. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  5947. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  5948. var element = elementsToRemove[k];
  5949. jqLite(element).remove(); // must do this way to clean up expando
  5950. fragment.appendChild(element);
  5951. delete elementsToRemove[k];
  5952. }
  5953. elementsToRemove[0] = newNode;
  5954. elementsToRemove.length = 1;
  5955. }
  5956. function cloneAndAnnotateFn(fn, annotation) {
  5957. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  5958. }
  5959. }];
  5960. }
  5961. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  5962. /**
  5963. * Converts all accepted directives format into proper directive name.
  5964. * All of these will become 'myDirective':
  5965. * my:Directive
  5966. * my-directive
  5967. * x-my-directive
  5968. * data-my:directive
  5969. *
  5970. * Also there is special case for Moz prefix starting with upper case letter.
  5971. * @param name Name to normalize
  5972. */
  5973. function directiveNormalize(name) {
  5974. return camelCase(name.replace(PREFIX_REGEXP, ''));
  5975. }
  5976. /**
  5977. * @ngdoc object
  5978. * @name ng.$compile.directive.Attributes
  5979. *
  5980. * @description
  5981. * A shared object between directive compile / linking functions which contains normalized DOM
  5982. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  5983. * needed since all of these are treated as equivalent in Angular:
  5984. *
  5985. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  5986. */
  5987. /**
  5988. * @ngdoc property
  5989. * @name ng.$compile.directive.Attributes#$attr
  5990. * @propertyOf ng.$compile.directive.Attributes
  5991. * @returns {object} A map of DOM element attribute names to the normalized name. This is
  5992. * needed to do reverse lookup from normalized name back to actual name.
  5993. */
  5994. /**
  5995. * @ngdoc function
  5996. * @name ng.$compile.directive.Attributes#$set
  5997. * @methodOf ng.$compile.directive.Attributes
  5998. * @function
  5999. *
  6000. * @description
  6001. * Set DOM element attribute value.
  6002. *
  6003. *
  6004. * @param {string} name Normalized element attribute name of the property to modify. The name is
  6005. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  6006. * property to the original name.
  6007. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  6008. */
  6009. /**
  6010. * Closure compiler type information
  6011. */
  6012. function nodesetLinkingFn(
  6013. /* angular.Scope */ scope,
  6014. /* NodeList */ nodeList,
  6015. /* Element */ rootElement,
  6016. /* function(Function) */ boundTranscludeFn
  6017. ){}
  6018. function directiveLinkingFn(
  6019. /* nodesetLinkingFn */ nodesetLinkingFn,
  6020. /* angular.Scope */ scope,
  6021. /* Node */ node,
  6022. /* Element */ rootElement,
  6023. /* function(Function) */ boundTranscludeFn
  6024. ){}
  6025. function tokenDifference(str1, str2) {
  6026. var values = '',
  6027. tokens1 = str1.split(/\s+/),
  6028. tokens2 = str2.split(/\s+/);
  6029. outer:
  6030. for(var i = 0; i < tokens1.length; i++) {
  6031. var token = tokens1[i];
  6032. for(var j = 0; j < tokens2.length; j++) {
  6033. if(token == tokens2[j]) continue outer;
  6034. }
  6035. values += (values.length > 0 ? ' ' : '') + token;
  6036. }
  6037. return values;
  6038. }
  6039. /**
  6040. * @ngdoc object
  6041. * @name ng.$controllerProvider
  6042. * @description
  6043. * The {@link ng.$controller $controller service} is used by Angular to create new
  6044. * controllers.
  6045. *
  6046. * This provider allows controller registration via the
  6047. * {@link ng.$controllerProvider#methods_register register} method.
  6048. */
  6049. function $ControllerProvider() {
  6050. var controllers = {},
  6051. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  6052. /**
  6053. * @ngdoc function
  6054. * @name ng.$controllerProvider#register
  6055. * @methodOf ng.$controllerProvider
  6056. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  6057. * the names and the values are the constructors.
  6058. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  6059. * annotations in the array notation).
  6060. */
  6061. this.register = function(name, constructor) {
  6062. assertNotHasOwnProperty(name, 'controller');
  6063. if (isObject(name)) {
  6064. extend(controllers, name);
  6065. } else {
  6066. controllers[name] = constructor;
  6067. }
  6068. };
  6069. this.$get = ['$injector', '$window', function($injector, $window) {
  6070. /**
  6071. * @ngdoc function
  6072. * @name ng.$controller
  6073. * @requires $injector
  6074. *
  6075. * @param {Function|string} constructor If called with a function then it's considered to be the
  6076. * controller constructor function. Otherwise it's considered to be a string which is used
  6077. * to retrieve the controller constructor using the following steps:
  6078. *
  6079. * * check if a controller with given name is registered via `$controllerProvider`
  6080. * * check if evaluating the string on the current scope returns a constructor
  6081. * * check `window[constructor]` on the global `window` object
  6082. *
  6083. * @param {Object} locals Injection locals for Controller.
  6084. * @return {Object} Instance of given controller.
  6085. *
  6086. * @description
  6087. * `$controller` service is responsible for instantiating controllers.
  6088. *
  6089. * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
  6090. * a service, so that one can override this service with {@link https://gist.github.com/1649788
  6091. * BC version}.
  6092. */
  6093. return function(expression, locals) {
  6094. var instance, match, constructor, identifier;
  6095. if(isString(expression)) {
  6096. match = expression.match(CNTRL_REG),
  6097. constructor = match[1],
  6098. identifier = match[3];
  6099. expression = controllers.hasOwnProperty(constructor)
  6100. ? controllers[constructor]
  6101. : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
  6102. assertArgFn(expression, constructor, true);
  6103. }
  6104. instance = $injector.instantiate(expression, locals);
  6105. if (identifier) {
  6106. if (!(locals && typeof locals.$scope == 'object')) {
  6107. throw minErr('$controller')('noscp',
  6108. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  6109. constructor || expression.name, identifier);
  6110. }
  6111. locals.$scope[identifier] = instance;
  6112. }
  6113. return instance;
  6114. };
  6115. }];
  6116. }
  6117. /**
  6118. * @ngdoc object
  6119. * @name ng.$document
  6120. * @requires $window
  6121. *
  6122. * @description
  6123. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  6124. */
  6125. function $DocumentProvider(){
  6126. this.$get = ['$window', function(window){
  6127. return jqLite(window.document);
  6128. }];
  6129. }
  6130. /**
  6131. * @ngdoc function
  6132. * @name ng.$exceptionHandler
  6133. * @requires $log
  6134. *
  6135. * @description
  6136. * Any uncaught exception in angular expressions is delegated to this service.
  6137. * The default implementation simply delegates to `$log.error` which logs it into
  6138. * the browser console.
  6139. *
  6140. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  6141. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  6142. *
  6143. * ## Example:
  6144. *
  6145. * <pre>
  6146. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  6147. * return function (exception, cause) {
  6148. * exception.message += ' (caused by "' + cause + '")';
  6149. * throw exception;
  6150. * };
  6151. * });
  6152. * </pre>
  6153. *
  6154. * This example will override the normal action of `$exceptionHandler`, to make angular
  6155. * exceptions fail hard when they happen, instead of just logging to the console.
  6156. *
  6157. * @param {Error} exception Exception associated with the error.
  6158. * @param {string=} cause optional information about the context in which
  6159. * the error was thrown.
  6160. *
  6161. */
  6162. function $ExceptionHandlerProvider() {
  6163. this.$get = ['$log', function($log) {
  6164. return function(exception, cause) {
  6165. $log.error.apply($log, arguments);
  6166. };
  6167. }];
  6168. }
  6169. /**
  6170. * Parse headers into key value object
  6171. *
  6172. * @param {string} headers Raw headers as a string
  6173. * @returns {Object} Parsed headers as key value object
  6174. */
  6175. function parseHeaders(headers) {
  6176. var parsed = {}, key, val, i;
  6177. if (!headers) return parsed;
  6178. forEach(headers.split('\n'), function(line) {
  6179. i = line.indexOf(':');
  6180. key = lowercase(trim(line.substr(0, i)));
  6181. val = trim(line.substr(i + 1));
  6182. if (key) {
  6183. if (parsed[key]) {
  6184. parsed[key] += ', ' + val;
  6185. } else {
  6186. parsed[key] = val;
  6187. }
  6188. }
  6189. });
  6190. return parsed;
  6191. }
  6192. /**
  6193. * Returns a function that provides access to parsed headers.
  6194. *
  6195. * Headers are lazy parsed when first requested.
  6196. * @see parseHeaders
  6197. *
  6198. * @param {(string|Object)} headers Headers to provide access to.
  6199. * @returns {function(string=)} Returns a getter function which if called with:
  6200. *
  6201. * - if called with single an argument returns a single header value or null
  6202. * - if called with no arguments returns an object containing all headers.
  6203. */
  6204. function headersGetter(headers) {
  6205. var headersObj = isObject(headers) ? headers : undefined;
  6206. return function(name) {
  6207. if (!headersObj) headersObj = parseHeaders(headers);
  6208. if (name) {
  6209. return headersObj[lowercase(name)] || null;
  6210. }
  6211. return headersObj;
  6212. };
  6213. }
  6214. /**
  6215. * Chain all given functions
  6216. *
  6217. * This function is used for both request and response transforming
  6218. *
  6219. * @param {*} data Data to transform.
  6220. * @param {function(string=)} headers Http headers getter fn.
  6221. * @param {(function|Array.<function>)} fns Function or an array of functions.
  6222. * @returns {*} Transformed data.
  6223. */
  6224. function transformData(data, headers, fns) {
  6225. if (isFunction(fns))
  6226. return fns(data, headers);
  6227. forEach(fns, function(fn) {
  6228. data = fn(data, headers);
  6229. });
  6230. return data;
  6231. }
  6232. function isSuccess(status) {
  6233. return 200 <= status && status < 300;
  6234. }
  6235. function $HttpProvider() {
  6236. var JSON_START = /^\s*(\[|\{[^\{])/,
  6237. JSON_END = /[\}\]]\s*$/,
  6238. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  6239. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
  6240. var defaults = this.defaults = {
  6241. // transform incoming response data
  6242. transformResponse: [function(data) {
  6243. if (isString(data)) {
  6244. // strip json vulnerability protection prefix
  6245. data = data.replace(PROTECTION_PREFIX, '');
  6246. if (JSON_START.test(data) && JSON_END.test(data))
  6247. data = fromJson(data);
  6248. }
  6249. return data;
  6250. }],
  6251. // transform outgoing request data
  6252. transformRequest: [function(d) {
  6253. return isObject(d) && !isFile(d) ? toJson(d) : d;
  6254. }],
  6255. // default headers
  6256. headers: {
  6257. common: {
  6258. 'Accept': 'application/json, text/plain, */*'
  6259. },
  6260. post: copy(CONTENT_TYPE_APPLICATION_JSON),
  6261. put: copy(CONTENT_TYPE_APPLICATION_JSON),
  6262. patch: copy(CONTENT_TYPE_APPLICATION_JSON)
  6263. },
  6264. xsrfCookieName: 'XSRF-TOKEN',
  6265. xsrfHeaderName: 'X-XSRF-TOKEN'
  6266. };
  6267. /**
  6268. * Are ordered by request, i.e. they are applied in the same order as the
  6269. * array, on request, but reverse order, on response.
  6270. */
  6271. var interceptorFactories = this.interceptors = [];
  6272. /**
  6273. * For historical reasons, response interceptors are ordered by the order in which
  6274. * they are applied to the response. (This is the opposite of interceptorFactories)
  6275. */
  6276. var responseInterceptorFactories = this.responseInterceptors = [];
  6277. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  6278. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  6279. var defaultCache = $cacheFactory('$http');
  6280. /**
  6281. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  6282. * The reversal is needed so that we can build up the interception chain around the
  6283. * server request.
  6284. */
  6285. var reversedInterceptors = [];
  6286. forEach(interceptorFactories, function(interceptorFactory) {
  6287. reversedInterceptors.unshift(isString(interceptorFactory)
  6288. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  6289. });
  6290. forEach(responseInterceptorFactories, function(interceptorFactory, index) {
  6291. var responseFn = isString(interceptorFactory)
  6292. ? $injector.get(interceptorFactory)
  6293. : $injector.invoke(interceptorFactory);
  6294. /**
  6295. * Response interceptors go before "around" interceptors (no real reason, just
  6296. * had to pick one.) But they are already reversed, so we can't use unshift, hence
  6297. * the splice.
  6298. */
  6299. reversedInterceptors.splice(index, 0, {
  6300. response: function(response) {
  6301. return responseFn($q.when(response));
  6302. },
  6303. responseError: function(response) {
  6304. return responseFn($q.reject(response));
  6305. }
  6306. });
  6307. });
  6308. /**
  6309. * @ngdoc function
  6310. * @name ng.$http
  6311. * @requires $httpBackend
  6312. * @requires $browser
  6313. * @requires $cacheFactory
  6314. * @requires $rootScope
  6315. * @requires $q
  6316. * @requires $injector
  6317. *
  6318. * @description
  6319. * The `$http` service is a core Angular service that facilitates communication with the remote
  6320. * HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest
  6321. * XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
  6322. *
  6323. * For unit testing applications that use `$http` service, see
  6324. * {@link ngMock.$httpBackend $httpBackend mock}.
  6325. *
  6326. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  6327. * $resource} service.
  6328. *
  6329. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  6330. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  6331. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  6332. *
  6333. *
  6334. * # General usage
  6335. * The `$http` service is a function which takes a single argument — a configuration object —
  6336. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  6337. * with two $http specific methods: `success` and `error`.
  6338. *
  6339. * <pre>
  6340. * $http({method: 'GET', url: '/someUrl'}).
  6341. * success(function(data, status, headers, config) {
  6342. * // this callback will be called asynchronously
  6343. * // when the response is available
  6344. * }).
  6345. * error(function(data, status, headers, config) {
  6346. * // called asynchronously if an error occurs
  6347. * // or server returns response with an error status.
  6348. * });
  6349. * </pre>
  6350. *
  6351. * Since the returned value of calling the $http function is a `promise`, you can also use
  6352. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  6353. * an object representing the response. See the API signature and type info below for more
  6354. * details.
  6355. *
  6356. * A response status code between 200 and 299 is considered a success status and
  6357. * will result in the success callback being called. Note that if the response is a redirect,
  6358. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  6359. * called for such responses.
  6360. *
  6361. * # Calling $http from outside AngularJS
  6362. * The `$http` service will not actually send the request until the next `$digest()` is
  6363. * executed. Normally this is not an issue, since almost all the time your call to `$http` will
  6364. * be from within a `$apply()` block.
  6365. * If you are calling `$http` from outside Angular, then you should wrap it in a call to
  6366. * `$apply` to cause a $digest to occur and also to handle errors in the block correctly.
  6367. *
  6368. * ```
  6369. * $scope.$apply(function() {
  6370. * $http(...);
  6371. * });
  6372. * ```
  6373. *
  6374. * # Writing Unit Tests that use $http
  6375. * When unit testing you are mostly responsible for scheduling the `$digest` cycle. If you do
  6376. * not trigger a `$digest` before calling `$httpBackend.flush()` then the request will not have
  6377. * been made and `$httpBackend.expect(...)` expectations will fail. The solution is to run the
  6378. * code that calls the `$http()` method inside a $apply block as explained in the previous
  6379. * section.
  6380. *
  6381. * ```
  6382. * $httpBackend.expectGET(...);
  6383. * $scope.$apply(function() {
  6384. * $http.get(...);
  6385. * });
  6386. * $httpBackend.flush();
  6387. * ```
  6388. *
  6389. * # Shortcut methods
  6390. *
  6391. * Since all invocations of the $http service require passing in an HTTP method and URL, and
  6392. * POST/PUT requests require request data to be provided as well, shortcut methods
  6393. * were created:
  6394. *
  6395. * <pre>
  6396. * $http.get('/someUrl').success(successCallback);
  6397. * $http.post('/someUrl', data).success(successCallback);
  6398. * </pre>
  6399. *
  6400. * Complete list of shortcut methods:
  6401. *
  6402. * - {@link ng.$http#methods_get $http.get}
  6403. * - {@link ng.$http#methods_head $http.head}
  6404. * - {@link ng.$http#methods_post $http.post}
  6405. * - {@link ng.$http#methods_put $http.put}
  6406. * - {@link ng.$http#methods_delete $http.delete}
  6407. * - {@link ng.$http#methods_jsonp $http.jsonp}
  6408. *
  6409. *
  6410. * # Setting HTTP Headers
  6411. *
  6412. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  6413. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  6414. * object, which currently contains this default configuration:
  6415. *
  6416. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  6417. * - `Accept: application/json, text/plain, * / *`
  6418. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  6419. * - `Content-Type: application/json`
  6420. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  6421. * - `Content-Type: application/json`
  6422. *
  6423. * To add or overwrite these defaults, simply add or remove a property from these configuration
  6424. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  6425. * with the lowercased HTTP method name as the key, e.g.
  6426. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  6427. *
  6428. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  6429. * fashion. For example:
  6430. *
  6431. * ```
  6432. * module.run(function($http) {
  6433. * $http.defaults.headers.common.Authentication = 'Basic YmVlcDpib29w'
  6434. * });
  6435. * ```
  6436. *
  6437. * In addition, you can supply a `headers` property in the config object passed when
  6438. * calling `$http(config)`, which overrides the defaults without changing them globally.
  6439. *
  6440. *
  6441. * # Transforming Requests and Responses
  6442. *
  6443. * Both requests and responses can be transformed using transform functions. By default, Angular
  6444. * applies these transformations:
  6445. *
  6446. * Request transformations:
  6447. *
  6448. * - If the `data` property of the request configuration object contains an object, serialize it
  6449. * into JSON format.
  6450. *
  6451. * Response transformations:
  6452. *
  6453. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  6454. * - If JSON response is detected, deserialize it using a JSON parser.
  6455. *
  6456. * To globally augment or override the default transforms, modify the
  6457. * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
  6458. * properties. These properties are by default an array of transform functions, which allows you
  6459. * to `push` or `unshift` a new transformation function into the transformation chain. You can
  6460. * also decide to completely override any default transformations by assigning your
  6461. * transformation functions to these properties directly without the array wrapper. These defaults
  6462. * are again available on the $http factory at run-time, which may be useful if you have run-time
  6463. * services you wish to be involved in your transformations.
  6464. *
  6465. * Similarly, to locally override the request/response transforms, augment the
  6466. * `transformRequest` and/or `transformResponse` properties of the configuration object passed
  6467. * into `$http`.
  6468. *
  6469. *
  6470. * # Caching
  6471. *
  6472. * To enable caching, set the request configuration `cache` property to `true` (to use default
  6473. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  6474. * When the cache is enabled, `$http` stores the response from the server in the specified
  6475. * cache. The next time the same request is made, the response is served from the cache without
  6476. * sending a request to the server.
  6477. *
  6478. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  6479. * the same way that real requests are.
  6480. *
  6481. * If there are multiple GET requests for the same URL that should be cached using the same
  6482. * cache, but the cache is not populated yet, only one request to the server will be made and
  6483. * the remaining requests will be fulfilled using the response from the first request.
  6484. *
  6485. * You can change the default cache to a new object (built with
  6486. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  6487. * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
  6488. * their `cache` property to `true` will now use this cache object.
  6489. *
  6490. * If you set the default cache to `false` then only requests that specify their own custom
  6491. * cache object will be cached.
  6492. *
  6493. * # Interceptors
  6494. *
  6495. * Before you start creating interceptors, be sure to understand the
  6496. * {@link ng.$q $q and deferred/promise APIs}.
  6497. *
  6498. * For purposes of global error handling, authentication, or any kind of synchronous or
  6499. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  6500. * able to intercept requests before they are handed to the server and
  6501. * responses before they are handed over to the application code that
  6502. * initiated these requests. The interceptors leverage the {@link ng.$q
  6503. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  6504. *
  6505. * The interceptors are service factories that are registered with the `$httpProvider` by
  6506. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  6507. * injected with dependencies (if specified) and returns the interceptor.
  6508. *
  6509. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  6510. *
  6511. * * `request`: interceptors get called with http `config` object. The function is free to
  6512. * modify the `config` or create a new one. The function needs to return the `config`
  6513. * directly or as a promise.
  6514. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  6515. * resolved with a rejection.
  6516. * * `response`: interceptors get called with http `response` object. The function is free to
  6517. * modify the `response` or create a new one. The function needs to return the `response`
  6518. * directly or as a promise.
  6519. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  6520. * resolved with a rejection.
  6521. *
  6522. *
  6523. * <pre>
  6524. * // register the interceptor as a service
  6525. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6526. * return {
  6527. * // optional method
  6528. * 'request': function(config) {
  6529. * // do something on success
  6530. * return config || $q.when(config);
  6531. * },
  6532. *
  6533. * // optional method
  6534. * 'requestError': function(rejection) {
  6535. * // do something on error
  6536. * if (canRecover(rejection)) {
  6537. * return responseOrNewPromise
  6538. * }
  6539. * return $q.reject(rejection);
  6540. * },
  6541. *
  6542. *
  6543. *
  6544. * // optional method
  6545. * 'response': function(response) {
  6546. * // do something on success
  6547. * return response || $q.when(response);
  6548. * },
  6549. *
  6550. * // optional method
  6551. * 'responseError': function(rejection) {
  6552. * // do something on error
  6553. * if (canRecover(rejection)) {
  6554. * return responseOrNewPromise
  6555. * }
  6556. * return $q.reject(rejection);
  6557. * }
  6558. * };
  6559. * });
  6560. *
  6561. * $httpProvider.interceptors.push('myHttpInterceptor');
  6562. *
  6563. *
  6564. * // alternatively, register the interceptor via an anonymous factory
  6565. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  6566. * return {
  6567. * 'request': function(config) {
  6568. * // same as above
  6569. * },
  6570. *
  6571. * 'response': function(response) {
  6572. * // same as above
  6573. * }
  6574. * };
  6575. * });
  6576. * </pre>
  6577. *
  6578. * # Response interceptors (DEPRECATED)
  6579. *
  6580. * Before you start creating interceptors, be sure to understand the
  6581. * {@link ng.$q $q and deferred/promise APIs}.
  6582. *
  6583. * For purposes of global error handling, authentication or any kind of synchronous or
  6584. * asynchronous preprocessing of received responses, it is desirable to be able to intercept
  6585. * responses for http requests before they are handed over to the application code that
  6586. * initiated these requests. The response interceptors leverage the {@link ng.$q
  6587. * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
  6588. *
  6589. * The interceptors are service factories that are registered with the $httpProvider by
  6590. * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
  6591. * injected with dependencies (if specified) and returns the interceptor — a function that
  6592. * takes a {@link ng.$q promise} and returns the original or a new promise.
  6593. *
  6594. * <pre>
  6595. * // register the interceptor as a service
  6596. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6597. * return function(promise) {
  6598. * return promise.then(function(response) {
  6599. * // do something on success
  6600. * return response;
  6601. * }, function(response) {
  6602. * // do something on error
  6603. * if (canRecover(response)) {
  6604. * return responseOrNewPromise
  6605. * }
  6606. * return $q.reject(response);
  6607. * });
  6608. * }
  6609. * });
  6610. *
  6611. * $httpProvider.responseInterceptors.push('myHttpInterceptor');
  6612. *
  6613. *
  6614. * // register the interceptor via an anonymous factory
  6615. * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
  6616. * return function(promise) {
  6617. * // same as above
  6618. * }
  6619. * });
  6620. * </pre>
  6621. *
  6622. *
  6623. * # Security Considerations
  6624. *
  6625. * When designing web applications, consider security threats from:
  6626. *
  6627. * - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
  6628. * JSON vulnerability}
  6629. * - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
  6630. *
  6631. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  6632. * pre-configured with strategies that address these issues, but for this to work backend server
  6633. * cooperation is required.
  6634. *
  6635. * ## JSON Vulnerability Protection
  6636. *
  6637. * A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
  6638. * JSON vulnerability} allows third party website to turn your JSON resource URL into
  6639. * {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To
  6640. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  6641. * Angular will automatically strip the prefix before processing it as JSON.
  6642. *
  6643. * For example if your server needs to return:
  6644. * <pre>
  6645. * ['one','two']
  6646. * </pre>
  6647. *
  6648. * which is vulnerable to attack, your server can return:
  6649. * <pre>
  6650. * )]}',
  6651. * ['one','two']
  6652. * </pre>
  6653. *
  6654. * Angular will strip the prefix, before processing the JSON.
  6655. *
  6656. *
  6657. * ## Cross Site Request Forgery (XSRF) Protection
  6658. *
  6659. * {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
  6660. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  6661. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  6662. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  6663. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  6664. * the XHR came from JavaScript running on your domain. The header will not be set for
  6665. * cross-domain requests.
  6666. *
  6667. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  6668. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  6669. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  6670. * that only JavaScript running on your domain could have sent the request. The token must be
  6671. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  6672. * making up its own tokens). We recommend that the token is a digest of your site's
  6673. * authentication cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt}
  6674. * for added security.
  6675. *
  6676. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  6677. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  6678. * or the per-request config object.
  6679. *
  6680. *
  6681. * @param {object} config Object describing the request to be made and how it should be
  6682. * processed. The object has following properties:
  6683. *
  6684. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  6685. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  6686. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  6687. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  6688. * JSONified.
  6689. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  6690. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  6691. * HTTP headers to send to the server. If the return value of a function is null, the
  6692. * header will not be sent.
  6693. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  6694. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  6695. * - **transformRequest** –
  6696. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  6697. * transform function or an array of such functions. The transform function takes the http
  6698. * request body and headers and returns its transformed (typically serialized) version.
  6699. * - **transformResponse** –
  6700. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  6701. * transform function or an array of such functions. The transform function takes the http
  6702. * response body and headers and returns its transformed (typically deserialized) version.
  6703. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  6704. * GET request, otherwise if a cache instance built with
  6705. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  6706. * caching.
  6707. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  6708. * that should abort the request when resolved.
  6709. * - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
  6710. * XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
  6711. * requests with credentials} for more information.
  6712. * - **responseType** - `{string}` - see {@link
  6713. * https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}.
  6714. *
  6715. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  6716. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  6717. * method takes two arguments a success and an error callback which will be called with a
  6718. * response object. The `success` and `error` methods take a single argument - a function that
  6719. * will be called when the request succeeds or fails respectively. The arguments passed into
  6720. * these functions are destructured representation of the response object passed into the
  6721. * `then` method. The response object has these properties:
  6722. *
  6723. * - **data** – `{string|Object}` – The response body transformed with the transform
  6724. * functions.
  6725. * - **status** – `{number}` – HTTP status code of the response.
  6726. * - **headers** – `{function([headerName])}` – Header getter function.
  6727. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  6728. *
  6729. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  6730. * requests. This is primarily meant to be used for debugging purposes.
  6731. *
  6732. *
  6733. * @example
  6734. <example>
  6735. <file name="index.html">
  6736. <div ng-controller="FetchCtrl">
  6737. <select ng-model="method">
  6738. <option>GET</option>
  6739. <option>JSONP</option>
  6740. </select>
  6741. <input type="text" ng-model="url" size="80"/>
  6742. <button ng-click="fetch()">fetch</button><br>
  6743. <button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  6744. <button
  6745. ng-click="updateModel('JSONP',
  6746. 'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  6747. Sample JSONP
  6748. </button>
  6749. <button
  6750. ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  6751. Invalid JSONP
  6752. </button>
  6753. <pre>http status code: {{status}}</pre>
  6754. <pre>http response data: {{data}}</pre>
  6755. </div>
  6756. </file>
  6757. <file name="script.js">
  6758. function FetchCtrl($scope, $http, $templateCache) {
  6759. $scope.method = 'GET';
  6760. $scope.url = 'http-hello.html';
  6761. $scope.fetch = function() {
  6762. $scope.code = null;
  6763. $scope.response = null;
  6764. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  6765. success(function(data, status) {
  6766. $scope.status = status;
  6767. $scope.data = data;
  6768. }).
  6769. error(function(data, status) {
  6770. $scope.data = data || "Request failed";
  6771. $scope.status = status;
  6772. });
  6773. };
  6774. $scope.updateModel = function(method, url) {
  6775. $scope.method = method;
  6776. $scope.url = url;
  6777. };
  6778. }
  6779. </file>
  6780. <file name="http-hello.html">
  6781. Hello, $http!
  6782. </file>
  6783. <file name="scenario.js">
  6784. it('should make an xhr GET request', function() {
  6785. element(':button:contains("Sample GET")').click();
  6786. element(':button:contains("fetch")').click();
  6787. expect(binding('status')).toBe('200');
  6788. expect(binding('data')).toMatch(/Hello, \$http!/);
  6789. });
  6790. it('should make a JSONP request to angularjs.org', function() {
  6791. element(':button:contains("Sample JSONP")').click();
  6792. element(':button:contains("fetch")').click();
  6793. expect(binding('status')).toBe('200');
  6794. expect(binding('data')).toMatch(/Super Hero!/);
  6795. });
  6796. it('should make JSONP request to invalid URL and invoke the error handler',
  6797. function() {
  6798. element(':button:contains("Invalid JSONP")').click();
  6799. element(':button:contains("fetch")').click();
  6800. expect(binding('status')).toBe('0');
  6801. expect(binding('data')).toBe('Request failed');
  6802. });
  6803. </file>
  6804. </example>
  6805. */
  6806. function $http(requestConfig) {
  6807. var config = {
  6808. transformRequest: defaults.transformRequest,
  6809. transformResponse: defaults.transformResponse
  6810. };
  6811. var headers = mergeHeaders(requestConfig);
  6812. extend(config, requestConfig);
  6813. config.headers = headers;
  6814. config.method = uppercase(config.method);
  6815. var xsrfValue = urlIsSameOrigin(config.url)
  6816. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  6817. : undefined;
  6818. if (xsrfValue) {
  6819. headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  6820. }
  6821. var serverRequest = function(config) {
  6822. headers = config.headers;
  6823. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  6824. // strip content-type if data is undefined
  6825. if (isUndefined(config.data)) {
  6826. forEach(headers, function(value, header) {
  6827. if (lowercase(header) === 'content-type') {
  6828. delete headers[header];
  6829. }
  6830. });
  6831. }
  6832. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  6833. config.withCredentials = defaults.withCredentials;
  6834. }
  6835. // send request
  6836. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  6837. };
  6838. var chain = [serverRequest, undefined];
  6839. var promise = $q.when(config);
  6840. // apply interceptors
  6841. forEach(reversedInterceptors, function(interceptor) {
  6842. if (interceptor.request || interceptor.requestError) {
  6843. chain.unshift(interceptor.request, interceptor.requestError);
  6844. }
  6845. if (interceptor.response || interceptor.responseError) {
  6846. chain.push(interceptor.response, interceptor.responseError);
  6847. }
  6848. });
  6849. while(chain.length) {
  6850. var thenFn = chain.shift();
  6851. var rejectFn = chain.shift();
  6852. promise = promise.then(thenFn, rejectFn);
  6853. }
  6854. promise.success = function(fn) {
  6855. promise.then(function(response) {
  6856. fn(response.data, response.status, response.headers, config);
  6857. });
  6858. return promise;
  6859. };
  6860. promise.error = function(fn) {
  6861. promise.then(null, function(response) {
  6862. fn(response.data, response.status, response.headers, config);
  6863. });
  6864. return promise;
  6865. };
  6866. return promise;
  6867. function transformResponse(response) {
  6868. // make a copy since the response must be cacheable
  6869. var resp = extend({}, response, {
  6870. data: transformData(response.data, response.headers, config.transformResponse)
  6871. });
  6872. return (isSuccess(response.status))
  6873. ? resp
  6874. : $q.reject(resp);
  6875. }
  6876. function mergeHeaders(config) {
  6877. var defHeaders = defaults.headers,
  6878. reqHeaders = extend({}, config.headers),
  6879. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  6880. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  6881. // execute if header value is function
  6882. execHeaders(defHeaders);
  6883. execHeaders(reqHeaders);
  6884. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  6885. defaultHeadersIteration:
  6886. for (defHeaderName in defHeaders) {
  6887. lowercaseDefHeaderName = lowercase(defHeaderName);
  6888. for (reqHeaderName in reqHeaders) {
  6889. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  6890. continue defaultHeadersIteration;
  6891. }
  6892. }
  6893. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  6894. }
  6895. return reqHeaders;
  6896. function execHeaders(headers) {
  6897. var headerContent;
  6898. forEach(headers, function(headerFn, header) {
  6899. if (isFunction(headerFn)) {
  6900. headerContent = headerFn();
  6901. if (headerContent != null) {
  6902. headers[header] = headerContent;
  6903. } else {
  6904. delete headers[header];
  6905. }
  6906. }
  6907. });
  6908. }
  6909. }
  6910. }
  6911. $http.pendingRequests = [];
  6912. /**
  6913. * @ngdoc method
  6914. * @name ng.$http#get
  6915. * @methodOf ng.$http
  6916. *
  6917. * @description
  6918. * Shortcut method to perform `GET` request.
  6919. *
  6920. * @param {string} url Relative or absolute URL specifying the destination of the request
  6921. * @param {Object=} config Optional configuration object
  6922. * @returns {HttpPromise} Future object
  6923. */
  6924. /**
  6925. * @ngdoc method
  6926. * @name ng.$http#delete
  6927. * @methodOf ng.$http
  6928. *
  6929. * @description
  6930. * Shortcut method to perform `DELETE` request.
  6931. *
  6932. * @param {string} url Relative or absolute URL specifying the destination of the request
  6933. * @param {Object=} config Optional configuration object
  6934. * @returns {HttpPromise} Future object
  6935. */
  6936. /**
  6937. * @ngdoc method
  6938. * @name ng.$http#head
  6939. * @methodOf ng.$http
  6940. *
  6941. * @description
  6942. * Shortcut method to perform `HEAD` request.
  6943. *
  6944. * @param {string} url Relative or absolute URL specifying the destination of the request
  6945. * @param {Object=} config Optional configuration object
  6946. * @returns {HttpPromise} Future object
  6947. */
  6948. /**
  6949. * @ngdoc method
  6950. * @name ng.$http#jsonp
  6951. * @methodOf ng.$http
  6952. *
  6953. * @description
  6954. * Shortcut method to perform `JSONP` request.
  6955. *
  6956. * @param {string} url Relative or absolute URL specifying the destination of the request.
  6957. * Should contain `JSON_CALLBACK` string.
  6958. * @param {Object=} config Optional configuration object
  6959. * @returns {HttpPromise} Future object
  6960. */
  6961. createShortMethods('get', 'delete', 'head', 'jsonp');
  6962. /**
  6963. * @ngdoc method
  6964. * @name ng.$http#post
  6965. * @methodOf ng.$http
  6966. *
  6967. * @description
  6968. * Shortcut method to perform `POST` request.
  6969. *
  6970. * @param {string} url Relative or absolute URL specifying the destination of the request
  6971. * @param {*} data Request content
  6972. * @param {Object=} config Optional configuration object
  6973. * @returns {HttpPromise} Future object
  6974. */
  6975. /**
  6976. * @ngdoc method
  6977. * @name ng.$http#put
  6978. * @methodOf ng.$http
  6979. *
  6980. * @description
  6981. * Shortcut method to perform `PUT` request.
  6982. *
  6983. * @param {string} url Relative or absolute URL specifying the destination of the request
  6984. * @param {*} data Request content
  6985. * @param {Object=} config Optional configuration object
  6986. * @returns {HttpPromise} Future object
  6987. */
  6988. createShortMethodsWithData('post', 'put');
  6989. /**
  6990. * @ngdoc property
  6991. * @name ng.$http#defaults
  6992. * @propertyOf ng.$http
  6993. *
  6994. * @description
  6995. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  6996. * default headers, withCredentials as well as request and response transformations.
  6997. *
  6998. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  6999. */
  7000. $http.defaults = defaults;
  7001. return $http;
  7002. function createShortMethods(names) {
  7003. forEach(arguments, function(name) {
  7004. $http[name] = function(url, config) {
  7005. return $http(extend(config || {}, {
  7006. method: name,
  7007. url: url
  7008. }));
  7009. };
  7010. });
  7011. }
  7012. function createShortMethodsWithData(name) {
  7013. forEach(arguments, function(name) {
  7014. $http[name] = function(url, data, config) {
  7015. return $http(extend(config || {}, {
  7016. method: name,
  7017. url: url,
  7018. data: data
  7019. }));
  7020. };
  7021. });
  7022. }
  7023. /**
  7024. * Makes the request.
  7025. *
  7026. * !!! ACCESSES CLOSURE VARS:
  7027. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  7028. */
  7029. function sendReq(config, reqData, reqHeaders) {
  7030. var deferred = $q.defer(),
  7031. promise = deferred.promise,
  7032. cache,
  7033. cachedResp,
  7034. url = buildUrl(config.url, config.params);
  7035. $http.pendingRequests.push(config);
  7036. promise.then(removePendingReq, removePendingReq);
  7037. if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
  7038. cache = isObject(config.cache) ? config.cache
  7039. : isObject(defaults.cache) ? defaults.cache
  7040. : defaultCache;
  7041. }
  7042. if (cache) {
  7043. cachedResp = cache.get(url);
  7044. if (isDefined(cachedResp)) {
  7045. if (cachedResp.then) {
  7046. // cached request has already been sent, but there is no response yet
  7047. cachedResp.then(removePendingReq, removePendingReq);
  7048. return cachedResp;
  7049. } else {
  7050. // serving from cache
  7051. if (isArray(cachedResp)) {
  7052. resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
  7053. } else {
  7054. resolvePromise(cachedResp, 200, {});
  7055. }
  7056. }
  7057. } else {
  7058. // put the promise for the non-transformed response into cache as a placeholder
  7059. cache.put(url, promise);
  7060. }
  7061. }
  7062. // if we won't have the response in cache, send the request to the backend
  7063. if (isUndefined(cachedResp)) {
  7064. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  7065. config.withCredentials, config.responseType);
  7066. }
  7067. return promise;
  7068. /**
  7069. * Callback registered to $httpBackend():
  7070. * - caches the response if desired
  7071. * - resolves the raw $http promise
  7072. * - calls $apply
  7073. */
  7074. function done(status, response, headersString) {
  7075. if (cache) {
  7076. if (isSuccess(status)) {
  7077. cache.put(url, [status, response, parseHeaders(headersString)]);
  7078. } else {
  7079. // remove promise from the cache
  7080. cache.remove(url);
  7081. }
  7082. }
  7083. resolvePromise(response, status, headersString);
  7084. if (!$rootScope.$$phase) $rootScope.$apply();
  7085. }
  7086. /**
  7087. * Resolves the raw $http promise.
  7088. */
  7089. function resolvePromise(response, status, headers) {
  7090. // normalize internal statuses to 0
  7091. status = Math.max(status, 0);
  7092. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  7093. data: response,
  7094. status: status,
  7095. headers: headersGetter(headers),
  7096. config: config
  7097. });
  7098. }
  7099. function removePendingReq() {
  7100. var idx = indexOf($http.pendingRequests, config);
  7101. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  7102. }
  7103. }
  7104. function buildUrl(url, params) {
  7105. if (!params) return url;
  7106. var parts = [];
  7107. forEachSorted(params, function(value, key) {
  7108. if (value === null || isUndefined(value)) return;
  7109. if (!isArray(value)) value = [value];
  7110. forEach(value, function(v) {
  7111. if (isObject(v)) {
  7112. v = toJson(v);
  7113. }
  7114. parts.push(encodeUriQuery(key) + '=' +
  7115. encodeUriQuery(v));
  7116. });
  7117. });
  7118. return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  7119. }
  7120. }];
  7121. }
  7122. function createXhr(method) {
  7123. // IE8 doesn't support PATCH method, but the ActiveX object does
  7124. /* global ActiveXObject */
  7125. return (msie <= 8 && lowercase(method) === 'patch')
  7126. ? new ActiveXObject('Microsoft.XMLHTTP')
  7127. : new window.XMLHttpRequest();
  7128. }
  7129. /**
  7130. * @ngdoc object
  7131. * @name ng.$httpBackend
  7132. * @requires $browser
  7133. * @requires $window
  7134. * @requires $document
  7135. *
  7136. * @description
  7137. * HTTP backend used by the {@link ng.$http service} that delegates to
  7138. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  7139. *
  7140. * You should never need to use this service directly, instead use the higher-level abstractions:
  7141. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  7142. *
  7143. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  7144. * $httpBackend} which can be trained with responses.
  7145. */
  7146. function $HttpBackendProvider() {
  7147. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  7148. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  7149. }];
  7150. }
  7151. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  7152. var ABORTED = -1;
  7153. // TODO(vojta): fix the signature
  7154. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  7155. var status;
  7156. $browser.$$incOutstandingRequestCount();
  7157. url = url || $browser.url();
  7158. if (lowercase(method) == 'jsonp') {
  7159. var callbackId = '_' + (callbacks.counter++).toString(36);
  7160. callbacks[callbackId] = function(data) {
  7161. callbacks[callbackId].data = data;
  7162. };
  7163. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  7164. function() {
  7165. if (callbacks[callbackId].data) {
  7166. completeRequest(callback, 200, callbacks[callbackId].data);
  7167. } else {
  7168. completeRequest(callback, status || -2);
  7169. }
  7170. callbacks[callbackId] = angular.noop;
  7171. });
  7172. } else {
  7173. var xhr = createXhr(method);
  7174. xhr.open(method, url, true);
  7175. forEach(headers, function(value, key) {
  7176. if (isDefined(value)) {
  7177. xhr.setRequestHeader(key, value);
  7178. }
  7179. });
  7180. // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
  7181. // response is in the cache. the promise api will ensure that to the app code the api is
  7182. // always async
  7183. xhr.onreadystatechange = function() {
  7184. // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by
  7185. // xhrs that are resolved while the app is in the background (see #5426).
  7186. // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before
  7187. // continuing
  7188. //
  7189. // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and
  7190. // Safari respectively.
  7191. if (xhr && xhr.readyState == 4) {
  7192. var responseHeaders = null,
  7193. response = null;
  7194. if(status !== ABORTED) {
  7195. responseHeaders = xhr.getAllResponseHeaders();
  7196. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  7197. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  7198. response = ('response' in xhr) ? xhr.response : xhr.responseText;
  7199. }
  7200. completeRequest(callback,
  7201. status || xhr.status,
  7202. response,
  7203. responseHeaders);
  7204. }
  7205. };
  7206. if (withCredentials) {
  7207. xhr.withCredentials = true;
  7208. }
  7209. if (responseType) {
  7210. xhr.responseType = responseType;
  7211. }
  7212. xhr.send(post || null);
  7213. }
  7214. if (timeout > 0) {
  7215. var timeoutId = $browserDefer(timeoutRequest, timeout);
  7216. } else if (timeout && timeout.then) {
  7217. timeout.then(timeoutRequest);
  7218. }
  7219. function timeoutRequest() {
  7220. status = ABORTED;
  7221. jsonpDone && jsonpDone();
  7222. xhr && xhr.abort();
  7223. }
  7224. function completeRequest(callback, status, response, headersString) {
  7225. // cancel timeout and subsequent timeout promise resolution
  7226. timeoutId && $browserDefer.cancel(timeoutId);
  7227. jsonpDone = xhr = null;
  7228. // fix status code when it is 0 (0 status is undocumented).
  7229. // Occurs when accessing file resources.
  7230. // On Android 4.1 stock browser it occurs while retrieving files from application cache.
  7231. status = (status === 0) ? (response ? 200 : 404) : status;
  7232. // normalize IE bug (http://bugs.jquery.com/ticket/1450)
  7233. status = status == 1223 ? 204 : status;
  7234. callback(status, response, headersString);
  7235. $browser.$$completeOutstandingRequest(noop);
  7236. }
  7237. };
  7238. function jsonpReq(url, done) {
  7239. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  7240. // - fetches local scripts via XHR and evals them
  7241. // - adds and immediately removes script elements from the document
  7242. var script = rawDocument.createElement('script'),
  7243. doneWrapper = function() {
  7244. script.onreadystatechange = script.onload = script.onerror = null;
  7245. rawDocument.body.removeChild(script);
  7246. if (done) done();
  7247. };
  7248. script.type = 'text/javascript';
  7249. script.src = url;
  7250. if (msie && msie <= 8) {
  7251. script.onreadystatechange = function() {
  7252. if (/loaded|complete/.test(script.readyState)) {
  7253. doneWrapper();
  7254. }
  7255. };
  7256. } else {
  7257. script.onload = script.onerror = function() {
  7258. doneWrapper();
  7259. };
  7260. }
  7261. rawDocument.body.appendChild(script);
  7262. return doneWrapper;
  7263. }
  7264. }
  7265. var $interpolateMinErr = minErr('$interpolate');
  7266. /**
  7267. * @ngdoc object
  7268. * @name ng.$interpolateProvider
  7269. * @function
  7270. *
  7271. * @description
  7272. *
  7273. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  7274. *
  7275. * @example
  7276. <doc:example module="customInterpolationApp">
  7277. <doc:source>
  7278. <script>
  7279. var customInterpolationApp = angular.module('customInterpolationApp', []);
  7280. customInterpolationApp.config(function($interpolateProvider) {
  7281. $interpolateProvider.startSymbol('//');
  7282. $interpolateProvider.endSymbol('//');
  7283. });
  7284. customInterpolationApp.controller('DemoController', function DemoController() {
  7285. this.label = "This binding is brought you by // interpolation symbols.";
  7286. });
  7287. </script>
  7288. <div ng-app="App" ng-controller="DemoController as demo">
  7289. //demo.label//
  7290. </div>
  7291. </doc:source>
  7292. <doc:scenario>
  7293. it('should interpolate binding with custom symbols', function() {
  7294. expect(binding('demo.label')).toBe('This binding is brought you by // interpolation symbols.');
  7295. });
  7296. </doc:scenario>
  7297. </doc:example>
  7298. */
  7299. function $InterpolateProvider() {
  7300. var startSymbol = '{{';
  7301. var endSymbol = '}}';
  7302. /**
  7303. * @ngdoc method
  7304. * @name ng.$interpolateProvider#startSymbol
  7305. * @methodOf ng.$interpolateProvider
  7306. * @description
  7307. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  7308. *
  7309. * @param {string=} value new value to set the starting symbol to.
  7310. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7311. */
  7312. this.startSymbol = function(value){
  7313. if (value) {
  7314. startSymbol = value;
  7315. return this;
  7316. } else {
  7317. return startSymbol;
  7318. }
  7319. };
  7320. /**
  7321. * @ngdoc method
  7322. * @name ng.$interpolateProvider#endSymbol
  7323. * @methodOf ng.$interpolateProvider
  7324. * @description
  7325. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7326. *
  7327. * @param {string=} value new value to set the ending symbol to.
  7328. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7329. */
  7330. this.endSymbol = function(value){
  7331. if (value) {
  7332. endSymbol = value;
  7333. return this;
  7334. } else {
  7335. return endSymbol;
  7336. }
  7337. };
  7338. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  7339. var startSymbolLength = startSymbol.length,
  7340. endSymbolLength = endSymbol.length;
  7341. /**
  7342. * @ngdoc function
  7343. * @name ng.$interpolate
  7344. * @function
  7345. *
  7346. * @requires $parse
  7347. * @requires $sce
  7348. *
  7349. * @description
  7350. *
  7351. * Compiles a string with markup into an interpolation function. This service is used by the
  7352. * HTML {@link ng.$compile $compile} service for data binding. See
  7353. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  7354. * interpolation markup.
  7355. *
  7356. *
  7357. <pre>
  7358. var $interpolate = ...; // injected
  7359. var exp = $interpolate('Hello {{name | uppercase}}!');
  7360. expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  7361. </pre>
  7362. *
  7363. *
  7364. * @param {string} text The text with markup to interpolate.
  7365. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  7366. * embedded expression in order to return an interpolation function. Strings with no
  7367. * embedded expression will return null for the interpolation function.
  7368. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  7369. * result through {@link ng.$sce#methods_getTrusted $sce.getTrusted(interpolatedResult,
  7370. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  7371. * provides Strict Contextual Escaping for details.
  7372. * @returns {function(context)} an interpolation function which is used to compute the
  7373. * interpolated string. The function has these parameters:
  7374. *
  7375. * * `context`: an object against which any expressions embedded in the strings are evaluated
  7376. * against.
  7377. *
  7378. */
  7379. function $interpolate(text, mustHaveExpression, trustedContext) {
  7380. var startIndex,
  7381. endIndex,
  7382. index = 0,
  7383. parts = [],
  7384. length = text.length,
  7385. hasInterpolation = false,
  7386. fn,
  7387. exp,
  7388. concat = [];
  7389. while(index < length) {
  7390. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  7391. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  7392. (index != startIndex) && parts.push(text.substring(index, startIndex));
  7393. parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
  7394. fn.exp = exp;
  7395. index = endIndex + endSymbolLength;
  7396. hasInterpolation = true;
  7397. } else {
  7398. // we did not find anything, so we have to add the remainder to the parts array
  7399. (index != length) && parts.push(text.substring(index));
  7400. index = length;
  7401. }
  7402. }
  7403. if (!(length = parts.length)) {
  7404. // we added, nothing, must have been an empty string.
  7405. parts.push('');
  7406. length = 1;
  7407. }
  7408. // Concatenating expressions makes it hard to reason about whether some combination of
  7409. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  7410. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  7411. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  7412. // make it obvious that you bound the value to some user controlled value. This helps reduce
  7413. // the load when auditing for XSS issues.
  7414. if (trustedContext && parts.length > 1) {
  7415. throw $interpolateMinErr('noconcat',
  7416. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  7417. "interpolations that concatenate multiple expressions when a trusted value is " +
  7418. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  7419. }
  7420. if (!mustHaveExpression || hasInterpolation) {
  7421. concat.length = length;
  7422. fn = function(context) {
  7423. try {
  7424. for(var i = 0, ii = length, part; i<ii; i++) {
  7425. if (typeof (part = parts[i]) == 'function') {
  7426. part = part(context);
  7427. if (trustedContext) {
  7428. part = $sce.getTrusted(trustedContext, part);
  7429. } else {
  7430. part = $sce.valueOf(part);
  7431. }
  7432. if (part === null || isUndefined(part)) {
  7433. part = '';
  7434. } else if (typeof part != 'string') {
  7435. part = toJson(part);
  7436. }
  7437. }
  7438. concat[i] = part;
  7439. }
  7440. return concat.join('');
  7441. }
  7442. catch(err) {
  7443. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  7444. err.toString());
  7445. $exceptionHandler(newErr);
  7446. }
  7447. };
  7448. fn.exp = text;
  7449. fn.parts = parts;
  7450. return fn;
  7451. }
  7452. }
  7453. /**
  7454. * @ngdoc method
  7455. * @name ng.$interpolate#startSymbol
  7456. * @methodOf ng.$interpolate
  7457. * @description
  7458. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  7459. *
  7460. * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
  7461. * the symbol.
  7462. *
  7463. * @returns {string} start symbol.
  7464. */
  7465. $interpolate.startSymbol = function() {
  7466. return startSymbol;
  7467. };
  7468. /**
  7469. * @ngdoc method
  7470. * @name ng.$interpolate#endSymbol
  7471. * @methodOf ng.$interpolate
  7472. * @description
  7473. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7474. *
  7475. * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
  7476. * the symbol.
  7477. *
  7478. * @returns {string} start symbol.
  7479. */
  7480. $interpolate.endSymbol = function() {
  7481. return endSymbol;
  7482. };
  7483. return $interpolate;
  7484. }];
  7485. }
  7486. function $IntervalProvider() {
  7487. this.$get = ['$rootScope', '$window', '$q',
  7488. function($rootScope, $window, $q) {
  7489. var intervals = {};
  7490. /**
  7491. * @ngdoc function
  7492. * @name ng.$interval
  7493. *
  7494. * @description
  7495. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  7496. * milliseconds.
  7497. *
  7498. * The return value of registering an interval function is a promise. This promise will be
  7499. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  7500. * run indefinitely if `count` is not defined. The value of the notification will be the
  7501. * number of iterations that have run.
  7502. * To cancel an interval, call `$interval.cancel(promise)`.
  7503. *
  7504. * In tests you can use {@link ngMock.$interval#methods_flush `$interval.flush(millis)`} to
  7505. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  7506. * time.
  7507. *
  7508. * <div class="alert alert-warning">
  7509. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  7510. * with them. In particular they are not automatically destroyed when a controller's scope or a
  7511. * directive's element are destroyed.
  7512. * You should take this into consideration and make sure to always cancel the interval at the
  7513. * appropriate moment. See the example below for more details on how and when to do this.
  7514. * </div>
  7515. *
  7516. * @param {function()} fn A function that should be called repeatedly.
  7517. * @param {number} delay Number of milliseconds between each function call.
  7518. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  7519. * indefinitely.
  7520. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  7521. * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
  7522. * @returns {promise} A promise which will be notified on each iteration.
  7523. *
  7524. * @example
  7525. <doc:example module="time">
  7526. <doc:source>
  7527. <script>
  7528. function Ctrl2($scope,$interval) {
  7529. $scope.format = 'M/d/yy h:mm:ss a';
  7530. $scope.blood_1 = 100;
  7531. $scope.blood_2 = 120;
  7532. var stop;
  7533. $scope.fight = function() {
  7534. // Don't start a new fight if we are already fighting
  7535. if ( angular.isDefined(stop) ) return;
  7536. stop = $interval(function() {
  7537. if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  7538. $scope.blood_1 = $scope.blood_1 - 3;
  7539. $scope.blood_2 = $scope.blood_2 - 4;
  7540. } else {
  7541. $scope.stopFight();
  7542. }
  7543. }, 100);
  7544. };
  7545. $scope.stopFight = function() {
  7546. if (angular.isDefined(stop)) {
  7547. $interval.cancel(stop);
  7548. stop = undefined;
  7549. }
  7550. };
  7551. $scope.resetFight = function() {
  7552. $scope.blood_1 = 100;
  7553. $scope.blood_2 = 120;
  7554. }
  7555. $scope.$on('$destroy', function() {
  7556. // Make sure that the interval is destroyed too
  7557. $scope.stopFight();
  7558. });
  7559. }
  7560. angular.module('time', [])
  7561. // Register the 'myCurrentTime' directive factory method.
  7562. // We inject $interval and dateFilter service since the factory method is DI.
  7563. .directive('myCurrentTime', function($interval, dateFilter) {
  7564. // return the directive link function. (compile function not needed)
  7565. return function(scope, element, attrs) {
  7566. var format, // date format
  7567. stopTime; // so that we can cancel the time updates
  7568. // used to update the UI
  7569. function updateTime() {
  7570. element.text(dateFilter(new Date(), format));
  7571. }
  7572. // watch the expression, and update the UI on change.
  7573. scope.$watch(attrs.myCurrentTime, function(value) {
  7574. format = value;
  7575. updateTime();
  7576. });
  7577. stopTime = $interval(updateTime, 1000);
  7578. // listen on DOM destroy (removal) event, and cancel the next UI update
  7579. // to prevent updating time ofter the DOM element was removed.
  7580. element.bind('$destroy', function() {
  7581. $interval.cancel(stopTime);
  7582. });
  7583. }
  7584. });
  7585. </script>
  7586. <div>
  7587. <div ng-controller="Ctrl2">
  7588. Date format: <input ng-model="format"> <hr/>
  7589. Current time is: <span my-current-time="format"></span>
  7590. <hr/>
  7591. Blood 1 : <font color='red'>{{blood_1}}</font>
  7592. Blood 2 : <font color='red'>{{blood_2}}</font>
  7593. <button type="button" data-ng-click="fight()">Fight</button>
  7594. <button type="button" data-ng-click="stopFight()">StopFight</button>
  7595. <button type="button" data-ng-click="resetFight()">resetFight</button>
  7596. </div>
  7597. </div>
  7598. </doc:source>
  7599. </doc:example>
  7600. */
  7601. function interval(fn, delay, count, invokeApply) {
  7602. var setInterval = $window.setInterval,
  7603. clearInterval = $window.clearInterval,
  7604. deferred = $q.defer(),
  7605. promise = deferred.promise,
  7606. iteration = 0,
  7607. skipApply = (isDefined(invokeApply) && !invokeApply);
  7608. count = isDefined(count) ? count : 0,
  7609. promise.then(null, null, fn);
  7610. promise.$$intervalId = setInterval(function tick() {
  7611. deferred.notify(iteration++);
  7612. if (count > 0 && iteration >= count) {
  7613. deferred.resolve(iteration);
  7614. clearInterval(promise.$$intervalId);
  7615. delete intervals[promise.$$intervalId];
  7616. }
  7617. if (!skipApply) $rootScope.$apply();
  7618. }, delay);
  7619. intervals[promise.$$intervalId] = deferred;
  7620. return promise;
  7621. }
  7622. /**
  7623. * @ngdoc function
  7624. * @name ng.$interval#cancel
  7625. * @methodOf ng.$interval
  7626. *
  7627. * @description
  7628. * Cancels a task associated with the `promise`.
  7629. *
  7630. * @param {number} promise Promise returned by the `$interval` function.
  7631. * @returns {boolean} Returns `true` if the task was successfully canceled.
  7632. */
  7633. interval.cancel = function(promise) {
  7634. if (promise && promise.$$intervalId in intervals) {
  7635. intervals[promise.$$intervalId].reject('canceled');
  7636. clearInterval(promise.$$intervalId);
  7637. delete intervals[promise.$$intervalId];
  7638. return true;
  7639. }
  7640. return false;
  7641. };
  7642. return interval;
  7643. }];
  7644. }
  7645. /**
  7646. * @ngdoc object
  7647. * @name ng.$locale
  7648. *
  7649. * @description
  7650. * $locale service provides localization rules for various Angular components. As of right now the
  7651. * only public api is:
  7652. *
  7653. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  7654. */
  7655. function $LocaleProvider(){
  7656. this.$get = function() {
  7657. return {
  7658. id: 'en-us',
  7659. NUMBER_FORMATS: {
  7660. DECIMAL_SEP: '.',
  7661. GROUP_SEP: ',',
  7662. PATTERNS: [
  7663. { // Decimal Pattern
  7664. minInt: 1,
  7665. minFrac: 0,
  7666. maxFrac: 3,
  7667. posPre: '',
  7668. posSuf: '',
  7669. negPre: '-',
  7670. negSuf: '',
  7671. gSize: 3,
  7672. lgSize: 3
  7673. },{ //Currency Pattern
  7674. minInt: 1,
  7675. minFrac: 2,
  7676. maxFrac: 2,
  7677. posPre: '\u00A4',
  7678. posSuf: '',
  7679. negPre: '(\u00A4',
  7680. negSuf: ')',
  7681. gSize: 3,
  7682. lgSize: 3
  7683. }
  7684. ],
  7685. CURRENCY_SYM: '$'
  7686. },
  7687. DATETIME_FORMATS: {
  7688. MONTH:
  7689. 'January,February,March,April,May,June,July,August,September,October,November,December'
  7690. .split(','),
  7691. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  7692. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  7693. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  7694. AMPMS: ['AM','PM'],
  7695. medium: 'MMM d, y h:mm:ss a',
  7696. short: 'M/d/yy h:mm a',
  7697. fullDate: 'EEEE, MMMM d, y',
  7698. longDate: 'MMMM d, y',
  7699. mediumDate: 'MMM d, y',
  7700. shortDate: 'M/d/yy',
  7701. mediumTime: 'h:mm:ss a',
  7702. shortTime: 'h:mm a'
  7703. },
  7704. pluralCat: function(num) {
  7705. if (num === 1) {
  7706. return 'one';
  7707. }
  7708. return 'other';
  7709. }
  7710. };
  7711. };
  7712. }
  7713. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  7714. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  7715. var $locationMinErr = minErr('$location');
  7716. /**
  7717. * Encode path using encodeUriSegment, ignoring forward slashes
  7718. *
  7719. * @param {string} path Path to encode
  7720. * @returns {string}
  7721. */
  7722. function encodePath(path) {
  7723. var segments = path.split('/'),
  7724. i = segments.length;
  7725. while (i--) {
  7726. segments[i] = encodeUriSegment(segments[i]);
  7727. }
  7728. return segments.join('/');
  7729. }
  7730. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  7731. var parsedUrl = urlResolve(absoluteUrl, appBase);
  7732. locationObj.$$protocol = parsedUrl.protocol;
  7733. locationObj.$$host = parsedUrl.hostname;
  7734. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  7735. }
  7736. function parseAppUrl(relativeUrl, locationObj, appBase) {
  7737. var prefixed = (relativeUrl.charAt(0) !== '/');
  7738. if (prefixed) {
  7739. relativeUrl = '/' + relativeUrl;
  7740. }
  7741. var match = urlResolve(relativeUrl, appBase);
  7742. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  7743. match.pathname.substring(1) : match.pathname);
  7744. locationObj.$$search = parseKeyValue(match.search);
  7745. locationObj.$$hash = decodeURIComponent(match.hash);
  7746. // make sure path starts with '/';
  7747. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  7748. locationObj.$$path = '/' + locationObj.$$path;
  7749. }
  7750. }
  7751. /**
  7752. *
  7753. * @param {string} begin
  7754. * @param {string} whole
  7755. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  7756. * expected string.
  7757. */
  7758. function beginsWith(begin, whole) {
  7759. if (whole.indexOf(begin) === 0) {
  7760. return whole.substr(begin.length);
  7761. }
  7762. }
  7763. function stripHash(url) {
  7764. var index = url.indexOf('#');
  7765. return index == -1 ? url : url.substr(0, index);
  7766. }
  7767. function stripFile(url) {
  7768. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  7769. }
  7770. /* return the server only (scheme://host:port) */
  7771. function serverBase(url) {
  7772. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  7773. }
  7774. /**
  7775. * LocationHtml5Url represents an url
  7776. * This object is exposed as $location service when HTML5 mode is enabled and supported
  7777. *
  7778. * @constructor
  7779. * @param {string} appBase application base URL
  7780. * @param {string} basePrefix url path prefix
  7781. */
  7782. function LocationHtml5Url(appBase, basePrefix) {
  7783. this.$$html5 = true;
  7784. basePrefix = basePrefix || '';
  7785. var appBaseNoFile = stripFile(appBase);
  7786. parseAbsoluteUrl(appBase, this, appBase);
  7787. /**
  7788. * Parse given html5 (regular) url string into properties
  7789. * @param {string} newAbsoluteUrl HTML5 url
  7790. * @private
  7791. */
  7792. this.$$parse = function(url) {
  7793. var pathUrl = beginsWith(appBaseNoFile, url);
  7794. if (!isString(pathUrl)) {
  7795. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  7796. appBaseNoFile);
  7797. }
  7798. parseAppUrl(pathUrl, this, appBase);
  7799. if (!this.$$path) {
  7800. this.$$path = '/';
  7801. }
  7802. this.$$compose();
  7803. };
  7804. /**
  7805. * Compose url and update `absUrl` property
  7806. * @private
  7807. */
  7808. this.$$compose = function() {
  7809. var search = toKeyValue(this.$$search),
  7810. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  7811. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  7812. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  7813. };
  7814. this.$$rewrite = function(url) {
  7815. var appUrl, prevAppUrl;
  7816. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  7817. prevAppUrl = appUrl;
  7818. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  7819. return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  7820. } else {
  7821. return appBase + prevAppUrl;
  7822. }
  7823. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  7824. return appBaseNoFile + appUrl;
  7825. } else if (appBaseNoFile == url + '/') {
  7826. return appBaseNoFile;
  7827. }
  7828. };
  7829. }
  7830. /**
  7831. * LocationHashbangUrl represents url
  7832. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  7833. * It also serves as the base class for html5 mode fallback on legacy browsers.
  7834. *
  7835. * @constructor
  7836. * @param {string} appBase application base URL
  7837. * @param {string} hashPrefix hashbang prefix
  7838. */
  7839. function LocationHashbangUrl(appBase, hashPrefix) {
  7840. var appBaseNoFile = stripFile(appBase);
  7841. parseAbsoluteUrl(appBase, this, appBase);
  7842. /**
  7843. * Parse given hashbang url into properties
  7844. * @param {string} url Hashbang url
  7845. * @private
  7846. */
  7847. this.$$parse = function(url) {
  7848. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  7849. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  7850. ? beginsWith(hashPrefix, withoutBaseUrl)
  7851. : (this.$$html5)
  7852. ? withoutBaseUrl
  7853. : '';
  7854. if (!isString(withoutHashUrl)) {
  7855. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  7856. hashPrefix);
  7857. }
  7858. parseAppUrl(withoutHashUrl, this, appBase);
  7859. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  7860. this.$$compose();
  7861. /*
  7862. * In Windows, on an anchor node on documents loaded from
  7863. * the filesystem, the browser will return a pathname
  7864. * prefixed with the drive name ('/C:/path') when a
  7865. * pathname without a drive is set:
  7866. * * a.setAttribute('href', '/foo')
  7867. * * a.pathname === '/C:/foo' //true
  7868. *
  7869. * Inside of Angular, we're always using pathnames that
  7870. * do not include drive names for routing.
  7871. */
  7872. function removeWindowsDriveName (path, url, base) {
  7873. /*
  7874. Matches paths for file protocol on windows,
  7875. such as /C:/foo/bar, and captures only /foo/bar.
  7876. */
  7877. var windowsFilePathExp = /^\/?.*?:(\/.*)/;
  7878. var firstPathSegmentMatch;
  7879. //Get the relative path from the input URL.
  7880. if (url.indexOf(base) === 0) {
  7881. url = url.replace(base, '');
  7882. }
  7883. /*
  7884. * The input URL intentionally contains a
  7885. * first path segment that ends with a colon.
  7886. */
  7887. if (windowsFilePathExp.exec(url)) {
  7888. return path;
  7889. }
  7890. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  7891. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  7892. }
  7893. };
  7894. /**
  7895. * Compose hashbang url and update `absUrl` property
  7896. * @private
  7897. */
  7898. this.$$compose = function() {
  7899. var search = toKeyValue(this.$$search),
  7900. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  7901. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  7902. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  7903. };
  7904. this.$$rewrite = function(url) {
  7905. if(stripHash(appBase) == stripHash(url)) {
  7906. return url;
  7907. }
  7908. };
  7909. }
  7910. /**
  7911. * LocationHashbangUrl represents url
  7912. * This object is exposed as $location service when html5 history api is enabled but the browser
  7913. * does not support it.
  7914. *
  7915. * @constructor
  7916. * @param {string} appBase application base URL
  7917. * @param {string} hashPrefix hashbang prefix
  7918. */
  7919. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  7920. this.$$html5 = true;
  7921. LocationHashbangUrl.apply(this, arguments);
  7922. var appBaseNoFile = stripFile(appBase);
  7923. this.$$rewrite = function(url) {
  7924. var appUrl;
  7925. if ( appBase == stripHash(url) ) {
  7926. return url;
  7927. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  7928. return appBase + hashPrefix + appUrl;
  7929. } else if ( appBaseNoFile === url + '/') {
  7930. return appBaseNoFile;
  7931. }
  7932. };
  7933. }
  7934. LocationHashbangInHtml5Url.prototype =
  7935. LocationHashbangUrl.prototype =
  7936. LocationHtml5Url.prototype = {
  7937. /**
  7938. * Are we in html5 mode?
  7939. * @private
  7940. */
  7941. $$html5: false,
  7942. /**
  7943. * Has any change been replacing ?
  7944. * @private
  7945. */
  7946. $$replace: false,
  7947. /**
  7948. * @ngdoc method
  7949. * @name ng.$location#absUrl
  7950. * @methodOf ng.$location
  7951. *
  7952. * @description
  7953. * This method is getter only.
  7954. *
  7955. * Return full url representation with all segments encoded according to rules specified in
  7956. * {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
  7957. *
  7958. * @return {string} full url
  7959. */
  7960. absUrl: locationGetter('$$absUrl'),
  7961. /**
  7962. * @ngdoc method
  7963. * @name ng.$location#url
  7964. * @methodOf ng.$location
  7965. *
  7966. * @description
  7967. * This method is getter / setter.
  7968. *
  7969. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  7970. *
  7971. * Change path, search and hash, when called with parameter and return `$location`.
  7972. *
  7973. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  7974. * @param {string=} replace The path that will be changed
  7975. * @return {string} url
  7976. */
  7977. url: function(url, replace) {
  7978. if (isUndefined(url))
  7979. return this.$$url;
  7980. var match = PATH_MATCH.exec(url);
  7981. if (match[1]) this.path(decodeURIComponent(match[1]));
  7982. if (match[2] || match[1]) this.search(match[3] || '');
  7983. this.hash(match[5] || '', replace);
  7984. return this;
  7985. },
  7986. /**
  7987. * @ngdoc method
  7988. * @name ng.$location#protocol
  7989. * @methodOf ng.$location
  7990. *
  7991. * @description
  7992. * This method is getter only.
  7993. *
  7994. * Return protocol of current url.
  7995. *
  7996. * @return {string} protocol of current url
  7997. */
  7998. protocol: locationGetter('$$protocol'),
  7999. /**
  8000. * @ngdoc method
  8001. * @name ng.$location#host
  8002. * @methodOf ng.$location
  8003. *
  8004. * @description
  8005. * This method is getter only.
  8006. *
  8007. * Return host of current url.
  8008. *
  8009. * @return {string} host of current url.
  8010. */
  8011. host: locationGetter('$$host'),
  8012. /**
  8013. * @ngdoc method
  8014. * @name ng.$location#port
  8015. * @methodOf ng.$location
  8016. *
  8017. * @description
  8018. * This method is getter only.
  8019. *
  8020. * Return port of current url.
  8021. *
  8022. * @return {Number} port
  8023. */
  8024. port: locationGetter('$$port'),
  8025. /**
  8026. * @ngdoc method
  8027. * @name ng.$location#path
  8028. * @methodOf ng.$location
  8029. *
  8030. * @description
  8031. * This method is getter / setter.
  8032. *
  8033. * Return path of current url when called without any parameter.
  8034. *
  8035. * Change path when called with parameter and return `$location`.
  8036. *
  8037. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  8038. * if it is missing.
  8039. *
  8040. * @param {string=} path New path
  8041. * @return {string} path
  8042. */
  8043. path: locationGetterSetter('$$path', function(path) {
  8044. return path.charAt(0) == '/' ? path : '/' + path;
  8045. }),
  8046. /**
  8047. * @ngdoc method
  8048. * @name ng.$location#search
  8049. * @methodOf ng.$location
  8050. *
  8051. * @description
  8052. * This method is getter / setter.
  8053. *
  8054. * Return search part (as object) of current url when called without any parameter.
  8055. *
  8056. * Change search part when called with parameter and return `$location`.
  8057. *
  8058. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  8059. * hash object. Hash object may contain an array of values, which will be decoded as duplicates in
  8060. * the url.
  8061. *
  8062. * @param {(string|Array<string>)=} paramValue If `search` is a string, then `paramValue` will override only a
  8063. * single search parameter. If `paramValue` is an array, it will set the parameter as a
  8064. * comma-separated value. If `paramValue` is `null`, the parameter will be deleted.
  8065. *
  8066. * @return {string} search
  8067. */
  8068. search: function(search, paramValue) {
  8069. switch (arguments.length) {
  8070. case 0:
  8071. return this.$$search;
  8072. case 1:
  8073. if (isString(search)) {
  8074. this.$$search = parseKeyValue(search);
  8075. } else if (isObject(search)) {
  8076. this.$$search = search;
  8077. } else {
  8078. throw $locationMinErr('isrcharg',
  8079. 'The first argument of the `$location#search()` call must be a string or an object.');
  8080. }
  8081. break;
  8082. default:
  8083. if (isUndefined(paramValue) || paramValue === null) {
  8084. delete this.$$search[search];
  8085. } else {
  8086. this.$$search[search] = paramValue;
  8087. }
  8088. }
  8089. this.$$compose();
  8090. return this;
  8091. },
  8092. /**
  8093. * @ngdoc method
  8094. * @name ng.$location#hash
  8095. * @methodOf ng.$location
  8096. *
  8097. * @description
  8098. * This method is getter / setter.
  8099. *
  8100. * Return hash fragment when called without any parameter.
  8101. *
  8102. * Change hash fragment when called with parameter and return `$location`.
  8103. *
  8104. * @param {string=} hash New hash fragment
  8105. * @return {string} hash
  8106. */
  8107. hash: locationGetterSetter('$$hash', identity),
  8108. /**
  8109. * @ngdoc method
  8110. * @name ng.$location#replace
  8111. * @methodOf ng.$location
  8112. *
  8113. * @description
  8114. * If called, all changes to $location during current `$digest` will be replacing current history
  8115. * record, instead of adding new one.
  8116. */
  8117. replace: function() {
  8118. this.$$replace = true;
  8119. return this;
  8120. }
  8121. };
  8122. function locationGetter(property) {
  8123. return function() {
  8124. return this[property];
  8125. };
  8126. }
  8127. function locationGetterSetter(property, preprocess) {
  8128. return function(value) {
  8129. if (isUndefined(value))
  8130. return this[property];
  8131. this[property] = preprocess(value);
  8132. this.$$compose();
  8133. return this;
  8134. };
  8135. }
  8136. /**
  8137. * @ngdoc object
  8138. * @name ng.$location
  8139. *
  8140. * @requires $browser
  8141. * @requires $sniffer
  8142. * @requires $rootElement
  8143. *
  8144. * @description
  8145. * The $location service parses the URL in the browser address bar (based on the
  8146. * {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
  8147. * available to your application. Changes to the URL in the address bar are reflected into
  8148. * $location service and changes to $location are reflected into the browser address bar.
  8149. *
  8150. * **The $location service:**
  8151. *
  8152. * - Exposes the current URL in the browser address bar, so you can
  8153. * - Watch and observe the URL.
  8154. * - Change the URL.
  8155. * - Synchronizes the URL with the browser when the user
  8156. * - Changes the address bar.
  8157. * - Clicks the back or forward button (or clicks a History link).
  8158. * - Clicks on a link.
  8159. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  8160. *
  8161. * For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
  8162. * Services: Using $location}
  8163. */
  8164. /**
  8165. * @ngdoc object
  8166. * @name ng.$locationProvider
  8167. * @description
  8168. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  8169. */
  8170. function $LocationProvider(){
  8171. var hashPrefix = '',
  8172. html5Mode = false;
  8173. /**
  8174. * @ngdoc property
  8175. * @name ng.$locationProvider#hashPrefix
  8176. * @methodOf ng.$locationProvider
  8177. * @description
  8178. * @param {string=} prefix Prefix for hash part (containing path and search)
  8179. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8180. */
  8181. this.hashPrefix = function(prefix) {
  8182. if (isDefined(prefix)) {
  8183. hashPrefix = prefix;
  8184. return this;
  8185. } else {
  8186. return hashPrefix;
  8187. }
  8188. };
  8189. /**
  8190. * @ngdoc property
  8191. * @name ng.$locationProvider#html5Mode
  8192. * @methodOf ng.$locationProvider
  8193. * @description
  8194. * @param {boolean=} mode Use HTML5 strategy if available.
  8195. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8196. */
  8197. this.html5Mode = function(mode) {
  8198. if (isDefined(mode)) {
  8199. html5Mode = mode;
  8200. return this;
  8201. } else {
  8202. return html5Mode;
  8203. }
  8204. };
  8205. /**
  8206. * @ngdoc event
  8207. * @name ng.$location#$locationChangeStart
  8208. * @eventOf ng.$location
  8209. * @eventType broadcast on root scope
  8210. * @description
  8211. * Broadcasted before a URL will change. This change can be prevented by calling
  8212. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  8213. * details about event object. Upon successful change
  8214. * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
  8215. *
  8216. * @param {Object} angularEvent Synthetic event object.
  8217. * @param {string} newUrl New URL
  8218. * @param {string=} oldUrl URL that was before it was changed.
  8219. */
  8220. /**
  8221. * @ngdoc event
  8222. * @name ng.$location#$locationChangeSuccess
  8223. * @eventOf ng.$location
  8224. * @eventType broadcast on root scope
  8225. * @description
  8226. * Broadcasted after a URL was changed.
  8227. *
  8228. * @param {Object} angularEvent Synthetic event object.
  8229. * @param {string} newUrl New URL
  8230. * @param {string=} oldUrl URL that was before it was changed.
  8231. */
  8232. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  8233. function( $rootScope, $browser, $sniffer, $rootElement) {
  8234. var $location,
  8235. LocationMode,
  8236. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  8237. initialUrl = $browser.url(),
  8238. appBase;
  8239. if (html5Mode) {
  8240. appBase = serverBase(initialUrl) + (baseHref || '/');
  8241. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  8242. } else {
  8243. appBase = stripHash(initialUrl);
  8244. LocationMode = LocationHashbangUrl;
  8245. }
  8246. $location = new LocationMode(appBase, '#' + hashPrefix);
  8247. $location.$$parse($location.$$rewrite(initialUrl));
  8248. $rootElement.on('click', function(event) {
  8249. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  8250. // currently we open nice url link and redirect then
  8251. if (event.ctrlKey || event.metaKey || event.which == 2) return;
  8252. var elm = jqLite(event.target);
  8253. // traverse the DOM up to find first A tag
  8254. while (lowercase(elm[0].nodeName) !== 'a') {
  8255. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  8256. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  8257. }
  8258. var absHref = elm.prop('href');
  8259. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  8260. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  8261. // an animation.
  8262. absHref = urlResolve(absHref.animVal).href;
  8263. }
  8264. var rewrittenUrl = $location.$$rewrite(absHref);
  8265. if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
  8266. event.preventDefault();
  8267. if (rewrittenUrl != $browser.url()) {
  8268. // update location manually
  8269. $location.$$parse(rewrittenUrl);
  8270. $rootScope.$apply();
  8271. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  8272. window.angular['ff-684208-preventDefault'] = true;
  8273. }
  8274. }
  8275. });
  8276. // rewrite hashbang url <> html5 url
  8277. if ($location.absUrl() != initialUrl) {
  8278. $browser.url($location.absUrl(), true);
  8279. }
  8280. // update $location when $browser url changes
  8281. $browser.onUrlChange(function(newUrl) {
  8282. if ($location.absUrl() != newUrl) {
  8283. $rootScope.$evalAsync(function() {
  8284. var oldUrl = $location.absUrl();
  8285. $location.$$parse(newUrl);
  8286. if ($rootScope.$broadcast('$locationChangeStart', newUrl,
  8287. oldUrl).defaultPrevented) {
  8288. $location.$$parse(oldUrl);
  8289. $browser.url(oldUrl);
  8290. } else {
  8291. afterLocationChange(oldUrl);
  8292. }
  8293. });
  8294. if (!$rootScope.$$phase) $rootScope.$digest();
  8295. }
  8296. });
  8297. // update browser
  8298. var changeCounter = 0;
  8299. $rootScope.$watch(function $locationWatch() {
  8300. var oldUrl = $browser.url();
  8301. var currentReplace = $location.$$replace;
  8302. if (!changeCounter || oldUrl != $location.absUrl()) {
  8303. changeCounter++;
  8304. $rootScope.$evalAsync(function() {
  8305. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
  8306. defaultPrevented) {
  8307. $location.$$parse(oldUrl);
  8308. } else {
  8309. $browser.url($location.absUrl(), currentReplace);
  8310. afterLocationChange(oldUrl);
  8311. }
  8312. });
  8313. }
  8314. $location.$$replace = false;
  8315. return changeCounter;
  8316. });
  8317. return $location;
  8318. function afterLocationChange(oldUrl) {
  8319. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
  8320. }
  8321. }];
  8322. }
  8323. /**
  8324. * @ngdoc object
  8325. * @name ng.$log
  8326. * @requires $window
  8327. *
  8328. * @description
  8329. * Simple service for logging. Default implementation safely writes the message
  8330. * into the browser's console (if present).
  8331. *
  8332. * The main purpose of this service is to simplify debugging and troubleshooting.
  8333. *
  8334. * The default is to log `debug` messages. You can use
  8335. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  8336. *
  8337. * @example
  8338. <example>
  8339. <file name="script.js">
  8340. function LogCtrl($scope, $log) {
  8341. $scope.$log = $log;
  8342. $scope.message = 'Hello World!';
  8343. }
  8344. </file>
  8345. <file name="index.html">
  8346. <div ng-controller="LogCtrl">
  8347. <p>Reload this page with open console, enter text and hit the log button...</p>
  8348. Message:
  8349. <input type="text" ng-model="message"/>
  8350. <button ng-click="$log.log(message)">log</button>
  8351. <button ng-click="$log.warn(message)">warn</button>
  8352. <button ng-click="$log.info(message)">info</button>
  8353. <button ng-click="$log.error(message)">error</button>
  8354. </div>
  8355. </file>
  8356. </example>
  8357. */
  8358. /**
  8359. * @ngdoc object
  8360. * @name ng.$logProvider
  8361. * @description
  8362. * Use the `$logProvider` to configure how the application logs messages
  8363. */
  8364. function $LogProvider(){
  8365. var debug = true,
  8366. self = this;
  8367. /**
  8368. * @ngdoc property
  8369. * @name ng.$logProvider#debugEnabled
  8370. * @methodOf ng.$logProvider
  8371. * @description
  8372. * @param {string=} flag enable or disable debug level messages
  8373. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8374. */
  8375. this.debugEnabled = function(flag) {
  8376. if (isDefined(flag)) {
  8377. debug = flag;
  8378. return this;
  8379. } else {
  8380. return debug;
  8381. }
  8382. };
  8383. this.$get = ['$window', function($window){
  8384. return {
  8385. /**
  8386. * @ngdoc method
  8387. * @name ng.$log#log
  8388. * @methodOf ng.$log
  8389. *
  8390. * @description
  8391. * Write a log message
  8392. */
  8393. log: consoleLog('log'),
  8394. /**
  8395. * @ngdoc method
  8396. * @name ng.$log#info
  8397. * @methodOf ng.$log
  8398. *
  8399. * @description
  8400. * Write an information message
  8401. */
  8402. info: consoleLog('info'),
  8403. /**
  8404. * @ngdoc method
  8405. * @name ng.$log#warn
  8406. * @methodOf ng.$log
  8407. *
  8408. * @description
  8409. * Write a warning message
  8410. */
  8411. warn: consoleLog('warn'),
  8412. /**
  8413. * @ngdoc method
  8414. * @name ng.$log#error
  8415. * @methodOf ng.$log
  8416. *
  8417. * @description
  8418. * Write an error message
  8419. */
  8420. error: consoleLog('error'),
  8421. /**
  8422. * @ngdoc method
  8423. * @name ng.$log#debug
  8424. * @methodOf ng.$log
  8425. *
  8426. * @description
  8427. * Write a debug message
  8428. */
  8429. debug: (function () {
  8430. var fn = consoleLog('debug');
  8431. return function() {
  8432. if (debug) {
  8433. fn.apply(self, arguments);
  8434. }
  8435. };
  8436. }())
  8437. };
  8438. function formatError(arg) {
  8439. if (arg instanceof Error) {
  8440. if (arg.stack) {
  8441. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  8442. ? 'Error: ' + arg.message + '\n' + arg.stack
  8443. : arg.stack;
  8444. } else if (arg.sourceURL) {
  8445. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  8446. }
  8447. }
  8448. return arg;
  8449. }
  8450. function consoleLog(type) {
  8451. var console = $window.console || {},
  8452. logFn = console[type] || console.log || noop,
  8453. hasApply = false;
  8454. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  8455. // The reason behind this is that console.log has type "object" in IE8...
  8456. try {
  8457. hasApply = !! logFn.apply;
  8458. } catch (e) {}
  8459. if (hasApply) {
  8460. return function() {
  8461. var args = [];
  8462. forEach(arguments, function(arg) {
  8463. args.push(formatError(arg));
  8464. });
  8465. return logFn.apply(console, args);
  8466. };
  8467. }
  8468. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  8469. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  8470. return function(arg1, arg2) {
  8471. logFn(arg1, arg2 == null ? '' : arg2);
  8472. };
  8473. }
  8474. }];
  8475. }
  8476. var $parseMinErr = minErr('$parse');
  8477. var promiseWarningCache = {};
  8478. var promiseWarning;
  8479. // Sandboxing Angular Expressions
  8480. // ------------------------------
  8481. // Angular expressions are generally considered safe because these expressions only have direct
  8482. // access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
  8483. // obtaining a reference to native JS functions such as the Function constructor.
  8484. //
  8485. // As an example, consider the following Angular expression:
  8486. //
  8487. // {}.toString.constructor(alert("evil JS code"))
  8488. //
  8489. // We want to prevent this type of access. For the sake of performance, during the lexing phase we
  8490. // disallow any "dotted" access to any member named "constructor".
  8491. //
  8492. // For reflective calls (a[b]) we check that the value of the lookup is not the Function constructor
  8493. // while evaluating the expression, which is a stronger but more expensive test. Since reflective
  8494. // calls are expensive anyway, this is not such a big deal compared to static dereferencing.
  8495. //
  8496. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  8497. // against the expression language, but not to prevent exploits that were enabled by exposing
  8498. // sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
  8499. // practice and therefore we are not even trying to protect against interaction with an object
  8500. // explicitly exposed in this way.
  8501. //
  8502. // A developer could foil the name check by aliasing the Function constructor under a different
  8503. // name on the scope.
  8504. //
  8505. // In general, it is not possible to access a Window object from an angular expression unless a
  8506. // window or some DOM object that has a reference to window is published onto a Scope.
  8507. function ensureSafeMemberName(name, fullExpression) {
  8508. if (name === "constructor") {
  8509. throw $parseMinErr('isecfld',
  8510. 'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',
  8511. fullExpression);
  8512. }
  8513. return name;
  8514. }
  8515. function ensureSafeObject(obj, fullExpression) {
  8516. // nifty check if obj is Function that is fast and works across iframes and other contexts
  8517. if (obj) {
  8518. if (obj.constructor === obj) {
  8519. throw $parseMinErr('isecfn',
  8520. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  8521. fullExpression);
  8522. } else if (// isWindow(obj)
  8523. obj.document && obj.location && obj.alert && obj.setInterval) {
  8524. throw $parseMinErr('isecwindow',
  8525. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  8526. fullExpression);
  8527. } else if (// isElement(obj)
  8528. obj.children && (obj.nodeName || (obj.on && obj.find))) {
  8529. throw $parseMinErr('isecdom',
  8530. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  8531. fullExpression);
  8532. }
  8533. }
  8534. return obj;
  8535. }
  8536. var OPERATORS = {
  8537. /* jshint bitwise : false */
  8538. 'null':function(){return null;},
  8539. 'true':function(){return true;},
  8540. 'false':function(){return false;},
  8541. undefined:noop,
  8542. '+':function(self, locals, a,b){
  8543. a=a(self, locals); b=b(self, locals);
  8544. if (isDefined(a)) {
  8545. if (isDefined(b)) {
  8546. return a + b;
  8547. }
  8548. return a;
  8549. }
  8550. return isDefined(b)?b:undefined;},
  8551. '-':function(self, locals, a,b){
  8552. a=a(self, locals); b=b(self, locals);
  8553. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  8554. },
  8555. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  8556. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  8557. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  8558. '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
  8559. '=':noop,
  8560. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  8561. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  8562. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  8563. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  8564. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  8565. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  8566. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  8567. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  8568. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  8569. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  8570. '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
  8571. // '|':function(self, locals, a,b){return a|b;},
  8572. '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
  8573. '!':function(self, locals, a){return !a(self, locals);}
  8574. };
  8575. /* jshint bitwise: true */
  8576. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  8577. /////////////////////////////////////////
  8578. /**
  8579. * @constructor
  8580. */
  8581. var Lexer = function (options) {
  8582. this.options = options;
  8583. };
  8584. Lexer.prototype = {
  8585. constructor: Lexer,
  8586. lex: function (text) {
  8587. this.text = text;
  8588. this.index = 0;
  8589. this.ch = undefined;
  8590. this.lastCh = ':'; // can start regexp
  8591. this.tokens = [];
  8592. var token;
  8593. var json = [];
  8594. while (this.index < this.text.length) {
  8595. this.ch = this.text.charAt(this.index);
  8596. if (this.is('"\'')) {
  8597. this.readString(this.ch);
  8598. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  8599. this.readNumber();
  8600. } else if (this.isIdent(this.ch)) {
  8601. this.readIdent();
  8602. // identifiers can only be if the preceding char was a { or ,
  8603. if (this.was('{,') && json[0] === '{' &&
  8604. (token = this.tokens[this.tokens.length - 1])) {
  8605. token.json = token.text.indexOf('.') === -1;
  8606. }
  8607. } else if (this.is('(){}[].,;:?')) {
  8608. this.tokens.push({
  8609. index: this.index,
  8610. text: this.ch,
  8611. json: (this.was(':[,') && this.is('{[')) || this.is('}]:,')
  8612. });
  8613. if (this.is('{[')) json.unshift(this.ch);
  8614. if (this.is('}]')) json.shift();
  8615. this.index++;
  8616. } else if (this.isWhitespace(this.ch)) {
  8617. this.index++;
  8618. continue;
  8619. } else {
  8620. var ch2 = this.ch + this.peek();
  8621. var ch3 = ch2 + this.peek(2);
  8622. var fn = OPERATORS[this.ch];
  8623. var fn2 = OPERATORS[ch2];
  8624. var fn3 = OPERATORS[ch3];
  8625. if (fn3) {
  8626. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  8627. this.index += 3;
  8628. } else if (fn2) {
  8629. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  8630. this.index += 2;
  8631. } else if (fn) {
  8632. this.tokens.push({
  8633. index: this.index,
  8634. text: this.ch,
  8635. fn: fn,
  8636. json: (this.was('[,:') && this.is('+-'))
  8637. });
  8638. this.index += 1;
  8639. } else {
  8640. this.throwError('Unexpected next character ', this.index, this.index + 1);
  8641. }
  8642. }
  8643. this.lastCh = this.ch;
  8644. }
  8645. return this.tokens;
  8646. },
  8647. is: function(chars) {
  8648. return chars.indexOf(this.ch) !== -1;
  8649. },
  8650. was: function(chars) {
  8651. return chars.indexOf(this.lastCh) !== -1;
  8652. },
  8653. peek: function(i) {
  8654. var num = i || 1;
  8655. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  8656. },
  8657. isNumber: function(ch) {
  8658. return ('0' <= ch && ch <= '9');
  8659. },
  8660. isWhitespace: function(ch) {
  8661. // IE treats non-breaking space as \u00A0
  8662. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  8663. ch === '\n' || ch === '\v' || ch === '\u00A0');
  8664. },
  8665. isIdent: function(ch) {
  8666. return ('a' <= ch && ch <= 'z' ||
  8667. 'A' <= ch && ch <= 'Z' ||
  8668. '_' === ch || ch === '$');
  8669. },
  8670. isExpOperator: function(ch) {
  8671. return (ch === '-' || ch === '+' || this.isNumber(ch));
  8672. },
  8673. throwError: function(error, start, end) {
  8674. end = end || this.index;
  8675. var colStr = (isDefined(start)
  8676. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  8677. : ' ' + end);
  8678. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  8679. error, colStr, this.text);
  8680. },
  8681. readNumber: function() {
  8682. var number = '';
  8683. var start = this.index;
  8684. while (this.index < this.text.length) {
  8685. var ch = lowercase(this.text.charAt(this.index));
  8686. if (ch == '.' || this.isNumber(ch)) {
  8687. number += ch;
  8688. } else {
  8689. var peekCh = this.peek();
  8690. if (ch == 'e' && this.isExpOperator(peekCh)) {
  8691. number += ch;
  8692. } else if (this.isExpOperator(ch) &&
  8693. peekCh && this.isNumber(peekCh) &&
  8694. number.charAt(number.length - 1) == 'e') {
  8695. number += ch;
  8696. } else if (this.isExpOperator(ch) &&
  8697. (!peekCh || !this.isNumber(peekCh)) &&
  8698. number.charAt(number.length - 1) == 'e') {
  8699. this.throwError('Invalid exponent');
  8700. } else {
  8701. break;
  8702. }
  8703. }
  8704. this.index++;
  8705. }
  8706. number = 1 * number;
  8707. this.tokens.push({
  8708. index: start,
  8709. text: number,
  8710. json: true,
  8711. fn: function() { return number; }
  8712. });
  8713. },
  8714. readIdent: function() {
  8715. var parser = this;
  8716. var ident = '';
  8717. var start = this.index;
  8718. var lastDot, peekIndex, methodName, ch;
  8719. while (this.index < this.text.length) {
  8720. ch = this.text.charAt(this.index);
  8721. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  8722. if (ch === '.') lastDot = this.index;
  8723. ident += ch;
  8724. } else {
  8725. break;
  8726. }
  8727. this.index++;
  8728. }
  8729. //check if this is not a method invocation and if it is back out to last dot
  8730. if (lastDot) {
  8731. peekIndex = this.index;
  8732. while (peekIndex < this.text.length) {
  8733. ch = this.text.charAt(peekIndex);
  8734. if (ch === '(') {
  8735. methodName = ident.substr(lastDot - start + 1);
  8736. ident = ident.substr(0, lastDot - start);
  8737. this.index = peekIndex;
  8738. break;
  8739. }
  8740. if (this.isWhitespace(ch)) {
  8741. peekIndex++;
  8742. } else {
  8743. break;
  8744. }
  8745. }
  8746. }
  8747. var token = {
  8748. index: start,
  8749. text: ident
  8750. };
  8751. // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
  8752. if (OPERATORS.hasOwnProperty(ident)) {
  8753. token.fn = OPERATORS[ident];
  8754. token.json = OPERATORS[ident];
  8755. } else {
  8756. var getter = getterFn(ident, this.options, this.text);
  8757. token.fn = extend(function(self, locals) {
  8758. return (getter(self, locals));
  8759. }, {
  8760. assign: function(self, value) {
  8761. return setter(self, ident, value, parser.text, parser.options);
  8762. }
  8763. });
  8764. }
  8765. this.tokens.push(token);
  8766. if (methodName) {
  8767. this.tokens.push({
  8768. index:lastDot,
  8769. text: '.',
  8770. json: false
  8771. });
  8772. this.tokens.push({
  8773. index: lastDot + 1,
  8774. text: methodName,
  8775. json: false
  8776. });
  8777. }
  8778. },
  8779. readString: function(quote) {
  8780. var start = this.index;
  8781. this.index++;
  8782. var string = '';
  8783. var rawString = quote;
  8784. var escape = false;
  8785. while (this.index < this.text.length) {
  8786. var ch = this.text.charAt(this.index);
  8787. rawString += ch;
  8788. if (escape) {
  8789. if (ch === 'u') {
  8790. var hex = this.text.substring(this.index + 1, this.index + 5);
  8791. if (!hex.match(/[\da-f]{4}/i))
  8792. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  8793. this.index += 4;
  8794. string += String.fromCharCode(parseInt(hex, 16));
  8795. } else {
  8796. var rep = ESCAPE[ch];
  8797. if (rep) {
  8798. string += rep;
  8799. } else {
  8800. string += ch;
  8801. }
  8802. }
  8803. escape = false;
  8804. } else if (ch === '\\') {
  8805. escape = true;
  8806. } else if (ch === quote) {
  8807. this.index++;
  8808. this.tokens.push({
  8809. index: start,
  8810. text: rawString,
  8811. string: string,
  8812. json: true,
  8813. fn: function() { return string; }
  8814. });
  8815. return;
  8816. } else {
  8817. string += ch;
  8818. }
  8819. this.index++;
  8820. }
  8821. this.throwError('Unterminated quote', start);
  8822. }
  8823. };
  8824. /**
  8825. * @constructor
  8826. */
  8827. var Parser = function (lexer, $filter, options) {
  8828. this.lexer = lexer;
  8829. this.$filter = $filter;
  8830. this.options = options;
  8831. };
  8832. Parser.ZERO = function () { return 0; };
  8833. Parser.prototype = {
  8834. constructor: Parser,
  8835. parse: function (text, json) {
  8836. this.text = text;
  8837. //TODO(i): strip all the obsolte json stuff from this file
  8838. this.json = json;
  8839. this.tokens = this.lexer.lex(text);
  8840. if (json) {
  8841. // The extra level of aliasing is here, just in case the lexer misses something, so that
  8842. // we prevent any accidental execution in JSON.
  8843. this.assignment = this.logicalOR;
  8844. this.functionCall =
  8845. this.fieldAccess =
  8846. this.objectIndex =
  8847. this.filterChain = function() {
  8848. this.throwError('is not valid json', {text: text, index: 0});
  8849. };
  8850. }
  8851. var value = json ? this.primary() : this.statements();
  8852. if (this.tokens.length !== 0) {
  8853. this.throwError('is an unexpected token', this.tokens[0]);
  8854. }
  8855. value.literal = !!value.literal;
  8856. value.constant = !!value.constant;
  8857. return value;
  8858. },
  8859. primary: function () {
  8860. var primary;
  8861. if (this.expect('(')) {
  8862. primary = this.filterChain();
  8863. this.consume(')');
  8864. } else if (this.expect('[')) {
  8865. primary = this.arrayDeclaration();
  8866. } else if (this.expect('{')) {
  8867. primary = this.object();
  8868. } else {
  8869. var token = this.expect();
  8870. primary = token.fn;
  8871. if (!primary) {
  8872. this.throwError('not a primary expression', token);
  8873. }
  8874. if (token.json) {
  8875. primary.constant = true;
  8876. primary.literal = true;
  8877. }
  8878. }
  8879. var next, context;
  8880. while ((next = this.expect('(', '[', '.'))) {
  8881. if (next.text === '(') {
  8882. primary = this.functionCall(primary, context);
  8883. context = null;
  8884. } else if (next.text === '[') {
  8885. context = primary;
  8886. primary = this.objectIndex(primary);
  8887. } else if (next.text === '.') {
  8888. context = primary;
  8889. primary = this.fieldAccess(primary);
  8890. } else {
  8891. this.throwError('IMPOSSIBLE');
  8892. }
  8893. }
  8894. return primary;
  8895. },
  8896. throwError: function(msg, token) {
  8897. throw $parseMinErr('syntax',
  8898. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  8899. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  8900. },
  8901. peekToken: function() {
  8902. if (this.tokens.length === 0)
  8903. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  8904. return this.tokens[0];
  8905. },
  8906. peek: function(e1, e2, e3, e4) {
  8907. if (this.tokens.length > 0) {
  8908. var token = this.tokens[0];
  8909. var t = token.text;
  8910. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  8911. (!e1 && !e2 && !e3 && !e4)) {
  8912. return token;
  8913. }
  8914. }
  8915. return false;
  8916. },
  8917. expect: function(e1, e2, e3, e4){
  8918. var token = this.peek(e1, e2, e3, e4);
  8919. if (token) {
  8920. if (this.json && !token.json) {
  8921. this.throwError('is not valid json', token);
  8922. }
  8923. this.tokens.shift();
  8924. return token;
  8925. }
  8926. return false;
  8927. },
  8928. consume: function(e1){
  8929. if (!this.expect(e1)) {
  8930. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  8931. }
  8932. },
  8933. unaryFn: function(fn, right) {
  8934. return extend(function(self, locals) {
  8935. return fn(self, locals, right);
  8936. }, {
  8937. constant:right.constant
  8938. });
  8939. },
  8940. ternaryFn: function(left, middle, right){
  8941. return extend(function(self, locals){
  8942. return left(self, locals) ? middle(self, locals) : right(self, locals);
  8943. }, {
  8944. constant: left.constant && middle.constant && right.constant
  8945. });
  8946. },
  8947. binaryFn: function(left, fn, right) {
  8948. return extend(function(self, locals) {
  8949. return fn(self, locals, left, right);
  8950. }, {
  8951. constant:left.constant && right.constant
  8952. });
  8953. },
  8954. statements: function() {
  8955. var statements = [];
  8956. while (true) {
  8957. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  8958. statements.push(this.filterChain());
  8959. if (!this.expect(';')) {
  8960. // optimize for the common case where there is only one statement.
  8961. // TODO(size): maybe we should not support multiple statements?
  8962. return (statements.length === 1)
  8963. ? statements[0]
  8964. : function(self, locals) {
  8965. var value;
  8966. for (var i = 0; i < statements.length; i++) {
  8967. var statement = statements[i];
  8968. if (statement) {
  8969. value = statement(self, locals);
  8970. }
  8971. }
  8972. return value;
  8973. };
  8974. }
  8975. }
  8976. },
  8977. filterChain: function() {
  8978. var left = this.expression();
  8979. var token;
  8980. while (true) {
  8981. if ((token = this.expect('|'))) {
  8982. left = this.binaryFn(left, token.fn, this.filter());
  8983. } else {
  8984. return left;
  8985. }
  8986. }
  8987. },
  8988. filter: function() {
  8989. var token = this.expect();
  8990. var fn = this.$filter(token.text);
  8991. var argsFn = [];
  8992. while (true) {
  8993. if ((token = this.expect(':'))) {
  8994. argsFn.push(this.expression());
  8995. } else {
  8996. var fnInvoke = function(self, locals, input) {
  8997. var args = [input];
  8998. for (var i = 0; i < argsFn.length; i++) {
  8999. args.push(argsFn[i](self, locals));
  9000. }
  9001. return fn.apply(self, args);
  9002. };
  9003. return function() {
  9004. return fnInvoke;
  9005. };
  9006. }
  9007. }
  9008. },
  9009. expression: function() {
  9010. return this.assignment();
  9011. },
  9012. assignment: function() {
  9013. var left = this.ternary();
  9014. var right;
  9015. var token;
  9016. if ((token = this.expect('='))) {
  9017. if (!left.assign) {
  9018. this.throwError('implies assignment but [' +
  9019. this.text.substring(0, token.index) + '] can not be assigned to', token);
  9020. }
  9021. right = this.ternary();
  9022. return function(scope, locals) {
  9023. return left.assign(scope, right(scope, locals), locals);
  9024. };
  9025. }
  9026. return left;
  9027. },
  9028. ternary: function() {
  9029. var left = this.logicalOR();
  9030. var middle;
  9031. var token;
  9032. if ((token = this.expect('?'))) {
  9033. middle = this.ternary();
  9034. if ((token = this.expect(':'))) {
  9035. return this.ternaryFn(left, middle, this.ternary());
  9036. } else {
  9037. this.throwError('expected :', token);
  9038. }
  9039. } else {
  9040. return left;
  9041. }
  9042. },
  9043. logicalOR: function() {
  9044. var left = this.logicalAND();
  9045. var token;
  9046. while (true) {
  9047. if ((token = this.expect('||'))) {
  9048. left = this.binaryFn(left, token.fn, this.logicalAND());
  9049. } else {
  9050. return left;
  9051. }
  9052. }
  9053. },
  9054. logicalAND: function() {
  9055. var left = this.equality();
  9056. var token;
  9057. if ((token = this.expect('&&'))) {
  9058. left = this.binaryFn(left, token.fn, this.logicalAND());
  9059. }
  9060. return left;
  9061. },
  9062. equality: function() {
  9063. var left = this.relational();
  9064. var token;
  9065. if ((token = this.expect('==','!=','===','!=='))) {
  9066. left = this.binaryFn(left, token.fn, this.equality());
  9067. }
  9068. return left;
  9069. },
  9070. relational: function() {
  9071. var left = this.additive();
  9072. var token;
  9073. if ((token = this.expect('<', '>', '<=', '>='))) {
  9074. left = this.binaryFn(left, token.fn, this.relational());
  9075. }
  9076. return left;
  9077. },
  9078. additive: function() {
  9079. var left = this.multiplicative();
  9080. var token;
  9081. while ((token = this.expect('+','-'))) {
  9082. left = this.binaryFn(left, token.fn, this.multiplicative());
  9083. }
  9084. return left;
  9085. },
  9086. multiplicative: function() {
  9087. var left = this.unary();
  9088. var token;
  9089. while ((token = this.expect('*','/','%'))) {
  9090. left = this.binaryFn(left, token.fn, this.unary());
  9091. }
  9092. return left;
  9093. },
  9094. unary: function() {
  9095. var token;
  9096. if (this.expect('+')) {
  9097. return this.primary();
  9098. } else if ((token = this.expect('-'))) {
  9099. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  9100. } else if ((token = this.expect('!'))) {
  9101. return this.unaryFn(token.fn, this.unary());
  9102. } else {
  9103. return this.primary();
  9104. }
  9105. },
  9106. fieldAccess: function(object) {
  9107. var parser = this;
  9108. var field = this.expect().text;
  9109. var getter = getterFn(field, this.options, this.text);
  9110. return extend(function(scope, locals, self) {
  9111. return getter(self || object(scope, locals), locals);
  9112. }, {
  9113. assign: function(scope, value, locals) {
  9114. return setter(object(scope, locals), field, value, parser.text, parser.options);
  9115. }
  9116. });
  9117. },
  9118. objectIndex: function(obj) {
  9119. var parser = this;
  9120. var indexFn = this.expression();
  9121. this.consume(']');
  9122. return extend(function(self, locals) {
  9123. var o = obj(self, locals),
  9124. i = indexFn(self, locals),
  9125. v, p;
  9126. if (!o) return undefined;
  9127. v = ensureSafeObject(o[i], parser.text);
  9128. if (v && v.then && parser.options.unwrapPromises) {
  9129. p = v;
  9130. if (!('$$v' in v)) {
  9131. p.$$v = undefined;
  9132. p.then(function(val) { p.$$v = val; });
  9133. }
  9134. v = v.$$v;
  9135. }
  9136. return v;
  9137. }, {
  9138. assign: function(self, value, locals) {
  9139. var key = indexFn(self, locals);
  9140. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  9141. var safe = ensureSafeObject(obj(self, locals), parser.text);
  9142. return safe[key] = value;
  9143. }
  9144. });
  9145. },
  9146. functionCall: function(fn, contextGetter) {
  9147. var argsFn = [];
  9148. if (this.peekToken().text !== ')') {
  9149. do {
  9150. argsFn.push(this.expression());
  9151. } while (this.expect(','));
  9152. }
  9153. this.consume(')');
  9154. var parser = this;
  9155. return function(scope, locals) {
  9156. var args = [];
  9157. var context = contextGetter ? contextGetter(scope, locals) : scope;
  9158. for (var i = 0; i < argsFn.length; i++) {
  9159. args.push(argsFn[i](scope, locals));
  9160. }
  9161. var fnPtr = fn(scope, locals, context) || noop;
  9162. ensureSafeObject(context, parser.text);
  9163. ensureSafeObject(fnPtr, parser.text);
  9164. // IE stupidity! (IE doesn't have apply for some native functions)
  9165. var v = fnPtr.apply
  9166. ? fnPtr.apply(context, args)
  9167. : fnPtr(args[0], args[1], args[2], args[3], args[4]);
  9168. return ensureSafeObject(v, parser.text);
  9169. };
  9170. },
  9171. // This is used with json array declaration
  9172. arrayDeclaration: function () {
  9173. var elementFns = [];
  9174. var allConstant = true;
  9175. if (this.peekToken().text !== ']') {
  9176. do {
  9177. var elementFn = this.expression();
  9178. elementFns.push(elementFn);
  9179. if (!elementFn.constant) {
  9180. allConstant = false;
  9181. }
  9182. } while (this.expect(','));
  9183. }
  9184. this.consume(']');
  9185. return extend(function(self, locals) {
  9186. var array = [];
  9187. for (var i = 0; i < elementFns.length; i++) {
  9188. array.push(elementFns[i](self, locals));
  9189. }
  9190. return array;
  9191. }, {
  9192. literal: true,
  9193. constant: allConstant
  9194. });
  9195. },
  9196. object: function () {
  9197. var keyValues = [];
  9198. var allConstant = true;
  9199. if (this.peekToken().text !== '}') {
  9200. do {
  9201. var token = this.expect(),
  9202. key = token.string || token.text;
  9203. this.consume(':');
  9204. var value = this.expression();
  9205. keyValues.push({key: key, value: value});
  9206. if (!value.constant) {
  9207. allConstant = false;
  9208. }
  9209. } while (this.expect(','));
  9210. }
  9211. this.consume('}');
  9212. return extend(function(self, locals) {
  9213. var object = {};
  9214. for (var i = 0; i < keyValues.length; i++) {
  9215. var keyValue = keyValues[i];
  9216. object[keyValue.key] = keyValue.value(self, locals);
  9217. }
  9218. return object;
  9219. }, {
  9220. literal: true,
  9221. constant: allConstant
  9222. });
  9223. }
  9224. };
  9225. //////////////////////////////////////////////////
  9226. // Parser helper functions
  9227. //////////////////////////////////////////////////
  9228. function setter(obj, path, setValue, fullExp, options) {
  9229. //needed?
  9230. options = options || {};
  9231. var element = path.split('.'), key;
  9232. for (var i = 0; element.length > 1; i++) {
  9233. key = ensureSafeMemberName(element.shift(), fullExp);
  9234. var propertyObj = obj[key];
  9235. if (!propertyObj) {
  9236. propertyObj = {};
  9237. obj[key] = propertyObj;
  9238. }
  9239. obj = propertyObj;
  9240. if (obj.then && options.unwrapPromises) {
  9241. promiseWarning(fullExp);
  9242. if (!("$$v" in obj)) {
  9243. (function(promise) {
  9244. promise.then(function(val) { promise.$$v = val; }); }
  9245. )(obj);
  9246. }
  9247. if (obj.$$v === undefined) {
  9248. obj.$$v = {};
  9249. }
  9250. obj = obj.$$v;
  9251. }
  9252. }
  9253. key = ensureSafeMemberName(element.shift(), fullExp);
  9254. obj[key] = setValue;
  9255. return setValue;
  9256. }
  9257. var getterFnCache = {};
  9258. /**
  9259. * Implementation of the "Black Hole" variant from:
  9260. * - http://jsperf.com/angularjs-parse-getter/4
  9261. * - http://jsperf.com/path-evaluation-simplified/7
  9262. */
  9263. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  9264. ensureSafeMemberName(key0, fullExp);
  9265. ensureSafeMemberName(key1, fullExp);
  9266. ensureSafeMemberName(key2, fullExp);
  9267. ensureSafeMemberName(key3, fullExp);
  9268. ensureSafeMemberName(key4, fullExp);
  9269. return !options.unwrapPromises
  9270. ? function cspSafeGetter(scope, locals) {
  9271. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  9272. if (pathVal == null) return pathVal;
  9273. pathVal = pathVal[key0];
  9274. if (!key1) return pathVal;
  9275. if (pathVal == null) return undefined;
  9276. pathVal = pathVal[key1];
  9277. if (!key2) return pathVal;
  9278. if (pathVal == null) return undefined;
  9279. pathVal = pathVal[key2];
  9280. if (!key3) return pathVal;
  9281. if (pathVal == null) return undefined;
  9282. pathVal = pathVal[key3];
  9283. if (!key4) return pathVal;
  9284. if (pathVal == null) return undefined;
  9285. pathVal = pathVal[key4];
  9286. return pathVal;
  9287. }
  9288. : function cspSafePromiseEnabledGetter(scope, locals) {
  9289. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
  9290. promise;
  9291. if (pathVal == null) return pathVal;
  9292. pathVal = pathVal[key0];
  9293. if (pathVal && pathVal.then) {
  9294. promiseWarning(fullExp);
  9295. if (!("$$v" in pathVal)) {
  9296. promise = pathVal;
  9297. promise.$$v = undefined;
  9298. promise.then(function(val) { promise.$$v = val; });
  9299. }
  9300. pathVal = pathVal.$$v;
  9301. }
  9302. if (!key1) return pathVal;
  9303. if (pathVal == null) return undefined;
  9304. pathVal = pathVal[key1];
  9305. if (pathVal && pathVal.then) {
  9306. promiseWarning(fullExp);
  9307. if (!("$$v" in pathVal)) {
  9308. promise = pathVal;
  9309. promise.$$v = undefined;
  9310. promise.then(function(val) { promise.$$v = val; });
  9311. }
  9312. pathVal = pathVal.$$v;
  9313. }
  9314. if (!key2) return pathVal;
  9315. if (pathVal == null) return undefined;
  9316. pathVal = pathVal[key2];
  9317. if (pathVal && pathVal.then) {
  9318. promiseWarning(fullExp);
  9319. if (!("$$v" in pathVal)) {
  9320. promise = pathVal;
  9321. promise.$$v = undefined;
  9322. promise.then(function(val) { promise.$$v = val; });
  9323. }
  9324. pathVal = pathVal.$$v;
  9325. }
  9326. if (!key3) return pathVal;
  9327. if (pathVal == null) return undefined;
  9328. pathVal = pathVal[key3];
  9329. if (pathVal && pathVal.then) {
  9330. promiseWarning(fullExp);
  9331. if (!("$$v" in pathVal)) {
  9332. promise = pathVal;
  9333. promise.$$v = undefined;
  9334. promise.then(function(val) { promise.$$v = val; });
  9335. }
  9336. pathVal = pathVal.$$v;
  9337. }
  9338. if (!key4) return pathVal;
  9339. if (pathVal == null) return undefined;
  9340. pathVal = pathVal[key4];
  9341. if (pathVal && pathVal.then) {
  9342. promiseWarning(fullExp);
  9343. if (!("$$v" in pathVal)) {
  9344. promise = pathVal;
  9345. promise.$$v = undefined;
  9346. promise.then(function(val) { promise.$$v = val; });
  9347. }
  9348. pathVal = pathVal.$$v;
  9349. }
  9350. return pathVal;
  9351. };
  9352. }
  9353. function simpleGetterFn1(key0, fullExp) {
  9354. ensureSafeMemberName(key0, fullExp);
  9355. return function simpleGetterFn1(scope, locals) {
  9356. if (scope == null) return undefined;
  9357. return ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
  9358. };
  9359. }
  9360. function simpleGetterFn2(key0, key1, fullExp) {
  9361. ensureSafeMemberName(key0, fullExp);
  9362. ensureSafeMemberName(key1, fullExp);
  9363. return function simpleGetterFn2(scope, locals) {
  9364. if (scope == null) return undefined;
  9365. scope = ((locals && locals.hasOwnProperty(key0)) ? locals : scope)[key0];
  9366. return scope == null ? undefined : scope[key1];
  9367. };
  9368. }
  9369. function getterFn(path, options, fullExp) {
  9370. // Check whether the cache has this getter already.
  9371. // We can use hasOwnProperty directly on the cache because we ensure,
  9372. // see below, that the cache never stores a path called 'hasOwnProperty'
  9373. if (getterFnCache.hasOwnProperty(path)) {
  9374. return getterFnCache[path];
  9375. }
  9376. var pathKeys = path.split('.'),
  9377. pathKeysLength = pathKeys.length,
  9378. fn;
  9379. // When we have only 1 or 2 tokens, use optimized special case closures.
  9380. // http://jsperf.com/angularjs-parse-getter/6
  9381. if (!options.unwrapPromises && pathKeysLength === 1) {
  9382. fn = simpleGetterFn1(pathKeys[0], fullExp);
  9383. } else if (!options.unwrapPromises && pathKeysLength === 2) {
  9384. fn = simpleGetterFn2(pathKeys[0], pathKeys[1], fullExp);
  9385. } else if (options.csp) {
  9386. if (pathKeysLength < 6) {
  9387. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
  9388. options);
  9389. } else {
  9390. fn = function(scope, locals) {
  9391. var i = 0, val;
  9392. do {
  9393. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  9394. pathKeys[i++], fullExp, options)(scope, locals);
  9395. locals = undefined; // clear after first iteration
  9396. scope = val;
  9397. } while (i < pathKeysLength);
  9398. return val;
  9399. };
  9400. }
  9401. } else {
  9402. var code = 'var p;\n';
  9403. forEach(pathKeys, function(key, index) {
  9404. ensureSafeMemberName(key, fullExp);
  9405. code += 'if(s == null) return undefined;\n' +
  9406. 's='+ (index
  9407. // we simply dereference 's' on any .dot notation
  9408. ? 's'
  9409. // but if we are first then we check locals first, and if so read it first
  9410. : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
  9411. (options.unwrapPromises
  9412. ? 'if (s && s.then) {\n' +
  9413. ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
  9414. ' if (!("$$v" in s)) {\n' +
  9415. ' p=s;\n' +
  9416. ' p.$$v = undefined;\n' +
  9417. ' p.then(function(v) {p.$$v=v;});\n' +
  9418. '}\n' +
  9419. ' s=s.$$v\n' +
  9420. '}\n'
  9421. : '');
  9422. });
  9423. code += 'return s;';
  9424. /* jshint -W054 */
  9425. var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
  9426. /* jshint +W054 */
  9427. evaledFnGetter.toString = valueFn(code);
  9428. fn = options.unwrapPromises ? function(scope, locals) {
  9429. return evaledFnGetter(scope, locals, promiseWarning);
  9430. } : evaledFnGetter;
  9431. }
  9432. // Only cache the value if it's not going to mess up the cache object
  9433. // This is more performant that using Object.prototype.hasOwnProperty.call
  9434. if (path !== 'hasOwnProperty') {
  9435. getterFnCache[path] = fn;
  9436. }
  9437. return fn;
  9438. }
  9439. ///////////////////////////////////
  9440. /**
  9441. * @ngdoc function
  9442. * @name ng.$parse
  9443. * @function
  9444. *
  9445. * @description
  9446. *
  9447. * Converts Angular {@link guide/expression expression} into a function.
  9448. *
  9449. * <pre>
  9450. * var getter = $parse('user.name');
  9451. * var setter = getter.assign;
  9452. * var context = {user:{name:'angular'}};
  9453. * var locals = {user:{name:'local'}};
  9454. *
  9455. * expect(getter(context)).toEqual('angular');
  9456. * setter(context, 'newValue');
  9457. * expect(context.user.name).toEqual('newValue');
  9458. * expect(getter(context, locals)).toEqual('local');
  9459. * </pre>
  9460. *
  9461. *
  9462. * @param {string} expression String expression to compile.
  9463. * @returns {function(context, locals)} a function which represents the compiled expression:
  9464. *
  9465. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  9466. * are evaluated against (typically a scope object).
  9467. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  9468. * `context`.
  9469. *
  9470. * The returned function also has the following properties:
  9471. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  9472. * literal.
  9473. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  9474. * constant literals.
  9475. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  9476. * set to a function to change its value on the given context.
  9477. *
  9478. */
  9479. /**
  9480. * @ngdoc object
  9481. * @name ng.$parseProvider
  9482. * @function
  9483. *
  9484. * @description
  9485. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  9486. * service.
  9487. */
  9488. function $ParseProvider() {
  9489. var cache = {};
  9490. var $parseOptions = {
  9491. csp: false,
  9492. unwrapPromises: false,
  9493. logPromiseWarnings: true
  9494. };
  9495. /**
  9496. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  9497. *
  9498. * @ngdoc method
  9499. * @name ng.$parseProvider#unwrapPromises
  9500. * @methodOf ng.$parseProvider
  9501. * @description
  9502. *
  9503. * **This feature is deprecated, see deprecation notes below for more info**
  9504. *
  9505. * If set to true (default is false), $parse will unwrap promises automatically when a promise is
  9506. * found at any part of the expression. In other words, if set to true, the expression will always
  9507. * result in a non-promise value.
  9508. *
  9509. * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
  9510. * the fulfillment value is used in place of the promise while evaluating the expression.
  9511. *
  9512. * **Deprecation notice**
  9513. *
  9514. * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
  9515. * dichotomy between data access in templates (accessed as raw values) and controller code
  9516. * (accessed as promises).
  9517. *
  9518. * In most code we ended up resolving promises manually in controllers anyway and thus unifying
  9519. * the model access there.
  9520. *
  9521. * Other downsides of automatic promise unwrapping:
  9522. *
  9523. * - when building components it's often desirable to receive the raw promises
  9524. * - adds complexity and slows down expression evaluation
  9525. * - makes expression code pre-generation unattractive due to the amount of code that needs to be
  9526. * generated
  9527. * - makes IDE auto-completion and tool support hard
  9528. *
  9529. * **Warning Logs**
  9530. *
  9531. * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
  9532. * promise (to reduce the noise, each expression is logged only once). To disable this logging use
  9533. * `$parseProvider.logPromiseWarnings(false)` api.
  9534. *
  9535. *
  9536. * @param {boolean=} value New value.
  9537. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  9538. * setter.
  9539. */
  9540. this.unwrapPromises = function(value) {
  9541. if (isDefined(value)) {
  9542. $parseOptions.unwrapPromises = !!value;
  9543. return this;
  9544. } else {
  9545. return $parseOptions.unwrapPromises;
  9546. }
  9547. };
  9548. /**
  9549. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  9550. *
  9551. * @ngdoc method
  9552. * @name ng.$parseProvider#logPromiseWarnings
  9553. * @methodOf ng.$parseProvider
  9554. * @description
  9555. *
  9556. * Controls whether Angular should log a warning on any encounter of a promise in an expression.
  9557. *
  9558. * The default is set to `true`.
  9559. *
  9560. * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
  9561. *
  9562. * @param {boolean=} value New value.
  9563. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  9564. * setter.
  9565. */
  9566. this.logPromiseWarnings = function(value) {
  9567. if (isDefined(value)) {
  9568. $parseOptions.logPromiseWarnings = value;
  9569. return this;
  9570. } else {
  9571. return $parseOptions.logPromiseWarnings;
  9572. }
  9573. };
  9574. this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
  9575. $parseOptions.csp = $sniffer.csp;
  9576. promiseWarning = function promiseWarningFn(fullExp) {
  9577. if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
  9578. promiseWarningCache[fullExp] = true;
  9579. $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
  9580. 'Automatic unwrapping of promises in Angular expressions is deprecated.');
  9581. };
  9582. return function(exp) {
  9583. var parsedExpression;
  9584. switch (typeof exp) {
  9585. case 'string':
  9586. if (cache.hasOwnProperty(exp)) {
  9587. return cache[exp];
  9588. }
  9589. var lexer = new Lexer($parseOptions);
  9590. var parser = new Parser(lexer, $filter, $parseOptions);
  9591. parsedExpression = parser.parse(exp, false);
  9592. if (exp !== 'hasOwnProperty') {
  9593. // Only cache the value if it's not going to mess up the cache object
  9594. // This is more performant that using Object.prototype.hasOwnProperty.call
  9595. cache[exp] = parsedExpression;
  9596. }
  9597. return parsedExpression;
  9598. case 'function':
  9599. return exp;
  9600. default:
  9601. return noop;
  9602. }
  9603. };
  9604. }];
  9605. }
  9606. /**
  9607. * @ngdoc service
  9608. * @name ng.$q
  9609. * @requires $rootScope
  9610. *
  9611. * @description
  9612. * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  9613. *
  9614. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  9615. * interface for interacting with an object that represents the result of an action that is
  9616. * performed asynchronously, and may or may not be finished at any given point in time.
  9617. *
  9618. * From the perspective of dealing with error handling, deferred and promise APIs are to
  9619. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  9620. *
  9621. * <pre>
  9622. * // for the purpose of this example let's assume that variables `$q` and `scope` are
  9623. * // available in the current lexical scope (they could have been injected or passed in).
  9624. *
  9625. * function asyncGreet(name) {
  9626. * var deferred = $q.defer();
  9627. *
  9628. * setTimeout(function() {
  9629. * // since this fn executes async in a future turn of the event loop, we need to wrap
  9630. * // our code into an $apply call so that the model changes are properly observed.
  9631. * scope.$apply(function() {
  9632. * deferred.notify('About to greet ' + name + '.');
  9633. *
  9634. * if (okToGreet(name)) {
  9635. * deferred.resolve('Hello, ' + name + '!');
  9636. * } else {
  9637. * deferred.reject('Greeting ' + name + ' is not allowed.');
  9638. * }
  9639. * });
  9640. * }, 1000);
  9641. *
  9642. * return deferred.promise;
  9643. * }
  9644. *
  9645. * var promise = asyncGreet('Robin Hood');
  9646. * promise.then(function(greeting) {
  9647. * alert('Success: ' + greeting);
  9648. * }, function(reason) {
  9649. * alert('Failed: ' + reason);
  9650. * }, function(update) {
  9651. * alert('Got notification: ' + update);
  9652. * });
  9653. * </pre>
  9654. *
  9655. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  9656. * comes in the way of guarantees that promise and deferred APIs make, see
  9657. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  9658. *
  9659. * Additionally the promise api allows for composition that is very hard to do with the
  9660. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  9661. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  9662. * section on serial or parallel joining of promises.
  9663. *
  9664. *
  9665. * # The Deferred API
  9666. *
  9667. * A new instance of deferred is constructed by calling `$q.defer()`.
  9668. *
  9669. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  9670. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  9671. * of the task.
  9672. *
  9673. * **Methods**
  9674. *
  9675. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  9676. * constructed via `$q.reject`, the promise will be rejected instead.
  9677. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  9678. * resolving it with a rejection constructed via `$q.reject`.
  9679. * - `notify(value)` - provides updates on the status of the promises execution. This may be called
  9680. * multiple times before the promise is either resolved or rejected.
  9681. *
  9682. * **Properties**
  9683. *
  9684. * - promise – `{Promise}` – promise object associated with this deferred.
  9685. *
  9686. *
  9687. * # The Promise API
  9688. *
  9689. * A new promise instance is created when a deferred instance is created and can be retrieved by
  9690. * calling `deferred.promise`.
  9691. *
  9692. * The purpose of the promise object is to allow for interested parties to get access to the result
  9693. * of the deferred task when it completes.
  9694. *
  9695. * **Methods**
  9696. *
  9697. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  9698. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  9699. * as soon as the result is available. The callbacks are called with a single argument: the result
  9700. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  9701. * provide a progress indication, before the promise is resolved or rejected.
  9702. *
  9703. * This method *returns a new promise* which is resolved or rejected via the return value of the
  9704. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  9705. * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
  9706. * method.
  9707. *
  9708. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  9709. *
  9710. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  9711. * but to do so without modifying the final value. This is useful to release resources or do some
  9712. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  9713. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  9714. * more information.
  9715. *
  9716. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  9717. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  9718. * make your code IE8 compatible.
  9719. *
  9720. * # Chaining promises
  9721. *
  9722. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  9723. * possible to create a chain of promises:
  9724. *
  9725. * <pre>
  9726. * promiseB = promiseA.then(function(result) {
  9727. * return result + 1;
  9728. * });
  9729. *
  9730. * // promiseB will be resolved immediately after promiseA is resolved and its value
  9731. * // will be the result of promiseA incremented by 1
  9732. * </pre>
  9733. *
  9734. * It is possible to create chains of any length and since a promise can be resolved with another
  9735. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  9736. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  9737. * $http's response interceptors.
  9738. *
  9739. *
  9740. * # Differences between Kris Kowal's Q and $q
  9741. *
  9742. * There are two main differences:
  9743. *
  9744. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  9745. * mechanism in angular, which means faster propagation of resolution or rejection into your
  9746. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  9747. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  9748. * all the important functionality needed for common async tasks.
  9749. *
  9750. * # Testing
  9751. *
  9752. * <pre>
  9753. * it('should simulate promise', inject(function($q, $rootScope) {
  9754. * var deferred = $q.defer();
  9755. * var promise = deferred.promise;
  9756. * var resolvedValue;
  9757. *
  9758. * promise.then(function(value) { resolvedValue = value; });
  9759. * expect(resolvedValue).toBeUndefined();
  9760. *
  9761. * // Simulate resolving of promise
  9762. * deferred.resolve(123);
  9763. * // Note that the 'then' function does not get called synchronously.
  9764. * // This is because we want the promise API to always be async, whether or not
  9765. * // it got called synchronously or asynchronously.
  9766. * expect(resolvedValue).toBeUndefined();
  9767. *
  9768. * // Propagate promise resolution to 'then' functions using $apply().
  9769. * $rootScope.$apply();
  9770. * expect(resolvedValue).toEqual(123);
  9771. * }));
  9772. * </pre>
  9773. */
  9774. function $QProvider() {
  9775. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  9776. return qFactory(function(callback) {
  9777. $rootScope.$evalAsync(callback);
  9778. }, $exceptionHandler);
  9779. }];
  9780. }
  9781. /**
  9782. * Constructs a promise manager.
  9783. *
  9784. * @param {function(function)} nextTick Function for executing functions in the next turn.
  9785. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  9786. * debugging purposes.
  9787. * @returns {object} Promise manager.
  9788. */
  9789. function qFactory(nextTick, exceptionHandler) {
  9790. /**
  9791. * @ngdoc
  9792. * @name ng.$q#defer
  9793. * @methodOf ng.$q
  9794. * @description
  9795. * Creates a `Deferred` object which represents a task which will finish in the future.
  9796. *
  9797. * @returns {Deferred} Returns a new instance of deferred.
  9798. */
  9799. var defer = function() {
  9800. var pending = [],
  9801. value, deferred;
  9802. deferred = {
  9803. resolve: function(val) {
  9804. if (pending) {
  9805. var callbacks = pending;
  9806. pending = undefined;
  9807. value = ref(val);
  9808. if (callbacks.length) {
  9809. nextTick(function() {
  9810. var callback;
  9811. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  9812. callback = callbacks[i];
  9813. value.then(callback[0], callback[1], callback[2]);
  9814. }
  9815. });
  9816. }
  9817. }
  9818. },
  9819. reject: function(reason) {
  9820. deferred.resolve(reject(reason));
  9821. },
  9822. notify: function(progress) {
  9823. if (pending) {
  9824. var callbacks = pending;
  9825. if (pending.length) {
  9826. nextTick(function() {
  9827. var callback;
  9828. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  9829. callback = callbacks[i];
  9830. callback[2](progress);
  9831. }
  9832. });
  9833. }
  9834. }
  9835. },
  9836. promise: {
  9837. then: function(callback, errback, progressback) {
  9838. var result = defer();
  9839. var wrappedCallback = function(value) {
  9840. try {
  9841. result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
  9842. } catch(e) {
  9843. result.reject(e);
  9844. exceptionHandler(e);
  9845. }
  9846. };
  9847. var wrappedErrback = function(reason) {
  9848. try {
  9849. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  9850. } catch(e) {
  9851. result.reject(e);
  9852. exceptionHandler(e);
  9853. }
  9854. };
  9855. var wrappedProgressback = function(progress) {
  9856. try {
  9857. result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
  9858. } catch(e) {
  9859. exceptionHandler(e);
  9860. }
  9861. };
  9862. if (pending) {
  9863. pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
  9864. } else {
  9865. value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
  9866. }
  9867. return result.promise;
  9868. },
  9869. "catch": function(callback) {
  9870. return this.then(null, callback);
  9871. },
  9872. "finally": function(callback) {
  9873. function makePromise(value, resolved) {
  9874. var result = defer();
  9875. if (resolved) {
  9876. result.resolve(value);
  9877. } else {
  9878. result.reject(value);
  9879. }
  9880. return result.promise;
  9881. }
  9882. function handleCallback(value, isResolved) {
  9883. var callbackOutput = null;
  9884. try {
  9885. callbackOutput = (callback ||defaultCallback)();
  9886. } catch(e) {
  9887. return makePromise(e, false);
  9888. }
  9889. if (callbackOutput && isFunction(callbackOutput.then)) {
  9890. return callbackOutput.then(function() {
  9891. return makePromise(value, isResolved);
  9892. }, function(error) {
  9893. return makePromise(error, false);
  9894. });
  9895. } else {
  9896. return makePromise(value, isResolved);
  9897. }
  9898. }
  9899. return this.then(function(value) {
  9900. return handleCallback(value, true);
  9901. }, function(error) {
  9902. return handleCallback(error, false);
  9903. });
  9904. }
  9905. }
  9906. };
  9907. return deferred;
  9908. };
  9909. var ref = function(value) {
  9910. if (value && isFunction(value.then)) return value;
  9911. return {
  9912. then: function(callback) {
  9913. var result = defer();
  9914. nextTick(function() {
  9915. result.resolve(callback(value));
  9916. });
  9917. return result.promise;
  9918. }
  9919. };
  9920. };
  9921. /**
  9922. * @ngdoc
  9923. * @name ng.$q#reject
  9924. * @methodOf ng.$q
  9925. * @description
  9926. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  9927. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  9928. * a promise chain, you don't need to worry about it.
  9929. *
  9930. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  9931. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  9932. * a promise error callback and you want to forward the error to the promise derived from the
  9933. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  9934. * `reject`.
  9935. *
  9936. * <pre>
  9937. * promiseB = promiseA.then(function(result) {
  9938. * // success: do something and resolve promiseB
  9939. * // with the old or a new result
  9940. * return result;
  9941. * }, function(reason) {
  9942. * // error: handle the error if possible and
  9943. * // resolve promiseB with newPromiseOrValue,
  9944. * // otherwise forward the rejection to promiseB
  9945. * if (canHandle(reason)) {
  9946. * // handle the error and recover
  9947. * return newPromiseOrValue;
  9948. * }
  9949. * return $q.reject(reason);
  9950. * });
  9951. * </pre>
  9952. *
  9953. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  9954. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  9955. */
  9956. var reject = function(reason) {
  9957. return {
  9958. then: function(callback, errback) {
  9959. var result = defer();
  9960. nextTick(function() {
  9961. try {
  9962. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  9963. } catch(e) {
  9964. result.reject(e);
  9965. exceptionHandler(e);
  9966. }
  9967. });
  9968. return result.promise;
  9969. }
  9970. };
  9971. };
  9972. /**
  9973. * @ngdoc
  9974. * @name ng.$q#when
  9975. * @methodOf ng.$q
  9976. * @description
  9977. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  9978. * This is useful when you are dealing with an object that might or might not be a promise, or if
  9979. * the promise comes from a source that can't be trusted.
  9980. *
  9981. * @param {*} value Value or a promise
  9982. * @returns {Promise} Returns a promise of the passed value or promise
  9983. */
  9984. var when = function(value, callback, errback, progressback) {
  9985. var result = defer(),
  9986. done;
  9987. var wrappedCallback = function(value) {
  9988. try {
  9989. return (isFunction(callback) ? callback : defaultCallback)(value);
  9990. } catch (e) {
  9991. exceptionHandler(e);
  9992. return reject(e);
  9993. }
  9994. };
  9995. var wrappedErrback = function(reason) {
  9996. try {
  9997. return (isFunction(errback) ? errback : defaultErrback)(reason);
  9998. } catch (e) {
  9999. exceptionHandler(e);
  10000. return reject(e);
  10001. }
  10002. };
  10003. var wrappedProgressback = function(progress) {
  10004. try {
  10005. return (isFunction(progressback) ? progressback : defaultCallback)(progress);
  10006. } catch (e) {
  10007. exceptionHandler(e);
  10008. }
  10009. };
  10010. nextTick(function() {
  10011. ref(value).then(function(value) {
  10012. if (done) return;
  10013. done = true;
  10014. result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
  10015. }, function(reason) {
  10016. if (done) return;
  10017. done = true;
  10018. result.resolve(wrappedErrback(reason));
  10019. }, function(progress) {
  10020. if (done) return;
  10021. result.notify(wrappedProgressback(progress));
  10022. });
  10023. });
  10024. return result.promise;
  10025. };
  10026. function defaultCallback(value) {
  10027. return value;
  10028. }
  10029. function defaultErrback(reason) {
  10030. return reject(reason);
  10031. }
  10032. /**
  10033. * @ngdoc
  10034. * @name ng.$q#all
  10035. * @methodOf ng.$q
  10036. * @description
  10037. * Combines multiple promises into a single promise that is resolved when all of the input
  10038. * promises are resolved.
  10039. *
  10040. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  10041. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  10042. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  10043. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  10044. * with the same rejection value.
  10045. */
  10046. function all(promises) {
  10047. var deferred = defer(),
  10048. counter = 0,
  10049. results = isArray(promises) ? [] : {};
  10050. forEach(promises, function(promise, key) {
  10051. counter++;
  10052. ref(promise).then(function(value) {
  10053. if (results.hasOwnProperty(key)) return;
  10054. results[key] = value;
  10055. if (!(--counter)) deferred.resolve(results);
  10056. }, function(reason) {
  10057. if (results.hasOwnProperty(key)) return;
  10058. deferred.reject(reason);
  10059. });
  10060. });
  10061. if (counter === 0) {
  10062. deferred.resolve(results);
  10063. }
  10064. return deferred.promise;
  10065. }
  10066. return {
  10067. defer: defer,
  10068. reject: reject,
  10069. when: when,
  10070. all: all
  10071. };
  10072. }
  10073. /**
  10074. * DESIGN NOTES
  10075. *
  10076. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  10077. *
  10078. * The typical use of scope is to watch the expressions, which most of the time return the same
  10079. * value as last time so we optimize the operation.
  10080. *
  10081. * Closures construction is expensive in terms of speed as well as memory:
  10082. * - No closures, instead use prototypical inheritance for API
  10083. * - Internal state needs to be stored on scope directly, which means that private state is
  10084. * exposed as $$____ properties
  10085. *
  10086. * Loop operations are optimized by using while(count--) { ... }
  10087. * - this means that in order to keep the same order of execution as addition we have to add
  10088. * items to the array at the beginning (shift) instead of at the end (push)
  10089. *
  10090. * Child scopes are created and removed often
  10091. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  10092. *
  10093. * There are few watches then a lot of observers. This is why you don't want the observer to be
  10094. * implemented in the same way as watch. Watch requires return of initialization function which
  10095. * are expensive to construct.
  10096. */
  10097. /**
  10098. * @ngdoc object
  10099. * @name ng.$rootScopeProvider
  10100. * @description
  10101. *
  10102. * Provider for the $rootScope service.
  10103. */
  10104. /**
  10105. * @ngdoc function
  10106. * @name ng.$rootScopeProvider#digestTtl
  10107. * @methodOf ng.$rootScopeProvider
  10108. * @description
  10109. *
  10110. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  10111. * assuming that the model is unstable.
  10112. *
  10113. * The current default is 10 iterations.
  10114. *
  10115. * In complex applications it's possible that the dependencies between `$watch`s will result in
  10116. * several digest iterations. However if an application needs more than the default 10 digest
  10117. * iterations for its model to stabilize then you should investigate what is causing the model to
  10118. * continuously change during the digest.
  10119. *
  10120. * Increasing the TTL could have performance implications, so you should not change it without
  10121. * proper justification.
  10122. *
  10123. * @param {number} limit The number of digest iterations.
  10124. */
  10125. /**
  10126. * @ngdoc object
  10127. * @name ng.$rootScope
  10128. * @description
  10129. *
  10130. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  10131. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  10132. * between the model and the view, via a mechanism for watching the model for changes.
  10133. * They also provide an event emission/broadcast and subscription facility. See the
  10134. * {@link guide/scope developer guide on scopes}.
  10135. */
  10136. function $RootScopeProvider(){
  10137. var TTL = 10;
  10138. var $rootScopeMinErr = minErr('$rootScope');
  10139. var lastDirtyWatch = null;
  10140. this.digestTtl = function(value) {
  10141. if (arguments.length) {
  10142. TTL = value;
  10143. }
  10144. return TTL;
  10145. };
  10146. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  10147. function( $injector, $exceptionHandler, $parse, $browser) {
  10148. /**
  10149. * @ngdoc function
  10150. * @name ng.$rootScope.Scope
  10151. *
  10152. * @description
  10153. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  10154. * {@link AUTO.$injector $injector}. Child scopes are created using the
  10155. * {@link ng.$rootScope.Scope#methods_$new $new()} method. (Most scopes are created automatically when
  10156. * compiled HTML template is executed.)
  10157. *
  10158. * Here is a simple scope snippet to show how you can interact with the scope.
  10159. * <pre>
  10160. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  10161. * </pre>
  10162. *
  10163. * # Inheritance
  10164. * A scope can inherit from a parent scope, as in this example:
  10165. * <pre>
  10166. var parent = $rootScope;
  10167. var child = parent.$new();
  10168. parent.salutation = "Hello";
  10169. child.name = "World";
  10170. expect(child.salutation).toEqual('Hello');
  10171. child.salutation = "Welcome";
  10172. expect(child.salutation).toEqual('Welcome');
  10173. expect(parent.salutation).toEqual('Hello');
  10174. * </pre>
  10175. *
  10176. *
  10177. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  10178. * provided for the current scope. Defaults to {@link ng}.
  10179. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  10180. * append/override services provided by `providers`. This is handy
  10181. * when unit-testing and having the need to override a default
  10182. * service.
  10183. * @returns {Object} Newly created scope.
  10184. *
  10185. */
  10186. function Scope() {
  10187. this.$id = nextUid();
  10188. this.$$phase = this.$parent = this.$$watchers =
  10189. this.$$nextSibling = this.$$prevSibling =
  10190. this.$$childHead = this.$$childTail = null;
  10191. this['this'] = this.$root = this;
  10192. this.$$destroyed = false;
  10193. this.$$asyncQueue = [];
  10194. this.$$postDigestQueue = [];
  10195. this.$$listeners = {};
  10196. this.$$listenerCount = {};
  10197. this.$$isolateBindings = {};
  10198. }
  10199. /**
  10200. * @ngdoc property
  10201. * @name ng.$rootScope.Scope#$id
  10202. * @propertyOf ng.$rootScope.Scope
  10203. * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
  10204. * debugging.
  10205. */
  10206. Scope.prototype = {
  10207. constructor: Scope,
  10208. /**
  10209. * @ngdoc function
  10210. * @name ng.$rootScope.Scope#$new
  10211. * @methodOf ng.$rootScope.Scope
  10212. * @function
  10213. *
  10214. * @description
  10215. * Creates a new child {@link ng.$rootScope.Scope scope}.
  10216. *
  10217. * The parent scope will propagate the {@link ng.$rootScope.Scope#methods_$digest $digest()} and
  10218. * {@link ng.$rootScope.Scope#methods_$digest $digest()} events. The scope can be removed from the
  10219. * scope hierarchy using {@link ng.$rootScope.Scope#methods_$destroy $destroy()}.
  10220. *
  10221. * {@link ng.$rootScope.Scope#methods_$destroy $destroy()} must be called on a scope when it is
  10222. * desired for the scope and its child scopes to be permanently detached from the parent and
  10223. * thus stop participating in model change detection and listener notification by invoking.
  10224. *
  10225. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  10226. * parent scope. The scope is isolated, as it can not see parent scope properties.
  10227. * When creating widgets, it is useful for the widget to not accidentally read parent
  10228. * state.
  10229. *
  10230. * @returns {Object} The newly created child scope.
  10231. *
  10232. */
  10233. $new: function(isolate) {
  10234. var ChildScope,
  10235. child;
  10236. if (isolate) {
  10237. child = new Scope();
  10238. child.$root = this.$root;
  10239. // ensure that there is just one async queue per $rootScope and its children
  10240. child.$$asyncQueue = this.$$asyncQueue;
  10241. child.$$postDigestQueue = this.$$postDigestQueue;
  10242. } else {
  10243. ChildScope = function() {}; // should be anonymous; This is so that when the minifier munges
  10244. // the name it does not become random set of chars. This will then show up as class
  10245. // name in the web inspector.
  10246. ChildScope.prototype = this;
  10247. child = new ChildScope();
  10248. child.$id = nextUid();
  10249. }
  10250. child['this'] = child;
  10251. child.$$listeners = {};
  10252. child.$$listenerCount = {};
  10253. child.$parent = this;
  10254. child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
  10255. child.$$prevSibling = this.$$childTail;
  10256. if (this.$$childHead) {
  10257. this.$$childTail.$$nextSibling = child;
  10258. this.$$childTail = child;
  10259. } else {
  10260. this.$$childHead = this.$$childTail = child;
  10261. }
  10262. return child;
  10263. },
  10264. /**
  10265. * @ngdoc function
  10266. * @name ng.$rootScope.Scope#$watch
  10267. * @methodOf ng.$rootScope.Scope
  10268. * @function
  10269. *
  10270. * @description
  10271. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  10272. *
  10273. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#methods_$digest
  10274. * $digest()} and should return the value that will be watched. (Since
  10275. * {@link ng.$rootScope.Scope#methods_$digest $digest()} reruns when it detects changes the
  10276. * `watchExpression` can execute multiple times per
  10277. * {@link ng.$rootScope.Scope#methods_$digest $digest()} and should be idempotent.)
  10278. * - The `listener` is called only when the value from the current `watchExpression` and the
  10279. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  10280. * see below). The inequality is determined according to
  10281. * {@link angular.equals} function. To save the value of the object for later comparison,
  10282. * the {@link angular.copy} function is used. It also means that watching complex options
  10283. * will have adverse memory and performance implications.
  10284. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  10285. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  10286. * iteration limit is 10 to prevent an infinite loop deadlock.
  10287. *
  10288. *
  10289. * If you want to be notified whenever {@link ng.$rootScope.Scope#methods_$digest $digest} is called,
  10290. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  10291. * can execute multiple times per {@link ng.$rootScope.Scope#methods_$digest $digest} cycle when a
  10292. * change is detected, be prepared for multiple calls to your listener.)
  10293. *
  10294. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  10295. * (via {@link ng.$rootScope.Scope#methods_$evalAsync $evalAsync}) to initialize the
  10296. * watcher. In rare cases, this is undesirable because the listener is called when the result
  10297. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  10298. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  10299. * listener was called due to initialization.
  10300. *
  10301. * The example below contains an illustration of using a function as your $watch listener
  10302. *
  10303. *
  10304. * # Example
  10305. * <pre>
  10306. // let's assume that scope was dependency injected as the $rootScope
  10307. var scope = $rootScope;
  10308. scope.name = 'misko';
  10309. scope.counter = 0;
  10310. expect(scope.counter).toEqual(0);
  10311. scope.$watch('name', function(newValue, oldValue) {
  10312. scope.counter = scope.counter + 1;
  10313. });
  10314. expect(scope.counter).toEqual(0);
  10315. scope.$digest();
  10316. // no variable change
  10317. expect(scope.counter).toEqual(0);
  10318. scope.name = 'adam';
  10319. scope.$digest();
  10320. expect(scope.counter).toEqual(1);
  10321. // Using a listener function
  10322. var food;
  10323. scope.foodCounter = 0;
  10324. expect(scope.foodCounter).toEqual(0);
  10325. scope.$watch(
  10326. // This is the listener function
  10327. function() { return food; },
  10328. // This is the change handler
  10329. function(newValue, oldValue) {
  10330. if ( newValue !== oldValue ) {
  10331. // Only increment the counter if the value changed
  10332. scope.foodCounter = scope.foodCounter + 1;
  10333. }
  10334. }
  10335. );
  10336. // No digest has been run so the counter will be zero
  10337. expect(scope.foodCounter).toEqual(0);
  10338. // Run the digest but since food has not changed count will still be zero
  10339. scope.$digest();
  10340. expect(scope.foodCounter).toEqual(0);
  10341. // Update food and run digest. Now the counter will increment
  10342. food = 'cheeseburger';
  10343. scope.$digest();
  10344. expect(scope.foodCounter).toEqual(1);
  10345. * </pre>
  10346. *
  10347. *
  10348. *
  10349. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  10350. * {@link ng.$rootScope.Scope#methods_$digest $digest} cycle. A change in the return value triggers
  10351. * a call to the `listener`.
  10352. *
  10353. * - `string`: Evaluated as {@link guide/expression expression}
  10354. * - `function(scope)`: called with current `scope` as a parameter.
  10355. * @param {(function()|string)=} listener Callback called whenever the return value of
  10356. * the `watchExpression` changes.
  10357. *
  10358. * - `string`: Evaluated as {@link guide/expression expression}
  10359. * - `function(newValue, oldValue, scope)`: called with current and previous values as
  10360. * parameters.
  10361. *
  10362. * @param {boolean=} objectEquality Compare object for equality rather than for reference.
  10363. * @returns {function()} Returns a deregistration function for this listener.
  10364. */
  10365. $watch: function(watchExp, listener, objectEquality) {
  10366. var scope = this,
  10367. get = compileToFn(watchExp, 'watch'),
  10368. array = scope.$$watchers,
  10369. watcher = {
  10370. fn: listener,
  10371. last: initWatchVal,
  10372. get: get,
  10373. exp: watchExp,
  10374. eq: !!objectEquality
  10375. };
  10376. lastDirtyWatch = null;
  10377. // in the case user pass string, we need to compile it, do we really need this ?
  10378. if (!isFunction(listener)) {
  10379. var listenFn = compileToFn(listener || noop, 'listener');
  10380. watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
  10381. }
  10382. if (typeof watchExp == 'string' && get.constant) {
  10383. var originalFn = watcher.fn;
  10384. watcher.fn = function(newVal, oldVal, scope) {
  10385. originalFn.call(this, newVal, oldVal, scope);
  10386. arrayRemove(array, watcher);
  10387. };
  10388. }
  10389. if (!array) {
  10390. array = scope.$$watchers = [];
  10391. }
  10392. // we use unshift since we use a while loop in $digest for speed.
  10393. // the while loop reads in reverse order.
  10394. array.unshift(watcher);
  10395. return function() {
  10396. arrayRemove(array, watcher);
  10397. lastDirtyWatch = null;
  10398. };
  10399. },
  10400. /**
  10401. * @ngdoc function
  10402. * @name ng.$rootScope.Scope#$watchCollection
  10403. * @methodOf ng.$rootScope.Scope
  10404. * @function
  10405. *
  10406. * @description
  10407. * Shallow watches the properties of an object and fires whenever any of the properties change
  10408. * (for arrays, this implies watching the array items; for object maps, this implies watching
  10409. * the properties). If a change is detected, the `listener` callback is fired.
  10410. *
  10411. * - The `obj` collection is observed via standard $watch operation and is examined on every
  10412. * call to $digest() to see if any items have been added, removed, or moved.
  10413. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  10414. * adding, removing, and moving items belonging to an object or array.
  10415. *
  10416. *
  10417. * # Example
  10418. * <pre>
  10419. $scope.names = ['igor', 'matias', 'misko', 'james'];
  10420. $scope.dataCount = 4;
  10421. $scope.$watchCollection('names', function(newNames, oldNames) {
  10422. $scope.dataCount = newNames.length;
  10423. });
  10424. expect($scope.dataCount).toEqual(4);
  10425. $scope.$digest();
  10426. //still at 4 ... no changes
  10427. expect($scope.dataCount).toEqual(4);
  10428. $scope.names.pop();
  10429. $scope.$digest();
  10430. //now there's been a change
  10431. expect($scope.dataCount).toEqual(3);
  10432. * </pre>
  10433. *
  10434. *
  10435. * @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The
  10436. * expression value should evaluate to an object or an array which is observed on each
  10437. * {@link ng.$rootScope.Scope#methods_$digest $digest} cycle. Any shallow change within the
  10438. * collection will trigger a call to the `listener`.
  10439. *
  10440. * @param {function(newCollection, oldCollection, scope)} listener a callback function that is
  10441. * fired with both the `newCollection` and `oldCollection` as parameters.
  10442. * The `newCollection` object is the newly modified data obtained from the `obj` expression
  10443. * and the `oldCollection` object is a copy of the former collection data.
  10444. * The `scope` refers to the current scope.
  10445. *
  10446. * @returns {function()} Returns a de-registration function for this listener. When the
  10447. * de-registration function is executed, the internal watch operation is terminated.
  10448. */
  10449. $watchCollection: function(obj, listener) {
  10450. var self = this;
  10451. var oldValue;
  10452. var newValue;
  10453. var changeDetected = 0;
  10454. var objGetter = $parse(obj);
  10455. var internalArray = [];
  10456. var internalObject = {};
  10457. var oldLength = 0;
  10458. function $watchCollectionWatch() {
  10459. newValue = objGetter(self);
  10460. var newLength, key;
  10461. if (!isObject(newValue)) {
  10462. if (oldValue !== newValue) {
  10463. oldValue = newValue;
  10464. changeDetected++;
  10465. }
  10466. } else if (isArrayLike(newValue)) {
  10467. if (oldValue !== internalArray) {
  10468. // we are transitioning from something which was not an array into array.
  10469. oldValue = internalArray;
  10470. oldLength = oldValue.length = 0;
  10471. changeDetected++;
  10472. }
  10473. newLength = newValue.length;
  10474. if (oldLength !== newLength) {
  10475. // if lengths do not match we need to trigger change notification
  10476. changeDetected++;
  10477. oldValue.length = oldLength = newLength;
  10478. }
  10479. // copy the items to oldValue and look for changes.
  10480. for (var i = 0; i < newLength; i++) {
  10481. if (oldValue[i] !== newValue[i]) {
  10482. changeDetected++;
  10483. oldValue[i] = newValue[i];
  10484. }
  10485. }
  10486. } else {
  10487. if (oldValue !== internalObject) {
  10488. // we are transitioning from something which was not an object into object.
  10489. oldValue = internalObject = {};
  10490. oldLength = 0;
  10491. changeDetected++;
  10492. }
  10493. // copy the items to oldValue and look for changes.
  10494. newLength = 0;
  10495. for (key in newValue) {
  10496. if (newValue.hasOwnProperty(key)) {
  10497. newLength++;
  10498. if (oldValue.hasOwnProperty(key)) {
  10499. if (oldValue[key] !== newValue[key]) {
  10500. changeDetected++;
  10501. oldValue[key] = newValue[key];
  10502. }
  10503. } else {
  10504. oldLength++;
  10505. oldValue[key] = newValue[key];
  10506. changeDetected++;
  10507. }
  10508. }
  10509. }
  10510. if (oldLength > newLength) {
  10511. // we used to have more keys, need to find them and destroy them.
  10512. changeDetected++;
  10513. for(key in oldValue) {
  10514. if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
  10515. oldLength--;
  10516. delete oldValue[key];
  10517. }
  10518. }
  10519. }
  10520. }
  10521. return changeDetected;
  10522. }
  10523. function $watchCollectionAction() {
  10524. listener(newValue, oldValue, self);
  10525. }
  10526. return this.$watch($watchCollectionWatch, $watchCollectionAction);
  10527. },
  10528. /**
  10529. * @ngdoc function
  10530. * @name ng.$rootScope.Scope#$digest
  10531. * @methodOf ng.$rootScope.Scope
  10532. * @function
  10533. *
  10534. * @description
  10535. * Processes all of the {@link ng.$rootScope.Scope#methods_$watch watchers} of the current scope and
  10536. * its children. Because a {@link ng.$rootScope.Scope#methods_$watch watcher}'s listener can change
  10537. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#methods_$watch watchers}
  10538. * until no more listeners are firing. This means that it is possible to get into an infinite
  10539. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  10540. * iterations exceeds 10.
  10541. *
  10542. * Usually, you don't call `$digest()` directly in
  10543. * {@link ng.directive:ngController controllers} or in
  10544. * {@link ng.$compileProvider#methods_directive directives}.
  10545. * Instead, you should call {@link ng.$rootScope.Scope#methods_$apply $apply()} (typically from within
  10546. * a {@link ng.$compileProvider#methods_directive directives}), which will force a `$digest()`.
  10547. *
  10548. * If you want to be notified whenever `$digest()` is called,
  10549. * you can register a `watchExpression` function with
  10550. * {@link ng.$rootScope.Scope#methods_$watch $watch()} with no `listener`.
  10551. *
  10552. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  10553. *
  10554. * # Example
  10555. * <pre>
  10556. var scope = ...;
  10557. scope.name = 'misko';
  10558. scope.counter = 0;
  10559. expect(scope.counter).toEqual(0);
  10560. scope.$watch('name', function(newValue, oldValue) {
  10561. scope.counter = scope.counter + 1;
  10562. });
  10563. expect(scope.counter).toEqual(0);
  10564. scope.$digest();
  10565. // no variable change
  10566. expect(scope.counter).toEqual(0);
  10567. scope.name = 'adam';
  10568. scope.$digest();
  10569. expect(scope.counter).toEqual(1);
  10570. * </pre>
  10571. *
  10572. */
  10573. $digest: function() {
  10574. var watch, value, last,
  10575. watchers,
  10576. asyncQueue = this.$$asyncQueue,
  10577. postDigestQueue = this.$$postDigestQueue,
  10578. length,
  10579. dirty, ttl = TTL,
  10580. next, current, target = this,
  10581. watchLog = [],
  10582. logIdx, logMsg, asyncTask;
  10583. beginPhase('$digest');
  10584. lastDirtyWatch = null;
  10585. do { // "while dirty" loop
  10586. dirty = false;
  10587. current = target;
  10588. while(asyncQueue.length) {
  10589. try {
  10590. asyncTask = asyncQueue.shift();
  10591. asyncTask.scope.$eval(asyncTask.expression);
  10592. } catch (e) {
  10593. clearPhase();
  10594. $exceptionHandler(e);
  10595. }
  10596. lastDirtyWatch = null;
  10597. }
  10598. traverseScopesLoop:
  10599. do { // "traverse the scopes" loop
  10600. if ((watchers = current.$$watchers)) {
  10601. // process our watches
  10602. length = watchers.length;
  10603. while (length--) {
  10604. try {
  10605. watch = watchers[length];
  10606. // Most common watches are on primitives, in which case we can short
  10607. // circuit it with === operator, only when === fails do we use .equals
  10608. if (watch) {
  10609. if ((value = watch.get(current)) !== (last = watch.last) &&
  10610. !(watch.eq
  10611. ? equals(value, last)
  10612. : (typeof value == 'number' && typeof last == 'number'
  10613. && isNaN(value) && isNaN(last)))) {
  10614. dirty = true;
  10615. lastDirtyWatch = watch;
  10616. watch.last = watch.eq ? copy(value) : value;
  10617. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  10618. if (ttl < 5) {
  10619. logIdx = 4 - ttl;
  10620. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  10621. logMsg = (isFunction(watch.exp))
  10622. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  10623. : watch.exp;
  10624. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  10625. watchLog[logIdx].push(logMsg);
  10626. }
  10627. } else if (watch === lastDirtyWatch) {
  10628. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  10629. // have already been tested.
  10630. dirty = false;
  10631. break traverseScopesLoop;
  10632. }
  10633. }
  10634. } catch (e) {
  10635. clearPhase();
  10636. $exceptionHandler(e);
  10637. }
  10638. }
  10639. }
  10640. // Insanity Warning: scope depth-first traversal
  10641. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  10642. // this piece should be kept in sync with the traversal in $broadcast
  10643. if (!(next = (current.$$childHead ||
  10644. (current !== target && current.$$nextSibling)))) {
  10645. while(current !== target && !(next = current.$$nextSibling)) {
  10646. current = current.$parent;
  10647. }
  10648. }
  10649. } while ((current = next));
  10650. // `break traverseScopesLoop;` takes us to here
  10651. if((dirty || asyncQueue.length) && !(ttl--)) {
  10652. clearPhase();
  10653. throw $rootScopeMinErr('infdig',
  10654. '{0} $digest() iterations reached. Aborting!\n' +
  10655. 'Watchers fired in the last 5 iterations: {1}',
  10656. TTL, toJson(watchLog));
  10657. }
  10658. } while (dirty || asyncQueue.length);
  10659. clearPhase();
  10660. while(postDigestQueue.length) {
  10661. try {
  10662. postDigestQueue.shift()();
  10663. } catch (e) {
  10664. $exceptionHandler(e);
  10665. }
  10666. }
  10667. },
  10668. /**
  10669. * @ngdoc event
  10670. * @name ng.$rootScope.Scope#$destroy
  10671. * @eventOf ng.$rootScope.Scope
  10672. * @eventType broadcast on scope being destroyed
  10673. *
  10674. * @description
  10675. * Broadcasted when a scope and its children are being destroyed.
  10676. *
  10677. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  10678. * clean up DOM bindings before an element is removed from the DOM.
  10679. */
  10680. /**
  10681. * @ngdoc function
  10682. * @name ng.$rootScope.Scope#$destroy
  10683. * @methodOf ng.$rootScope.Scope
  10684. * @function
  10685. *
  10686. * @description
  10687. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  10688. * that calls to {@link ng.$rootScope.Scope#methods_$digest $digest()} will no longer
  10689. * propagate to the current scope and its children. Removal also implies that the current
  10690. * scope is eligible for garbage collection.
  10691. *
  10692. * The `$destroy()` is usually used by directives such as
  10693. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  10694. * unrolling of the loop.
  10695. *
  10696. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  10697. * Application code can register a `$destroy` event handler that will give it a chance to
  10698. * perform any necessary cleanup.
  10699. *
  10700. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  10701. * clean up DOM bindings before an element is removed from the DOM.
  10702. */
  10703. $destroy: function() {
  10704. // we can't destroy the root scope or a scope that has been already destroyed
  10705. if (this.$$destroyed) return;
  10706. var parent = this.$parent;
  10707. this.$broadcast('$destroy');
  10708. this.$$destroyed = true;
  10709. if (this === $rootScope) return;
  10710. forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
  10711. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  10712. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  10713. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  10714. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  10715. // This is bogus code that works around Chrome's GC leak
  10716. // see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  10717. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  10718. this.$$childTail = null;
  10719. },
  10720. /**
  10721. * @ngdoc function
  10722. * @name ng.$rootScope.Scope#$eval
  10723. * @methodOf ng.$rootScope.Scope
  10724. * @function
  10725. *
  10726. * @description
  10727. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  10728. * the expression are propagated (uncaught). This is useful when evaluating Angular
  10729. * expressions.
  10730. *
  10731. * # Example
  10732. * <pre>
  10733. var scope = ng.$rootScope.Scope();
  10734. scope.a = 1;
  10735. scope.b = 2;
  10736. expect(scope.$eval('a+b')).toEqual(3);
  10737. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  10738. * </pre>
  10739. *
  10740. * @param {(string|function())=} expression An angular expression to be executed.
  10741. *
  10742. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  10743. * - `function(scope)`: execute the function with the current `scope` parameter.
  10744. *
  10745. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  10746. * @returns {*} The result of evaluating the expression.
  10747. */
  10748. $eval: function(expr, locals) {
  10749. return $parse(expr)(this, locals);
  10750. },
  10751. /**
  10752. * @ngdoc function
  10753. * @name ng.$rootScope.Scope#$evalAsync
  10754. * @methodOf ng.$rootScope.Scope
  10755. * @function
  10756. *
  10757. * @description
  10758. * Executes the expression on the current scope at a later point in time.
  10759. *
  10760. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  10761. * that:
  10762. *
  10763. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  10764. * rendering).
  10765. * - at least one {@link ng.$rootScope.Scope#methods_$digest $digest cycle} will be performed after
  10766. * `expression` execution.
  10767. *
  10768. * Any exceptions from the execution of the expression are forwarded to the
  10769. * {@link ng.$exceptionHandler $exceptionHandler} service.
  10770. *
  10771. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  10772. * will be scheduled. However, it is encouraged to always call code that changes the model
  10773. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  10774. *
  10775. * @param {(string|function())=} expression An angular expression to be executed.
  10776. *
  10777. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  10778. * - `function(scope)`: execute the function with the current `scope` parameter.
  10779. *
  10780. */
  10781. $evalAsync: function(expr) {
  10782. // if we are outside of an $digest loop and this is the first time we are scheduling async
  10783. // task also schedule async auto-flush
  10784. if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
  10785. $browser.defer(function() {
  10786. if ($rootScope.$$asyncQueue.length) {
  10787. $rootScope.$digest();
  10788. }
  10789. });
  10790. }
  10791. this.$$asyncQueue.push({scope: this, expression: expr});
  10792. },
  10793. $$postDigest : function(fn) {
  10794. this.$$postDigestQueue.push(fn);
  10795. },
  10796. /**
  10797. * @ngdoc function
  10798. * @name ng.$rootScope.Scope#$apply
  10799. * @methodOf ng.$rootScope.Scope
  10800. * @function
  10801. *
  10802. * @description
  10803. * `$apply()` is used to execute an expression in angular from outside of the angular
  10804. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  10805. * Because we are calling into the angular framework we need to perform proper scope life
  10806. * cycle of {@link ng.$exceptionHandler exception handling},
  10807. * {@link ng.$rootScope.Scope#methods_$digest executing watches}.
  10808. *
  10809. * ## Life cycle
  10810. *
  10811. * # Pseudo-Code of `$apply()`
  10812. * <pre>
  10813. function $apply(expr) {
  10814. try {
  10815. return $eval(expr);
  10816. } catch (e) {
  10817. $exceptionHandler(e);
  10818. } finally {
  10819. $root.$digest();
  10820. }
  10821. }
  10822. * </pre>
  10823. *
  10824. *
  10825. * Scope's `$apply()` method transitions through the following stages:
  10826. *
  10827. * 1. The {@link guide/expression expression} is executed using the
  10828. * {@link ng.$rootScope.Scope#methods_$eval $eval()} method.
  10829. * 2. Any exceptions from the execution of the expression are forwarded to the
  10830. * {@link ng.$exceptionHandler $exceptionHandler} service.
  10831. * 3. The {@link ng.$rootScope.Scope#methods_$watch watch} listeners are fired immediately after the
  10832. * expression was executed using the {@link ng.$rootScope.Scope#methods_$digest $digest()} method.
  10833. *
  10834. *
  10835. * @param {(string|function())=} exp An angular expression to be executed.
  10836. *
  10837. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  10838. * - `function(scope)`: execute the function with current `scope` parameter.
  10839. *
  10840. * @returns {*} The result of evaluating the expression.
  10841. */
  10842. $apply: function(expr) {
  10843. try {
  10844. beginPhase('$apply');
  10845. return this.$eval(expr);
  10846. } catch (e) {
  10847. $exceptionHandler(e);
  10848. } finally {
  10849. clearPhase();
  10850. try {
  10851. $rootScope.$digest();
  10852. } catch (e) {
  10853. $exceptionHandler(e);
  10854. throw e;
  10855. }
  10856. }
  10857. },
  10858. /**
  10859. * @ngdoc function
  10860. * @name ng.$rootScope.Scope#$on
  10861. * @methodOf ng.$rootScope.Scope
  10862. * @function
  10863. *
  10864. * @description
  10865. * Listens on events of a given type. See {@link ng.$rootScope.Scope#methods_$emit $emit} for
  10866. * discussion of event life cycle.
  10867. *
  10868. * The event listener function format is: `function(event, args...)`. The `event` object
  10869. * passed into the listener has the following attributes:
  10870. *
  10871. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  10872. * `$broadcast`-ed.
  10873. * - `currentScope` - `{Scope}`: the current scope which is handling the event.
  10874. * - `name` - `{string}`: name of the event.
  10875. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  10876. * further event propagation (available only for events that were `$emit`-ed).
  10877. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  10878. * to true.
  10879. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  10880. *
  10881. * @param {string} name Event name to listen on.
  10882. * @param {function(event, args...)} listener Function to call when the event is emitted.
  10883. * @returns {function()} Returns a deregistration function for this listener.
  10884. */
  10885. $on: function(name, listener) {
  10886. var namedListeners = this.$$listeners[name];
  10887. if (!namedListeners) {
  10888. this.$$listeners[name] = namedListeners = [];
  10889. }
  10890. namedListeners.push(listener);
  10891. var current = this;
  10892. do {
  10893. if (!current.$$listenerCount[name]) {
  10894. current.$$listenerCount[name] = 0;
  10895. }
  10896. current.$$listenerCount[name]++;
  10897. } while ((current = current.$parent));
  10898. var self = this;
  10899. return function() {
  10900. namedListeners[indexOf(namedListeners, listener)] = null;
  10901. decrementListenerCount(self, 1, name);
  10902. };
  10903. },
  10904. /**
  10905. * @ngdoc function
  10906. * @name ng.$rootScope.Scope#$emit
  10907. * @methodOf ng.$rootScope.Scope
  10908. * @function
  10909. *
  10910. * @description
  10911. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  10912. * registered {@link ng.$rootScope.Scope#methods_$on} listeners.
  10913. *
  10914. * The event life cycle starts at the scope on which `$emit` was called. All
  10915. * {@link ng.$rootScope.Scope#methods_$on listeners} listening for `name` event on this scope get
  10916. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  10917. * registered listeners along the way. The event will stop propagating if one of the listeners
  10918. * cancels it.
  10919. *
  10920. * Any exception emitted from the {@link ng.$rootScope.Scope#methods_$on listeners} will be passed
  10921. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  10922. *
  10923. * @param {string} name Event name to emit.
  10924. * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
  10925. * @return {Object} Event object (see {@link ng.$rootScope.Scope#methods_$on}).
  10926. */
  10927. $emit: function(name, args) {
  10928. var empty = [],
  10929. namedListeners,
  10930. scope = this,
  10931. stopPropagation = false,
  10932. event = {
  10933. name: name,
  10934. targetScope: scope,
  10935. stopPropagation: function() {stopPropagation = true;},
  10936. preventDefault: function() {
  10937. event.defaultPrevented = true;
  10938. },
  10939. defaultPrevented: false
  10940. },
  10941. listenerArgs = concat([event], arguments, 1),
  10942. i, length;
  10943. do {
  10944. namedListeners = scope.$$listeners[name] || empty;
  10945. event.currentScope = scope;
  10946. for (i=0, length=namedListeners.length; i<length; i++) {
  10947. // if listeners were deregistered, defragment the array
  10948. if (!namedListeners[i]) {
  10949. namedListeners.splice(i, 1);
  10950. i--;
  10951. length--;
  10952. continue;
  10953. }
  10954. try {
  10955. //allow all listeners attached to the current scope to run
  10956. namedListeners[i].apply(null, listenerArgs);
  10957. } catch (e) {
  10958. $exceptionHandler(e);
  10959. }
  10960. }
  10961. //if any listener on the current scope stops propagation, prevent bubbling
  10962. if (stopPropagation) return event;
  10963. //traverse upwards
  10964. scope = scope.$parent;
  10965. } while (scope);
  10966. return event;
  10967. },
  10968. /**
  10969. * @ngdoc function
  10970. * @name ng.$rootScope.Scope#$broadcast
  10971. * @methodOf ng.$rootScope.Scope
  10972. * @function
  10973. *
  10974. * @description
  10975. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  10976. * registered {@link ng.$rootScope.Scope#methods_$on} listeners.
  10977. *
  10978. * The event life cycle starts at the scope on which `$broadcast` was called. All
  10979. * {@link ng.$rootScope.Scope#methods_$on listeners} listening for `name` event on this scope get
  10980. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  10981. * scope and calls all registered listeners along the way. The event cannot be canceled.
  10982. *
  10983. * Any exception emitted from the {@link ng.$rootScope.Scope#methods_$on listeners} will be passed
  10984. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  10985. *
  10986. * @param {string} name Event name to broadcast.
  10987. * @param {...*} args Optional set of arguments which will be passed onto the event listeners.
  10988. * @return {Object} Event object, see {@link ng.$rootScope.Scope#methods_$on}
  10989. */
  10990. $broadcast: function(name, args) {
  10991. var target = this,
  10992. current = target,
  10993. next = target,
  10994. event = {
  10995. name: name,
  10996. targetScope: target,
  10997. preventDefault: function() {
  10998. event.defaultPrevented = true;
  10999. },
  11000. defaultPrevented: false
  11001. },
  11002. listenerArgs = concat([event], arguments, 1),
  11003. listeners, i, length;
  11004. //down while you can, then up and next sibling or up and next sibling until back at root
  11005. while ((current = next)) {
  11006. event.currentScope = current;
  11007. listeners = current.$$listeners[name] || [];
  11008. for (i=0, length = listeners.length; i<length; i++) {
  11009. // if listeners were deregistered, defragment the array
  11010. if (!listeners[i]) {
  11011. listeners.splice(i, 1);
  11012. i--;
  11013. length--;
  11014. continue;
  11015. }
  11016. try {
  11017. listeners[i].apply(null, listenerArgs);
  11018. } catch(e) {
  11019. $exceptionHandler(e);
  11020. }
  11021. }
  11022. // Insanity Warning: scope depth-first traversal
  11023. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11024. // this piece should be kept in sync with the traversal in $digest
  11025. // (though it differs due to having the extra check for $$listenerCount)
  11026. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  11027. (current !== target && current.$$nextSibling)))) {
  11028. while(current !== target && !(next = current.$$nextSibling)) {
  11029. current = current.$parent;
  11030. }
  11031. }
  11032. }
  11033. return event;
  11034. }
  11035. };
  11036. var $rootScope = new Scope();
  11037. return $rootScope;
  11038. function beginPhase(phase) {
  11039. if ($rootScope.$$phase) {
  11040. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  11041. }
  11042. $rootScope.$$phase = phase;
  11043. }
  11044. function clearPhase() {
  11045. $rootScope.$$phase = null;
  11046. }
  11047. function compileToFn(exp, name) {
  11048. var fn = $parse(exp);
  11049. assertArgFn(fn, name);
  11050. return fn;
  11051. }
  11052. function decrementListenerCount(current, count, name) {
  11053. do {
  11054. current.$$listenerCount[name] -= count;
  11055. if (current.$$listenerCount[name] === 0) {
  11056. delete current.$$listenerCount[name];
  11057. }
  11058. } while ((current = current.$parent));
  11059. }
  11060. /**
  11061. * function used as an initial value for watchers.
  11062. * because it's unique we can easily tell it apart from other values
  11063. */
  11064. function initWatchVal() {}
  11065. }];
  11066. }
  11067. /**
  11068. * @description
  11069. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  11070. */
  11071. function $$SanitizeUriProvider() {
  11072. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  11073. imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
  11074. /**
  11075. * @description
  11076. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11077. * urls during a[href] sanitization.
  11078. *
  11079. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11080. *
  11081. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  11082. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  11083. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11084. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11085. *
  11086. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11087. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11088. * chaining otherwise.
  11089. */
  11090. this.aHrefSanitizationWhitelist = function(regexp) {
  11091. if (isDefined(regexp)) {
  11092. aHrefSanitizationWhitelist = regexp;
  11093. return this;
  11094. }
  11095. return aHrefSanitizationWhitelist;
  11096. };
  11097. /**
  11098. * @description
  11099. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11100. * urls during img[src] sanitization.
  11101. *
  11102. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11103. *
  11104. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  11105. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  11106. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11107. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11108. *
  11109. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11110. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11111. * chaining otherwise.
  11112. */
  11113. this.imgSrcSanitizationWhitelist = function(regexp) {
  11114. if (isDefined(regexp)) {
  11115. imgSrcSanitizationWhitelist = regexp;
  11116. return this;
  11117. }
  11118. return imgSrcSanitizationWhitelist;
  11119. };
  11120. this.$get = function() {
  11121. return function sanitizeUri(uri, isImage) {
  11122. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  11123. var normalizedVal;
  11124. // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
  11125. if (!msie || msie >= 8 ) {
  11126. normalizedVal = urlResolve(uri).href;
  11127. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  11128. return 'unsafe:'+normalizedVal;
  11129. }
  11130. }
  11131. return uri;
  11132. };
  11133. };
  11134. }
  11135. var $sceMinErr = minErr('$sce');
  11136. var SCE_CONTEXTS = {
  11137. HTML: 'html',
  11138. CSS: 'css',
  11139. URL: 'url',
  11140. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  11141. // url. (e.g. ng-include, script src, templateUrl)
  11142. RESOURCE_URL: 'resourceUrl',
  11143. JS: 'js'
  11144. };
  11145. // Helper functions follow.
  11146. // Copied from:
  11147. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  11148. // Prereq: s is a string.
  11149. function escapeForRegexp(s) {
  11150. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  11151. replace(/\x08/g, '\\x08');
  11152. }
  11153. function adjustMatcher(matcher) {
  11154. if (matcher === 'self') {
  11155. return matcher;
  11156. } else if (isString(matcher)) {
  11157. // Strings match exactly except for 2 wildcards - '*' and '**'.
  11158. // '*' matches any character except those from the set ':/.?&'.
  11159. // '**' matches any character (like .* in a RegExp).
  11160. // More than 2 *'s raises an error as it's ill defined.
  11161. if (matcher.indexOf('***') > -1) {
  11162. throw $sceMinErr('iwcard',
  11163. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  11164. }
  11165. matcher = escapeForRegexp(matcher).
  11166. replace('\\*\\*', '.*').
  11167. replace('\\*', '[^:/.?&;]*');
  11168. return new RegExp('^' + matcher + '$');
  11169. } else if (isRegExp(matcher)) {
  11170. // The only other type of matcher allowed is a Regexp.
  11171. // Match entire URL / disallow partial matches.
  11172. // Flags are reset (i.e. no global, ignoreCase or multiline)
  11173. return new RegExp('^' + matcher.source + '$');
  11174. } else {
  11175. throw $sceMinErr('imatcher',
  11176. 'Matchers may only be "self", string patterns or RegExp objects');
  11177. }
  11178. }
  11179. function adjustMatchers(matchers) {
  11180. var adjustedMatchers = [];
  11181. if (isDefined(matchers)) {
  11182. forEach(matchers, function(matcher) {
  11183. adjustedMatchers.push(adjustMatcher(matcher));
  11184. });
  11185. }
  11186. return adjustedMatchers;
  11187. }
  11188. /**
  11189. * @ngdoc service
  11190. * @name ng.$sceDelegate
  11191. * @function
  11192. *
  11193. * @description
  11194. *
  11195. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  11196. * Contextual Escaping (SCE)} services to AngularJS.
  11197. *
  11198. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  11199. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  11200. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  11201. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  11202. * work because `$sce` delegates to `$sceDelegate` for these operations.
  11203. *
  11204. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  11205. *
  11206. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  11207. * can override it completely to change the behavior of `$sce`, the common case would
  11208. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  11209. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  11210. * templates. Refer {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist
  11211. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  11212. * ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11213. */
  11214. /**
  11215. * @ngdoc object
  11216. * @name ng.$sceDelegateProvider
  11217. * @description
  11218. *
  11219. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  11220. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  11221. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  11222. * ng.$sceDelegateProvider#methods_resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  11223. * {@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11224. *
  11225. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  11226. * Strict Contextual Escaping (SCE)}.
  11227. *
  11228. * **Example**: Consider the following case. <a name="example"></a>
  11229. *
  11230. * - your app is hosted at url `http://myapp.example.com/`
  11231. * - but some of your templates are hosted on other domains you control such as
  11232. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  11233. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  11234. *
  11235. * Here is what a secure configuration for this scenario might look like:
  11236. *
  11237. * <pre class="prettyprint">
  11238. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  11239. * $sceDelegateProvider.resourceUrlWhitelist([
  11240. * // Allow same origin resource loads.
  11241. * 'self',
  11242. * // Allow loading from our assets domain. Notice the difference between * and **.
  11243. * 'http://srv*.assets.example.com/**']);
  11244. *
  11245. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  11246. * $sceDelegateProvider.resourceUrlBlacklist([
  11247. * 'http://myapp.example.com/clickThru**']);
  11248. * });
  11249. * </pre>
  11250. */
  11251. function $SceDelegateProvider() {
  11252. this.SCE_CONTEXTS = SCE_CONTEXTS;
  11253. // Resource URLs can also be trusted by policy.
  11254. var resourceUrlWhitelist = ['self'],
  11255. resourceUrlBlacklist = [];
  11256. /**
  11257. * @ngdoc function
  11258. * @name ng.sceDelegateProvider#resourceUrlWhitelist
  11259. * @methodOf ng.$sceDelegateProvider
  11260. * @function
  11261. *
  11262. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  11263. * provided. This must be an array or null. A snapshot of this array is used so further
  11264. * changes to the array are ignored.
  11265. *
  11266. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11267. * allowed in this array.
  11268. *
  11269. * Note: **an empty whitelist array will block all URLs**!
  11270. *
  11271. * @return {Array} the currently set whitelist array.
  11272. *
  11273. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  11274. * same origin resource requests.
  11275. *
  11276. * @description
  11277. * Sets/Gets the whitelist of trusted resource URLs.
  11278. */
  11279. this.resourceUrlWhitelist = function (value) {
  11280. if (arguments.length) {
  11281. resourceUrlWhitelist = adjustMatchers(value);
  11282. }
  11283. return resourceUrlWhitelist;
  11284. };
  11285. /**
  11286. * @ngdoc function
  11287. * @name ng.sceDelegateProvider#resourceUrlBlacklist
  11288. * @methodOf ng.$sceDelegateProvider
  11289. * @function
  11290. *
  11291. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  11292. * provided. This must be an array or null. A snapshot of this array is used so further
  11293. * changes to the array are ignored.
  11294. *
  11295. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11296. * allowed in this array.
  11297. *
  11298. * The typical usage for the blacklist is to **block
  11299. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  11300. * these would otherwise be trusted but actually return content from the redirected domain.
  11301. *
  11302. * Finally, **the blacklist overrides the whitelist** and has the final say.
  11303. *
  11304. * @return {Array} the currently set blacklist array.
  11305. *
  11306. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  11307. * is no blacklist.)
  11308. *
  11309. * @description
  11310. * Sets/Gets the blacklist of trusted resource URLs.
  11311. */
  11312. this.resourceUrlBlacklist = function (value) {
  11313. if (arguments.length) {
  11314. resourceUrlBlacklist = adjustMatchers(value);
  11315. }
  11316. return resourceUrlBlacklist;
  11317. };
  11318. this.$get = ['$injector', function($injector) {
  11319. var htmlSanitizer = function htmlSanitizer(html) {
  11320. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11321. };
  11322. if ($injector.has('$sanitize')) {
  11323. htmlSanitizer = $injector.get('$sanitize');
  11324. }
  11325. function matchUrl(matcher, parsedUrl) {
  11326. if (matcher === 'self') {
  11327. return urlIsSameOrigin(parsedUrl);
  11328. } else {
  11329. // definitely a regex. See adjustMatchers()
  11330. return !!matcher.exec(parsedUrl.href);
  11331. }
  11332. }
  11333. function isResourceUrlAllowedByPolicy(url) {
  11334. var parsedUrl = urlResolve(url.toString());
  11335. var i, n, allowed = false;
  11336. // Ensure that at least one item from the whitelist allows this url.
  11337. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  11338. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  11339. allowed = true;
  11340. break;
  11341. }
  11342. }
  11343. if (allowed) {
  11344. // Ensure that no item from the blacklist blocked this url.
  11345. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  11346. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  11347. allowed = false;
  11348. break;
  11349. }
  11350. }
  11351. }
  11352. return allowed;
  11353. }
  11354. function generateHolderType(Base) {
  11355. var holderType = function TrustedValueHolderType(trustedValue) {
  11356. this.$$unwrapTrustedValue = function() {
  11357. return trustedValue;
  11358. };
  11359. };
  11360. if (Base) {
  11361. holderType.prototype = new Base();
  11362. }
  11363. holderType.prototype.valueOf = function sceValueOf() {
  11364. return this.$$unwrapTrustedValue();
  11365. };
  11366. holderType.prototype.toString = function sceToString() {
  11367. return this.$$unwrapTrustedValue().toString();
  11368. };
  11369. return holderType;
  11370. }
  11371. var trustedValueHolderBase = generateHolderType(),
  11372. byType = {};
  11373. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  11374. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  11375. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  11376. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  11377. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  11378. /**
  11379. * @ngdoc method
  11380. * @name ng.$sceDelegate#trustAs
  11381. * @methodOf ng.$sceDelegate
  11382. *
  11383. * @description
  11384. * Returns an object that is trusted by angular for use in specified strict
  11385. * contextual escaping contexts (such as ng-html-bind-unsafe, ng-include, any src
  11386. * attribute interpolation, any dom event binding attribute interpolation
  11387. * such as for onclick, etc.) that uses the provided value.
  11388. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  11389. *
  11390. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  11391. * resourceUrl, html, js and css.
  11392. * @param {*} value The value that that should be considered trusted/safe.
  11393. * @returns {*} A value that can be used to stand in for the provided `value` in places
  11394. * where Angular expects a $sce.trustAs() return value.
  11395. */
  11396. function trustAs(type, trustedValue) {
  11397. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  11398. if (!Constructor) {
  11399. throw $sceMinErr('icontext',
  11400. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  11401. type, trustedValue);
  11402. }
  11403. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  11404. return trustedValue;
  11405. }
  11406. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  11407. // mutable objects, we ensure here that the value passed in is actually a string.
  11408. if (typeof trustedValue !== 'string') {
  11409. throw $sceMinErr('itype',
  11410. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  11411. type);
  11412. }
  11413. return new Constructor(trustedValue);
  11414. }
  11415. /**
  11416. * @ngdoc method
  11417. * @name ng.$sceDelegate#valueOf
  11418. * @methodOf ng.$sceDelegate
  11419. *
  11420. * @description
  11421. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#methods_trustAs
  11422. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  11423. * ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}.
  11424. *
  11425. * If the passed parameter is not a value that had been returned by {@link
  11426. * ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}, returns it as-is.
  11427. *
  11428. * @param {*} value The result of a prior {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}
  11429. * call or anything else.
  11430. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#methods_trustAs
  11431. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  11432. * `value` unchanged.
  11433. */
  11434. function valueOf(maybeTrusted) {
  11435. if (maybeTrusted instanceof trustedValueHolderBase) {
  11436. return maybeTrusted.$$unwrapTrustedValue();
  11437. } else {
  11438. return maybeTrusted;
  11439. }
  11440. }
  11441. /**
  11442. * @ngdoc method
  11443. * @name ng.$sceDelegate#getTrusted
  11444. * @methodOf ng.$sceDelegate
  11445. *
  11446. * @description
  11447. * Takes the result of a {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`} call and
  11448. * returns the originally supplied value if the queried context type is a supertype of the
  11449. * created type. If this condition isn't satisfied, throws an exception.
  11450. *
  11451. * @param {string} type The kind of context in which this value is to be used.
  11452. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#methods_trustAs
  11453. * `$sceDelegate.trustAs`} call.
  11454. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#methods_trustAs
  11455. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  11456. */
  11457. function getTrusted(type, maybeTrusted) {
  11458. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  11459. return maybeTrusted;
  11460. }
  11461. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  11462. if (constructor && maybeTrusted instanceof constructor) {
  11463. return maybeTrusted.$$unwrapTrustedValue();
  11464. }
  11465. // If we get here, then we may only take one of two actions.
  11466. // 1. sanitize the value for the requested type, or
  11467. // 2. throw an exception.
  11468. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  11469. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  11470. return maybeTrusted;
  11471. } else {
  11472. throw $sceMinErr('insecurl',
  11473. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  11474. maybeTrusted.toString());
  11475. }
  11476. } else if (type === SCE_CONTEXTS.HTML) {
  11477. return htmlSanitizer(maybeTrusted);
  11478. }
  11479. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11480. }
  11481. return { trustAs: trustAs,
  11482. getTrusted: getTrusted,
  11483. valueOf: valueOf };
  11484. }];
  11485. }
  11486. /**
  11487. * @ngdoc object
  11488. * @name ng.$sceProvider
  11489. * @description
  11490. *
  11491. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  11492. * - enable/disable Strict Contextual Escaping (SCE) in a module
  11493. * - override the default implementation with a custom delegate
  11494. *
  11495. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  11496. */
  11497. /* jshint maxlen: false*/
  11498. /**
  11499. * @ngdoc service
  11500. * @name ng.$sce
  11501. * @function
  11502. *
  11503. * @description
  11504. *
  11505. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  11506. *
  11507. * # Strict Contextual Escaping
  11508. *
  11509. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  11510. * contexts to result in a value that is marked as safe to use for that context. One example of
  11511. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  11512. * to these contexts as privileged or SCE contexts.
  11513. *
  11514. * As of version 1.2, Angular ships with SCE enabled by default.
  11515. *
  11516. * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
  11517. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  11518. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  11519. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  11520. * to the top of your HTML document.
  11521. *
  11522. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  11523. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  11524. *
  11525. * Here's an example of a binding in a privileged context:
  11526. *
  11527. * <pre class="prettyprint">
  11528. * <input ng-model="userHtml">
  11529. * <div ng-bind-html="userHtml">
  11530. * </pre>
  11531. *
  11532. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  11533. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  11534. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  11535. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  11536. * security vulnerabilities.)
  11537. *
  11538. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  11539. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  11540. *
  11541. * How would you ensure that every place that used these types of bindings was bound to a value that
  11542. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  11543. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  11544. * properties/fields and forgot to update the binding to the sanitized value?
  11545. *
  11546. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  11547. * determine that something explicitly says it's safe to use a value for binding in that
  11548. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  11549. * for those values that you can easily tell are safe - because they were received from your server,
  11550. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  11551. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  11552. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  11553. *
  11554. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#methods_trustAs $sce.trustAs}
  11555. * (and shorthand methods such as {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}, etc.) to
  11556. * obtain values that will be accepted by SCE / privileged contexts.
  11557. *
  11558. *
  11559. * ## How does it work?
  11560. *
  11561. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#methods_getTrusted
  11562. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  11563. * ng.$sce#methods_parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  11564. * {@link ng.$sce#methods_getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  11565. *
  11566. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  11567. * ng.$sce#methods_parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  11568. * simplified):
  11569. *
  11570. * <pre class="prettyprint">
  11571. * var ngBindHtmlDirective = ['$sce', function($sce) {
  11572. * return function(scope, element, attr) {
  11573. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  11574. * element.html(value || '');
  11575. * });
  11576. * };
  11577. * }];
  11578. * </pre>
  11579. *
  11580. * ## Impact on loading templates
  11581. *
  11582. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  11583. * `templateUrl`'s specified by {@link guide/directive directives}.
  11584. *
  11585. * By default, Angular only loads templates from the same domain and protocol as the application
  11586. * document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl
  11587. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  11588. * protocols, you may either either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist
  11589. * them} or {@link ng.$sce#methods_trustAsResourceUrl wrap it} into a trusted value.
  11590. *
  11591. * *Please note*:
  11592. * The browser's
  11593. * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
  11594. * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)}
  11595. * policy apply in addition to this and may further restrict whether the template is successfully
  11596. * loaded. This means that without the right CORS policy, loading templates from a different domain
  11597. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  11598. * browsers.
  11599. *
  11600. * ## This feels like too much overhead for the developer?
  11601. *
  11602. * It's important to remember that SCE only applies to interpolation expressions.
  11603. *
  11604. * If your expressions are constant literals, they're automatically trusted and you don't need to
  11605. * call `$sce.trustAs` on them. (e.g.
  11606. * `<div ng-html-bind-unsafe="'<b>implicitly trusted</b>'"></div>`) just works.
  11607. *
  11608. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  11609. * through {@link ng.$sce#methods_getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  11610. *
  11611. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  11612. * templates in `ng-include` from your application's domain without having to even know about SCE.
  11613. * It blocks loading templates from other domains or loading templates over http from an https
  11614. * served document. You can change these by setting your own custom {@link
  11615. * ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelists} and {@link
  11616. * ng.$sceDelegateProvider#methods_resourceUrlBlacklist blacklists} for matching such URLs.
  11617. *
  11618. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  11619. * application that's secure and can be audited to verify that with much more ease than bolting
  11620. * security onto an application later.
  11621. *
  11622. * <a name="contexts"></a>
  11623. * ## What trusted context types are supported?
  11624. *
  11625. * | Context | Notes |
  11626. * |---------------------|----------------|
  11627. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. |
  11628. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  11629. * | `$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. |
  11630. * | `$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. |
  11631. * | `$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. |
  11632. *
  11633. * ## Format of items in {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  11634. *
  11635. * Each element in these arrays must be one of the following:
  11636. *
  11637. * - **'self'**
  11638. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  11639. * domain** as the application document using the **same protocol**.
  11640. * - **String** (except the special value `'self'`)
  11641. * - The string is matched against the full *normalized / absolute URL* of the resource
  11642. * being tested (substring matches are not good enough.)
  11643. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  11644. * match themselves.
  11645. * - `*`: matches zero or more occurances of any character other than one of the following 6
  11646. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  11647. * in a whitelist.
  11648. * - `**`: matches zero or more occurances of *any* character. As such, it's not
  11649. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  11650. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  11651. * not have been the intention.) It's usage at the very end of the path is ok. (e.g.
  11652. * http://foo.example.com/templates/**).
  11653. * - **RegExp** (*see caveat below*)
  11654. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  11655. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  11656. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  11657. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  11658. * small number of cases. A `.` character in the regex used when matching the scheme or a
  11659. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  11660. * is highly recommended to use the string patterns and only fall back to regular expressions
  11661. * if they as a last resort.
  11662. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  11663. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  11664. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  11665. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  11666. * - If you are generating your Javascript from some other templating engine (not
  11667. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  11668. * remember to escape your regular expression (and be aware that you might need more than
  11669. * one level of escaping depending on your templating engine and the way you interpolated
  11670. * the value.) Do make use of your platform's escaping mechanism as it might be good
  11671. * enough before coding your own. e.g. Ruby has
  11672. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  11673. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  11674. * Javascript lacks a similar built in function for escaping. Take a look at Google
  11675. * Closure library's [goog.string.regExpEscape(s)](
  11676. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  11677. *
  11678. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  11679. *
  11680. * ## Show me an example using SCE.
  11681. *
  11682. * @example
  11683. <example module="mySceApp">
  11684. <file name="index.html">
  11685. <div ng-controller="myAppController as myCtrl">
  11686. <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  11687. <b>User comments</b><br>
  11688. By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  11689. $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  11690. exploit.
  11691. <div class="well">
  11692. <div ng-repeat="userComment in myCtrl.userComments">
  11693. <b>{{userComment.name}}</b>:
  11694. <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  11695. <br>
  11696. </div>
  11697. </div>
  11698. </div>
  11699. </file>
  11700. <file name="script.js">
  11701. var mySceApp = angular.module('mySceApp', ['ngSanitize']);
  11702. mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  11703. var self = this;
  11704. $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  11705. self.userComments = userComments;
  11706. });
  11707. self.explicitlyTrustedHtml = $sce.trustAsHtml(
  11708. '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  11709. 'sanitization.&quot;">Hover over this text.</span>');
  11710. });
  11711. </file>
  11712. <file name="test_data.json">
  11713. [
  11714. { "name": "Alice",
  11715. "htmlComment":
  11716. "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  11717. },
  11718. { "name": "Bob",
  11719. "htmlComment": "<i>Yes!</i> Am I the only other one?"
  11720. }
  11721. ]
  11722. </file>
  11723. <file name="scenario.js">
  11724. describe('SCE doc demo', function() {
  11725. it('should sanitize untrusted values', function() {
  11726. expect(element('.htmlComment').html()).toBe('<span>Is <i>anyone</i> reading this?</span>');
  11727. });
  11728. it('should NOT sanitize explicitly trusted values', function() {
  11729. expect(element('#explicitlyTrustedHtml').html()).toBe(
  11730. '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  11731. 'sanitization.&quot;">Hover over this text.</span>');
  11732. });
  11733. });
  11734. </file>
  11735. </example>
  11736. *
  11737. *
  11738. *
  11739. * ## Can I disable SCE completely?
  11740. *
  11741. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  11742. * for little coding overhead. It will be much harder to take an SCE disabled application and
  11743. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  11744. * for cases where you have a lot of existing code that was written before SCE was introduced and
  11745. * you're migrating them a module at a time.
  11746. *
  11747. * That said, here's how you can completely disable SCE:
  11748. *
  11749. * <pre class="prettyprint">
  11750. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  11751. * // Completely disable SCE. For demonstration purposes only!
  11752. * // Do not use in new projects.
  11753. * $sceProvider.enabled(false);
  11754. * });
  11755. * </pre>
  11756. *
  11757. */
  11758. /* jshint maxlen: 100 */
  11759. function $SceProvider() {
  11760. var enabled = true;
  11761. /**
  11762. * @ngdoc function
  11763. * @name ng.sceProvider#enabled
  11764. * @methodOf ng.$sceProvider
  11765. * @function
  11766. *
  11767. * @param {boolean=} value If provided, then enables/disables SCE.
  11768. * @return {boolean} true if SCE is enabled, false otherwise.
  11769. *
  11770. * @description
  11771. * Enables/disables SCE and returns the current value.
  11772. */
  11773. this.enabled = function (value) {
  11774. if (arguments.length) {
  11775. enabled = !!value;
  11776. }
  11777. return enabled;
  11778. };
  11779. /* Design notes on the default implementation for SCE.
  11780. *
  11781. * The API contract for the SCE delegate
  11782. * -------------------------------------
  11783. * The SCE delegate object must provide the following 3 methods:
  11784. *
  11785. * - trustAs(contextEnum, value)
  11786. * This method is used to tell the SCE service that the provided value is OK to use in the
  11787. * contexts specified by contextEnum. It must return an object that will be accepted by
  11788. * getTrusted() for a compatible contextEnum and return this value.
  11789. *
  11790. * - valueOf(value)
  11791. * For values that were not produced by trustAs(), return them as is. For values that were
  11792. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  11793. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  11794. * such a value.
  11795. *
  11796. * - getTrusted(contextEnum, value)
  11797. * This function should return the a value that is safe to use in the context specified by
  11798. * contextEnum or throw and exception otherwise.
  11799. *
  11800. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  11801. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  11802. * instance, an implementation could maintain a registry of all trusted objects by context. In
  11803. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  11804. * return the same object passed in if it was found in the registry under a compatible context or
  11805. * throw an exception otherwise. An implementation might only wrap values some of the time based
  11806. * on some criteria. getTrusted() might return a value and not throw an exception for special
  11807. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  11808. *
  11809. *
  11810. * A note on the inheritance model for SCE contexts
  11811. * ------------------------------------------------
  11812. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  11813. * is purely an implementation details.
  11814. *
  11815. * The contract is simply this:
  11816. *
  11817. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  11818. * will also succeed.
  11819. *
  11820. * Inheritance happens to capture this in a natural way. In some future, we
  11821. * may not use inheritance anymore. That is OK because no code outside of
  11822. * sce.js and sceSpecs.js would need to be aware of this detail.
  11823. */
  11824. this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
  11825. $parse, $sniffer, $sceDelegate) {
  11826. // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
  11827. // the "expression(javascript expression)" syntax which is insecure.
  11828. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
  11829. throw $sceMinErr('iequirks',
  11830. 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
  11831. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  11832. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  11833. }
  11834. var sce = copy(SCE_CONTEXTS);
  11835. /**
  11836. * @ngdoc function
  11837. * @name ng.sce#isEnabled
  11838. * @methodOf ng.$sce
  11839. * @function
  11840. *
  11841. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  11842. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  11843. *
  11844. * @description
  11845. * Returns a boolean indicating if SCE is enabled.
  11846. */
  11847. sce.isEnabled = function () {
  11848. return enabled;
  11849. };
  11850. sce.trustAs = $sceDelegate.trustAs;
  11851. sce.getTrusted = $sceDelegate.getTrusted;
  11852. sce.valueOf = $sceDelegate.valueOf;
  11853. if (!enabled) {
  11854. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  11855. sce.valueOf = identity;
  11856. }
  11857. /**
  11858. * @ngdoc method
  11859. * @name ng.$sce#parse
  11860. * @methodOf ng.$sce
  11861. *
  11862. * @description
  11863. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  11864. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  11865. * wraps the expression in a call to {@link ng.$sce#methods_getTrusted $sce.getTrusted(*type*,
  11866. * *result*)}
  11867. *
  11868. * @param {string} type The kind of SCE context in which this result will be used.
  11869. * @param {string} expression String expression to compile.
  11870. * @returns {function(context, locals)} a function which represents the compiled expression:
  11871. *
  11872. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11873. * are evaluated against (typically a scope object).
  11874. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11875. * `context`.
  11876. */
  11877. sce.parseAs = function sceParseAs(type, expr) {
  11878. var parsed = $parse(expr);
  11879. if (parsed.literal && parsed.constant) {
  11880. return parsed;
  11881. } else {
  11882. return function sceParseAsTrusted(self, locals) {
  11883. return sce.getTrusted(type, parsed(self, locals));
  11884. };
  11885. }
  11886. };
  11887. /**
  11888. * @ngdoc method
  11889. * @name ng.$sce#trustAs
  11890. * @methodOf ng.$sce
  11891. *
  11892. * @description
  11893. * Delegates to {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}. As such,
  11894. * returns an objectthat is trusted by angular for use in specified strict contextual
  11895. * escaping contexts (such as ng-html-bind-unsafe, ng-include, any src attribute
  11896. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  11897. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  11898. * escaping.
  11899. *
  11900. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  11901. * resource_url, html, js and css.
  11902. * @param {*} value The value that that should be considered trusted/safe.
  11903. * @returns {*} A value that can be used to stand in for the provided `value` in places
  11904. * where Angular expects a $sce.trustAs() return value.
  11905. */
  11906. /**
  11907. * @ngdoc method
  11908. * @name ng.$sce#trustAsHtml
  11909. * @methodOf ng.$sce
  11910. *
  11911. * @description
  11912. * Shorthand method. `$sce.trustAsHtml(value)` →
  11913. * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  11914. *
  11915. * @param {*} value The value to trustAs.
  11916. * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedHtml
  11917. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  11918. * only accept expressions that are either literal constants or are the
  11919. * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
  11920. */
  11921. /**
  11922. * @ngdoc method
  11923. * @name ng.$sce#trustAsUrl
  11924. * @methodOf ng.$sce
  11925. *
  11926. * @description
  11927. * Shorthand method. `$sce.trustAsUrl(value)` →
  11928. * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  11929. *
  11930. * @param {*} value The value to trustAs.
  11931. * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedUrl
  11932. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  11933. * only accept expressions that are either literal constants or are the
  11934. * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
  11935. */
  11936. /**
  11937. * @ngdoc method
  11938. * @name ng.$sce#trustAsResourceUrl
  11939. * @methodOf ng.$sce
  11940. *
  11941. * @description
  11942. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  11943. * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  11944. *
  11945. * @param {*} value The value to trustAs.
  11946. * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedResourceUrl
  11947. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  11948. * only accept expressions that are either literal constants or are the return
  11949. * value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
  11950. */
  11951. /**
  11952. * @ngdoc method
  11953. * @name ng.$sce#trustAsJs
  11954. * @methodOf ng.$sce
  11955. *
  11956. * @description
  11957. * Shorthand method. `$sce.trustAsJs(value)` →
  11958. * {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  11959. *
  11960. * @param {*} value The value to trustAs.
  11961. * @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedJs
  11962. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  11963. * only accept expressions that are either literal constants or are the
  11964. * return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
  11965. */
  11966. /**
  11967. * @ngdoc method
  11968. * @name ng.$sce#getTrusted
  11969. * @methodOf ng.$sce
  11970. *
  11971. * @description
  11972. * Delegates to {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted`}. As such,
  11973. * takes the result of a {@link ng.$sce#methods_trustAs `$sce.trustAs`}() call and returns the
  11974. * originally supplied value if the queried context type is a supertype of the created type.
  11975. * If this condition isn't satisfied, throws an exception.
  11976. *
  11977. * @param {string} type The kind of context in which this value is to be used.
  11978. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#methods_trustAs `$sce.trustAs`}
  11979. * call.
  11980. * @returns {*} The value the was originally provided to
  11981. * {@link ng.$sce#methods_trustAs `$sce.trustAs`} if valid in this context.
  11982. * Otherwise, throws an exception.
  11983. */
  11984. /**
  11985. * @ngdoc method
  11986. * @name ng.$sce#getTrustedHtml
  11987. * @methodOf ng.$sce
  11988. *
  11989. * @description
  11990. * Shorthand method. `$sce.getTrustedHtml(value)` →
  11991. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  11992. *
  11993. * @param {*} value The value to pass to `$sce.getTrusted`.
  11994. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  11995. */
  11996. /**
  11997. * @ngdoc method
  11998. * @name ng.$sce#getTrustedCss
  11999. * @methodOf ng.$sce
  12000. *
  12001. * @description
  12002. * Shorthand method. `$sce.getTrustedCss(value)` →
  12003. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  12004. *
  12005. * @param {*} value The value to pass to `$sce.getTrusted`.
  12006. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  12007. */
  12008. /**
  12009. * @ngdoc method
  12010. * @name ng.$sce#getTrustedUrl
  12011. * @methodOf ng.$sce
  12012. *
  12013. * @description
  12014. * Shorthand method. `$sce.getTrustedUrl(value)` →
  12015. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  12016. *
  12017. * @param {*} value The value to pass to `$sce.getTrusted`.
  12018. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  12019. */
  12020. /**
  12021. * @ngdoc method
  12022. * @name ng.$sce#getTrustedResourceUrl
  12023. * @methodOf ng.$sce
  12024. *
  12025. * @description
  12026. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  12027. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  12028. *
  12029. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  12030. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  12031. */
  12032. /**
  12033. * @ngdoc method
  12034. * @name ng.$sce#getTrustedJs
  12035. * @methodOf ng.$sce
  12036. *
  12037. * @description
  12038. * Shorthand method. `$sce.getTrustedJs(value)` →
  12039. * {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  12040. *
  12041. * @param {*} value The value to pass to `$sce.getTrusted`.
  12042. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  12043. */
  12044. /**
  12045. * @ngdoc method
  12046. * @name ng.$sce#parseAsHtml
  12047. * @methodOf ng.$sce
  12048. *
  12049. * @description
  12050. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  12051. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.HTML, value)`}
  12052. *
  12053. * @param {string} expression String expression to compile.
  12054. * @returns {function(context, locals)} a function which represents the compiled expression:
  12055. *
  12056. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12057. * are evaluated against (typically a scope object).
  12058. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12059. * `context`.
  12060. */
  12061. /**
  12062. * @ngdoc method
  12063. * @name ng.$sce#parseAsCss
  12064. * @methodOf ng.$sce
  12065. *
  12066. * @description
  12067. * Shorthand method. `$sce.parseAsCss(value)` →
  12068. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.CSS, value)`}
  12069. *
  12070. * @param {string} expression String expression to compile.
  12071. * @returns {function(context, locals)} a function which represents the compiled expression:
  12072. *
  12073. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12074. * are evaluated against (typically a scope object).
  12075. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12076. * `context`.
  12077. */
  12078. /**
  12079. * @ngdoc method
  12080. * @name ng.$sce#parseAsUrl
  12081. * @methodOf ng.$sce
  12082. *
  12083. * @description
  12084. * Shorthand method. `$sce.parseAsUrl(value)` →
  12085. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.URL, value)`}
  12086. *
  12087. * @param {string} expression String expression to compile.
  12088. * @returns {function(context, locals)} a function which represents the compiled expression:
  12089. *
  12090. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12091. * are evaluated against (typically a scope object).
  12092. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12093. * `context`.
  12094. */
  12095. /**
  12096. * @ngdoc method
  12097. * @name ng.$sce#parseAsResourceUrl
  12098. * @methodOf ng.$sce
  12099. *
  12100. * @description
  12101. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  12102. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
  12103. *
  12104. * @param {string} expression String expression to compile.
  12105. * @returns {function(context, locals)} a function which represents the compiled expression:
  12106. *
  12107. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12108. * are evaluated against (typically a scope object).
  12109. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12110. * `context`.
  12111. */
  12112. /**
  12113. * @ngdoc method
  12114. * @name ng.$sce#parseAsJs
  12115. * @methodOf ng.$sce
  12116. *
  12117. * @description
  12118. * Shorthand method. `$sce.parseAsJs(value)` →
  12119. * {@link ng.$sce#methods_parse `$sce.parseAs($sce.JS, value)`}
  12120. *
  12121. * @param {string} expression String expression to compile.
  12122. * @returns {function(context, locals)} a function which represents the compiled expression:
  12123. *
  12124. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12125. * are evaluated against (typically a scope object).
  12126. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12127. * `context`.
  12128. */
  12129. // Shorthand delegations.
  12130. var parse = sce.parseAs,
  12131. getTrusted = sce.getTrusted,
  12132. trustAs = sce.trustAs;
  12133. forEach(SCE_CONTEXTS, function (enumValue, name) {
  12134. var lName = lowercase(name);
  12135. sce[camelCase("parse_as_" + lName)] = function (expr) {
  12136. return parse(enumValue, expr);
  12137. };
  12138. sce[camelCase("get_trusted_" + lName)] = function (value) {
  12139. return getTrusted(enumValue, value);
  12140. };
  12141. sce[camelCase("trust_as_" + lName)] = function (value) {
  12142. return trustAs(enumValue, value);
  12143. };
  12144. });
  12145. return sce;
  12146. }];
  12147. }
  12148. /**
  12149. * !!! This is an undocumented "private" service !!!
  12150. *
  12151. * @name ng.$sniffer
  12152. * @requires $window
  12153. * @requires $document
  12154. *
  12155. * @property {boolean} history Does the browser support html5 history api ?
  12156. * @property {boolean} hashchange Does the browser support hashchange event ?
  12157. * @property {boolean} transitions Does the browser support CSS transition events ?
  12158. * @property {boolean} animations Does the browser support CSS animation events ?
  12159. *
  12160. * @description
  12161. * This is very simple implementation of testing browser's features.
  12162. */
  12163. function $SnifferProvider() {
  12164. this.$get = ['$window', '$document', function($window, $document) {
  12165. var eventSupport = {},
  12166. android =
  12167. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  12168. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  12169. document = $document[0] || {},
  12170. documentMode = document.documentMode,
  12171. vendorPrefix,
  12172. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  12173. bodyStyle = document.body && document.body.style,
  12174. transitions = false,
  12175. animations = false,
  12176. match;
  12177. if (bodyStyle) {
  12178. for(var prop in bodyStyle) {
  12179. if(match = vendorRegex.exec(prop)) {
  12180. vendorPrefix = match[0];
  12181. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  12182. break;
  12183. }
  12184. }
  12185. if(!vendorPrefix) {
  12186. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  12187. }
  12188. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  12189. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  12190. if (android && (!transitions||!animations)) {
  12191. transitions = isString(document.body.style.webkitTransition);
  12192. animations = isString(document.body.style.webkitAnimation);
  12193. }
  12194. }
  12195. return {
  12196. // Android has history.pushState, but it does not update location correctly
  12197. // so let's not use the history API at all.
  12198. // http://code.google.com/p/android/issues/detail?id=17471
  12199. // https://github.com/angular/angular.js/issues/904
  12200. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  12201. // so let's not use the history API also
  12202. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  12203. // jshint -W018
  12204. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  12205. // jshint +W018
  12206. hashchange: 'onhashchange' in $window &&
  12207. // IE8 compatible mode lies
  12208. (!documentMode || documentMode > 7),
  12209. hasEvent: function(event) {
  12210. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  12211. // it. In particular the event is not fired when backspace or delete key are pressed or
  12212. // when cut operation is performed.
  12213. if (event == 'input' && msie == 9) return false;
  12214. if (isUndefined(eventSupport[event])) {
  12215. var divElm = document.createElement('div');
  12216. eventSupport[event] = 'on' + event in divElm;
  12217. }
  12218. return eventSupport[event];
  12219. },
  12220. csp: csp(),
  12221. vendorPrefix: vendorPrefix,
  12222. transitions : transitions,
  12223. animations : animations,
  12224. android: android,
  12225. msie : msie,
  12226. msieDocumentMode: documentMode
  12227. };
  12228. }];
  12229. }
  12230. function $TimeoutProvider() {
  12231. this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
  12232. function($rootScope, $browser, $q, $exceptionHandler) {
  12233. var deferreds = {};
  12234. /**
  12235. * @ngdoc function
  12236. * @name ng.$timeout
  12237. * @requires $browser
  12238. *
  12239. * @description
  12240. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  12241. * block and delegates any exceptions to
  12242. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12243. *
  12244. * The return value of registering a timeout function is a promise, which will be resolved when
  12245. * the timeout is reached and the timeout function is executed.
  12246. *
  12247. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  12248. *
  12249. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  12250. * synchronously flush the queue of deferred functions.
  12251. *
  12252. * @param {function()} fn A function, whose execution should be delayed.
  12253. * @param {number=} [delay=0] Delay in milliseconds.
  12254. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12255. * will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
  12256. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  12257. * promise will be resolved with is the return value of the `fn` function.
  12258. *
  12259. */
  12260. function timeout(fn, delay, invokeApply) {
  12261. var deferred = $q.defer(),
  12262. promise = deferred.promise,
  12263. skipApply = (isDefined(invokeApply) && !invokeApply),
  12264. timeoutId;
  12265. timeoutId = $browser.defer(function() {
  12266. try {
  12267. deferred.resolve(fn());
  12268. } catch(e) {
  12269. deferred.reject(e);
  12270. $exceptionHandler(e);
  12271. }
  12272. finally {
  12273. delete deferreds[promise.$$timeoutId];
  12274. }
  12275. if (!skipApply) $rootScope.$apply();
  12276. }, delay);
  12277. promise.$$timeoutId = timeoutId;
  12278. deferreds[timeoutId] = deferred;
  12279. return promise;
  12280. }
  12281. /**
  12282. * @ngdoc function
  12283. * @name ng.$timeout#cancel
  12284. * @methodOf ng.$timeout
  12285. *
  12286. * @description
  12287. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  12288. * resolved with a rejection.
  12289. *
  12290. * @param {Promise=} promise Promise returned by the `$timeout` function.
  12291. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  12292. * canceled.
  12293. */
  12294. timeout.cancel = function(promise) {
  12295. if (promise && promise.$$timeoutId in deferreds) {
  12296. deferreds[promise.$$timeoutId].reject('canceled');
  12297. delete deferreds[promise.$$timeoutId];
  12298. return $browser.defer.cancel(promise.$$timeoutId);
  12299. }
  12300. return false;
  12301. };
  12302. return timeout;
  12303. }];
  12304. }
  12305. // NOTE: The usage of window and document instead of $window and $document here is
  12306. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  12307. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  12308. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  12309. // doesn't know about mocked locations and resolves URLs to the real document - which is
  12310. // exactly the behavior needed here. There is little value is mocking these out for this
  12311. // service.
  12312. var urlParsingNode = document.createElement("a");
  12313. var originUrl = urlResolve(window.location.href, true);
  12314. /**
  12315. *
  12316. * Implementation Notes for non-IE browsers
  12317. * ----------------------------------------
  12318. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  12319. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  12320. * URL will be resolved into an absolute URL in the context of the application document.
  12321. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  12322. * properties are all populated to reflect the normalized URL. This approach has wide
  12323. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  12324. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12325. *
  12326. * Implementation Notes for IE
  12327. * ---------------------------
  12328. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  12329. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  12330. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  12331. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  12332. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  12333. * properties such as protocol, hostname, port, etc.
  12334. *
  12335. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  12336. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  12337. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  12338. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  12339. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  12340. * method and IE < 8 is unsupported.
  12341. *
  12342. * References:
  12343. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  12344. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12345. * http://url.spec.whatwg.org/#urlutils
  12346. * https://github.com/angular/angular.js/pull/2902
  12347. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  12348. *
  12349. * @function
  12350. * @param {string} url The URL to be parsed.
  12351. * @description Normalizes and parses a URL.
  12352. * @returns {object} Returns the normalized URL as a dictionary.
  12353. *
  12354. * | member name | Description |
  12355. * |---------------|----------------|
  12356. * | href | A normalized version of the provided URL if it was not an absolute URL |
  12357. * | protocol | The protocol including the trailing colon |
  12358. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  12359. * | search | The search params, minus the question mark |
  12360. * | hash | The hash string, minus the hash symbol
  12361. * | hostname | The hostname
  12362. * | port | The port, without ":"
  12363. * | pathname | The pathname, beginning with "/"
  12364. *
  12365. */
  12366. function urlResolve(url, base) {
  12367. var href = url;
  12368. if (msie) {
  12369. // Normalize before parse. Refer Implementation Notes on why this is
  12370. // done in two steps on IE.
  12371. urlParsingNode.setAttribute("href", href);
  12372. href = urlParsingNode.href;
  12373. }
  12374. urlParsingNode.setAttribute('href', href);
  12375. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  12376. return {
  12377. href: urlParsingNode.href,
  12378. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  12379. host: urlParsingNode.host,
  12380. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  12381. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  12382. hostname: urlParsingNode.hostname,
  12383. port: urlParsingNode.port,
  12384. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  12385. ? urlParsingNode.pathname
  12386. : '/' + urlParsingNode.pathname
  12387. };
  12388. }
  12389. /**
  12390. * Parse a request URL and determine whether this is a same-origin request as the application document.
  12391. *
  12392. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  12393. * or a parsed URL object.
  12394. * @returns {boolean} Whether the request is for the same origin as the application document.
  12395. */
  12396. function urlIsSameOrigin(requestUrl) {
  12397. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  12398. return (parsed.protocol === originUrl.protocol &&
  12399. parsed.host === originUrl.host);
  12400. }
  12401. /**
  12402. * @ngdoc object
  12403. * @name ng.$window
  12404. *
  12405. * @description
  12406. * A reference to the browser's `window` object. While `window`
  12407. * is globally available in JavaScript, it causes testability problems, because
  12408. * it is a global variable. In angular we always refer to it through the
  12409. * `$window` service, so it may be overridden, removed or mocked for testing.
  12410. *
  12411. * Expressions, like the one defined for the `ngClick` directive in the example
  12412. * below, are evaluated with respect to the current scope. Therefore, there is
  12413. * no risk of inadvertently coding in a dependency on a global value in such an
  12414. * expression.
  12415. *
  12416. * @example
  12417. <doc:example>
  12418. <doc:source>
  12419. <script>
  12420. function Ctrl($scope, $window) {
  12421. $scope.greeting = 'Hello, World!';
  12422. $scope.doGreeting = function(greeting) {
  12423. $window.alert(greeting);
  12424. };
  12425. }
  12426. </script>
  12427. <div ng-controller="Ctrl">
  12428. <input type="text" ng-model="greeting" />
  12429. <button ng-click="doGreeting(greeting)">ALERT</button>
  12430. </div>
  12431. </doc:source>
  12432. <doc:scenario>
  12433. it('should display the greeting in the input box', function() {
  12434. input('greeting').enter('Hello, E2E Tests');
  12435. // If we click the button it will block the test runner
  12436. // element(':button').click();
  12437. });
  12438. </doc:scenario>
  12439. </doc:example>
  12440. */
  12441. function $WindowProvider(){
  12442. this.$get = valueFn(window);
  12443. }
  12444. /**
  12445. * @ngdoc object
  12446. * @name ng.$filterProvider
  12447. * @description
  12448. *
  12449. * Filters are just functions which transform input to an output. However filters need to be
  12450. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  12451. * annotated with dependencies and is responsible for creating a filter function.
  12452. *
  12453. * <pre>
  12454. * // Filter registration
  12455. * function MyModule($provide, $filterProvider) {
  12456. * // create a service to demonstrate injection (not always needed)
  12457. * $provide.value('greet', function(name){
  12458. * return 'Hello ' + name + '!';
  12459. * });
  12460. *
  12461. * // register a filter factory which uses the
  12462. * // greet service to demonstrate DI.
  12463. * $filterProvider.register('greet', function(greet){
  12464. * // return the filter function which uses the greet service
  12465. * // to generate salutation
  12466. * return function(text) {
  12467. * // filters need to be forgiving so check input validity
  12468. * return text && greet(text) || text;
  12469. * };
  12470. * });
  12471. * }
  12472. * </pre>
  12473. *
  12474. * The filter function is registered with the `$injector` under the filter name suffix with
  12475. * `Filter`.
  12476. *
  12477. * <pre>
  12478. * it('should be the same instance', inject(
  12479. * function($filterProvider) {
  12480. * $filterProvider.register('reverse', function(){
  12481. * return ...;
  12482. * });
  12483. * },
  12484. * function($filter, reverseFilter) {
  12485. * expect($filter('reverse')).toBe(reverseFilter);
  12486. * });
  12487. * </pre>
  12488. *
  12489. *
  12490. * For more information about how angular filters work, and how to create your own filters, see
  12491. * {@link guide/filter Filters} in the Angular Developer Guide.
  12492. */
  12493. /**
  12494. * @ngdoc method
  12495. * @name ng.$filterProvider#register
  12496. * @methodOf ng.$filterProvider
  12497. * @description
  12498. * Register filter factory function.
  12499. *
  12500. * @param {String} name Name of the filter.
  12501. * @param {function} fn The filter factory function which is injectable.
  12502. */
  12503. /**
  12504. * @ngdoc function
  12505. * @name ng.$filter
  12506. * @function
  12507. * @description
  12508. * Filters are used for formatting data displayed to the user.
  12509. *
  12510. * The general syntax in templates is as follows:
  12511. *
  12512. * {{ expression [| filter_name[:parameter_value] ... ] }}
  12513. *
  12514. * @param {String} name Name of the filter function to retrieve
  12515. * @return {Function} the filter function
  12516. */
  12517. $FilterProvider.$inject = ['$provide'];
  12518. function $FilterProvider($provide) {
  12519. var suffix = 'Filter';
  12520. /**
  12521. * @ngdoc function
  12522. * @name ng.$controllerProvider#register
  12523. * @methodOf ng.$controllerProvider
  12524. * @param {string|Object} name Name of the filter function, or an object map of filters where
  12525. * the keys are the filter names and the values are the filter factories.
  12526. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  12527. * of the registered filter instances.
  12528. */
  12529. function register(name, factory) {
  12530. if(isObject(name)) {
  12531. var filters = {};
  12532. forEach(name, function(filter, key) {
  12533. filters[key] = register(key, filter);
  12534. });
  12535. return filters;
  12536. } else {
  12537. return $provide.factory(name + suffix, factory);
  12538. }
  12539. }
  12540. this.register = register;
  12541. this.$get = ['$injector', function($injector) {
  12542. return function(name) {
  12543. return $injector.get(name + suffix);
  12544. };
  12545. }];
  12546. ////////////////////////////////////////
  12547. /* global
  12548. currencyFilter: false,
  12549. dateFilter: false,
  12550. filterFilter: false,
  12551. jsonFilter: false,
  12552. limitToFilter: false,
  12553. lowercaseFilter: false,
  12554. numberFilter: false,
  12555. orderByFilter: false,
  12556. uppercaseFilter: false,
  12557. */
  12558. register('currency', currencyFilter);
  12559. register('date', dateFilter);
  12560. register('filter', filterFilter);
  12561. register('json', jsonFilter);
  12562. register('limitTo', limitToFilter);
  12563. register('lowercase', lowercaseFilter);
  12564. register('number', numberFilter);
  12565. register('orderBy', orderByFilter);
  12566. register('uppercase', uppercaseFilter);
  12567. }
  12568. /**
  12569. * @ngdoc filter
  12570. * @name ng.filter:filter
  12571. * @function
  12572. *
  12573. * @description
  12574. * Selects a subset of items from `array` and returns it as a new array.
  12575. *
  12576. * @param {Array} array The source array.
  12577. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  12578. * `array`.
  12579. *
  12580. * Can be one of:
  12581. *
  12582. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  12583. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  12584. * will be returned. The predicate can be negated by prefixing the string with `!`.
  12585. *
  12586. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  12587. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  12588. * which have property `name` containing "M" and property `phone` containing "1". A special
  12589. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  12590. * property of the object. That's equivalent to the simple substring match with a `string`
  12591. * as described above.
  12592. *
  12593. * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
  12594. * called for each element of `array`. The final result is an array of those elements that
  12595. * the predicate returned true for.
  12596. *
  12597. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  12598. * determining if the expected value (from the filter expression) and actual value (from
  12599. * the object in the array) should be considered a match.
  12600. *
  12601. * Can be one of:
  12602. *
  12603. * - `function(actual, expected)`:
  12604. * The function will be given the object value and the predicate value to compare and
  12605. * should return true if the item should be included in filtered result.
  12606. *
  12607. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  12608. * this is essentially strict comparison of expected and actual.
  12609. *
  12610. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  12611. * insensitive way.
  12612. *
  12613. * @example
  12614. <doc:example>
  12615. <doc:source>
  12616. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  12617. {name:'Mary', phone:'800-BIG-MARY'},
  12618. {name:'Mike', phone:'555-4321'},
  12619. {name:'Adam', phone:'555-5678'},
  12620. {name:'Julie', phone:'555-8765'},
  12621. {name:'Juliette', phone:'555-5678'}]"></div>
  12622. Search: <input ng-model="searchText">
  12623. <table id="searchTextResults">
  12624. <tr><th>Name</th><th>Phone</th></tr>
  12625. <tr ng-repeat="friend in friends | filter:searchText">
  12626. <td>{{friend.name}}</td>
  12627. <td>{{friend.phone}}</td>
  12628. </tr>
  12629. </table>
  12630. <hr>
  12631. Any: <input ng-model="search.$"> <br>
  12632. Name only <input ng-model="search.name"><br>
  12633. Phone only <input ng-model="search.phone"><br>
  12634. Equality <input type="checkbox" ng-model="strict"><br>
  12635. <table id="searchObjResults">
  12636. <tr><th>Name</th><th>Phone</th></tr>
  12637. <tr ng-repeat="friend in friends | filter:search:strict">
  12638. <td>{{friend.name}}</td>
  12639. <td>{{friend.phone}}</td>
  12640. </tr>
  12641. </table>
  12642. </doc:source>
  12643. <doc:scenario>
  12644. it('should search across all fields when filtering with a string', function() {
  12645. input('searchText').enter('m');
  12646. expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
  12647. toEqual(['Mary', 'Mike', 'Adam']);
  12648. input('searchText').enter('76');
  12649. expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
  12650. toEqual(['John', 'Julie']);
  12651. });
  12652. it('should search in specific fields when filtering with a predicate object', function() {
  12653. input('search.$').enter('i');
  12654. expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
  12655. toEqual(['Mary', 'Mike', 'Julie', 'Juliette']);
  12656. });
  12657. it('should use a equal comparison when comparator is true', function() {
  12658. input('search.name').enter('Julie');
  12659. input('strict').check();
  12660. expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
  12661. toEqual(['Julie']);
  12662. });
  12663. </doc:scenario>
  12664. </doc:example>
  12665. */
  12666. function filterFilter() {
  12667. return function(array, expression, comparator) {
  12668. if (!isArray(array)) return array;
  12669. var comparatorType = typeof(comparator),
  12670. predicates = [];
  12671. predicates.check = function(value) {
  12672. for (var j = 0; j < predicates.length; j++) {
  12673. if(!predicates[j](value)) {
  12674. return false;
  12675. }
  12676. }
  12677. return true;
  12678. };
  12679. if (comparatorType !== 'function') {
  12680. if (comparatorType === 'boolean' && comparator) {
  12681. comparator = function(obj, text) {
  12682. return angular.equals(obj, text);
  12683. };
  12684. } else {
  12685. comparator = function(obj, text) {
  12686. text = (''+text).toLowerCase();
  12687. return (''+obj).toLowerCase().indexOf(text) > -1;
  12688. };
  12689. }
  12690. }
  12691. var search = function(obj, text){
  12692. if (typeof text == 'string' && text.charAt(0) === '!') {
  12693. return !search(obj, text.substr(1));
  12694. }
  12695. switch (typeof obj) {
  12696. case "boolean":
  12697. case "number":
  12698. case "string":
  12699. return comparator(obj, text);
  12700. case "object":
  12701. switch (typeof text) {
  12702. case "object":
  12703. return comparator(obj, text);
  12704. default:
  12705. for ( var objKey in obj) {
  12706. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  12707. return true;
  12708. }
  12709. }
  12710. break;
  12711. }
  12712. return false;
  12713. case "array":
  12714. for ( var i = 0; i < obj.length; i++) {
  12715. if (search(obj[i], text)) {
  12716. return true;
  12717. }
  12718. }
  12719. return false;
  12720. default:
  12721. return false;
  12722. }
  12723. };
  12724. switch (typeof expression) {
  12725. case "boolean":
  12726. case "number":
  12727. case "string":
  12728. // Set up expression object and fall through
  12729. expression = {$:expression};
  12730. // jshint -W086
  12731. case "object":
  12732. // jshint +W086
  12733. for (var key in expression) {
  12734. (function(path) {
  12735. if (typeof expression[path] == 'undefined') return;
  12736. predicates.push(function(value) {
  12737. return search(path == '$' ? value : getter(value, path), expression[path]);
  12738. });
  12739. })(key);
  12740. }
  12741. break;
  12742. case 'function':
  12743. predicates.push(expression);
  12744. break;
  12745. default:
  12746. return array;
  12747. }
  12748. var filtered = [];
  12749. for ( var j = 0; j < array.length; j++) {
  12750. var value = array[j];
  12751. if (predicates.check(value)) {
  12752. filtered.push(value);
  12753. }
  12754. }
  12755. return filtered;
  12756. };
  12757. }
  12758. /**
  12759. * @ngdoc filter
  12760. * @name ng.filter:currency
  12761. * @function
  12762. *
  12763. * @description
  12764. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  12765. * symbol for current locale is used.
  12766. *
  12767. * @param {number} amount Input to filter.
  12768. * @param {string=} symbol Currency symbol or identifier to be displayed.
  12769. * @returns {string} Formatted number.
  12770. *
  12771. *
  12772. * @example
  12773. <doc:example>
  12774. <doc:source>
  12775. <script>
  12776. function Ctrl($scope) {
  12777. $scope.amount = 1234.56;
  12778. }
  12779. </script>
  12780. <div ng-controller="Ctrl">
  12781. <input type="number" ng-model="amount"> <br>
  12782. default currency symbol ($): {{amount | currency}}<br>
  12783. custom currency identifier (USD$): {{amount | currency:"USD$"}}
  12784. </div>
  12785. </doc:source>
  12786. <doc:scenario>
  12787. it('should init with 1234.56', function() {
  12788. expect(binding('amount | currency')).toBe('$1,234.56');
  12789. expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
  12790. });
  12791. it('should update', function() {
  12792. input('amount').enter('-1234');
  12793. expect(binding('amount | currency')).toBe('($1,234.00)');
  12794. expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
  12795. });
  12796. </doc:scenario>
  12797. </doc:example>
  12798. */
  12799. currencyFilter.$inject = ['$locale'];
  12800. function currencyFilter($locale) {
  12801. var formats = $locale.NUMBER_FORMATS;
  12802. return function(amount, currencySymbol){
  12803. if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
  12804. return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
  12805. replace(/\u00A4/g, currencySymbol);
  12806. };
  12807. }
  12808. /**
  12809. * @ngdoc filter
  12810. * @name ng.filter:number
  12811. * @function
  12812. *
  12813. * @description
  12814. * Formats a number as text.
  12815. *
  12816. * If the input is not a number an empty string is returned.
  12817. *
  12818. * @param {number|string} number Number to format.
  12819. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  12820. * If this is not provided then the fraction size is computed from the current locale's number
  12821. * formatting pattern. In the case of the default locale, it will be 3.
  12822. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  12823. *
  12824. * @example
  12825. <doc:example>
  12826. <doc:source>
  12827. <script>
  12828. function Ctrl($scope) {
  12829. $scope.val = 1234.56789;
  12830. }
  12831. </script>
  12832. <div ng-controller="Ctrl">
  12833. Enter number: <input ng-model='val'><br>
  12834. Default formatting: {{val | number}}<br>
  12835. No fractions: {{val | number:0}}<br>
  12836. Negative number: {{-val | number:4}}
  12837. </div>
  12838. </doc:source>
  12839. <doc:scenario>
  12840. it('should format numbers', function() {
  12841. expect(binding('val | number')).toBe('1,234.568');
  12842. expect(binding('val | number:0')).toBe('1,235');
  12843. expect(binding('-val | number:4')).toBe('-1,234.5679');
  12844. });
  12845. it('should update', function() {
  12846. input('val').enter('3374.333');
  12847. expect(binding('val | number')).toBe('3,374.333');
  12848. expect(binding('val | number:0')).toBe('3,374');
  12849. expect(binding('-val | number:4')).toBe('-3,374.3330');
  12850. });
  12851. </doc:scenario>
  12852. </doc:example>
  12853. */
  12854. numberFilter.$inject = ['$locale'];
  12855. function numberFilter($locale) {
  12856. var formats = $locale.NUMBER_FORMATS;
  12857. return function(number, fractionSize) {
  12858. return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  12859. fractionSize);
  12860. };
  12861. }
  12862. var DECIMAL_SEP = '.';
  12863. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  12864. if (isNaN(number) || !isFinite(number)) return '';
  12865. var isNegative = number < 0;
  12866. number = Math.abs(number);
  12867. var numStr = number + '',
  12868. formatedText = '',
  12869. parts = [];
  12870. var hasExponent = false;
  12871. if (numStr.indexOf('e') !== -1) {
  12872. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  12873. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  12874. numStr = '0';
  12875. } else {
  12876. formatedText = numStr;
  12877. hasExponent = true;
  12878. }
  12879. }
  12880. if (!hasExponent) {
  12881. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  12882. // determine fractionSize if it is not specified
  12883. if (isUndefined(fractionSize)) {
  12884. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  12885. }
  12886. var pow = Math.pow(10, fractionSize);
  12887. number = Math.round(number * pow) / pow;
  12888. var fraction = ('' + number).split(DECIMAL_SEP);
  12889. var whole = fraction[0];
  12890. fraction = fraction[1] || '';
  12891. var i, pos = 0,
  12892. lgroup = pattern.lgSize,
  12893. group = pattern.gSize;
  12894. if (whole.length >= (lgroup + group)) {
  12895. pos = whole.length - lgroup;
  12896. for (i = 0; i < pos; i++) {
  12897. if ((pos - i)%group === 0 && i !== 0) {
  12898. formatedText += groupSep;
  12899. }
  12900. formatedText += whole.charAt(i);
  12901. }
  12902. }
  12903. for (i = pos; i < whole.length; i++) {
  12904. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  12905. formatedText += groupSep;
  12906. }
  12907. formatedText += whole.charAt(i);
  12908. }
  12909. // format fraction part.
  12910. while(fraction.length < fractionSize) {
  12911. fraction += '0';
  12912. }
  12913. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  12914. } else {
  12915. if (fractionSize > 0 && number > -1 && number < 1) {
  12916. formatedText = number.toFixed(fractionSize);
  12917. }
  12918. }
  12919. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  12920. parts.push(formatedText);
  12921. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  12922. return parts.join('');
  12923. }
  12924. function padNumber(num, digits, trim) {
  12925. var neg = '';
  12926. if (num < 0) {
  12927. neg = '-';
  12928. num = -num;
  12929. }
  12930. num = '' + num;
  12931. while(num.length < digits) num = '0' + num;
  12932. if (trim)
  12933. num = num.substr(num.length - digits);
  12934. return neg + num;
  12935. }
  12936. function dateGetter(name, size, offset, trim) {
  12937. offset = offset || 0;
  12938. return function(date) {
  12939. var value = date['get' + name]();
  12940. if (offset > 0 || value > -offset)
  12941. value += offset;
  12942. if (value === 0 && offset == -12 ) value = 12;
  12943. return padNumber(value, size, trim);
  12944. };
  12945. }
  12946. function dateStrGetter(name, shortForm) {
  12947. return function(date, formats) {
  12948. var value = date['get' + name]();
  12949. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  12950. return formats[get][value];
  12951. };
  12952. }
  12953. function timeZoneGetter(date) {
  12954. var zone = -1 * date.getTimezoneOffset();
  12955. var paddedZone = (zone >= 0) ? "+" : "";
  12956. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  12957. padNumber(Math.abs(zone % 60), 2);
  12958. return paddedZone;
  12959. }
  12960. function ampmGetter(date, formats) {
  12961. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  12962. }
  12963. var DATE_FORMATS = {
  12964. yyyy: dateGetter('FullYear', 4),
  12965. yy: dateGetter('FullYear', 2, 0, true),
  12966. y: dateGetter('FullYear', 1),
  12967. MMMM: dateStrGetter('Month'),
  12968. MMM: dateStrGetter('Month', true),
  12969. MM: dateGetter('Month', 2, 1),
  12970. M: dateGetter('Month', 1, 1),
  12971. dd: dateGetter('Date', 2),
  12972. d: dateGetter('Date', 1),
  12973. HH: dateGetter('Hours', 2),
  12974. H: dateGetter('Hours', 1),
  12975. hh: dateGetter('Hours', 2, -12),
  12976. h: dateGetter('Hours', 1, -12),
  12977. mm: dateGetter('Minutes', 2),
  12978. m: dateGetter('Minutes', 1),
  12979. ss: dateGetter('Seconds', 2),
  12980. s: dateGetter('Seconds', 1),
  12981. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  12982. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  12983. sss: dateGetter('Milliseconds', 3),
  12984. EEEE: dateStrGetter('Day'),
  12985. EEE: dateStrGetter('Day', true),
  12986. a: ampmGetter,
  12987. Z: timeZoneGetter
  12988. };
  12989. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
  12990. NUMBER_STRING = /^\-?\d+$/;
  12991. /**
  12992. * @ngdoc filter
  12993. * @name ng.filter:date
  12994. * @function
  12995. *
  12996. * @description
  12997. * Formats `date` to a string based on the requested `format`.
  12998. *
  12999. * `format` string can be composed of the following elements:
  13000. *
  13001. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  13002. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  13003. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  13004. * * `'MMMM'`: Month in year (January-December)
  13005. * * `'MMM'`: Month in year (Jan-Dec)
  13006. * * `'MM'`: Month in year, padded (01-12)
  13007. * * `'M'`: Month in year (1-12)
  13008. * * `'dd'`: Day in month, padded (01-31)
  13009. * * `'d'`: Day in month (1-31)
  13010. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  13011. * * `'EEE'`: Day in Week, (Sun-Sat)
  13012. * * `'HH'`: Hour in day, padded (00-23)
  13013. * * `'H'`: Hour in day (0-23)
  13014. * * `'hh'`: Hour in am/pm, padded (01-12)
  13015. * * `'h'`: Hour in am/pm, (1-12)
  13016. * * `'mm'`: Minute in hour, padded (00-59)
  13017. * * `'m'`: Minute in hour (0-59)
  13018. * * `'ss'`: Second in minute, padded (00-59)
  13019. * * `'s'`: Second in minute (0-59)
  13020. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  13021. * * `'a'`: am/pm marker
  13022. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  13023. *
  13024. * `format` string can also be one of the following predefined
  13025. * {@link guide/i18n localizable formats}:
  13026. *
  13027. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  13028. * (e.g. Sep 3, 2010 12:05:08 pm)
  13029. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
  13030. * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
  13031. * (e.g. Friday, September 3, 2010)
  13032. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  13033. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  13034. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  13035. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
  13036. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
  13037. *
  13038. * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
  13039. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
  13040. * (e.g. `"h 'o''clock'"`).
  13041. *
  13042. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  13043. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
  13044. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  13045. * specified in the string input, the time is considered to be in the local timezone.
  13046. * @param {string=} format Formatting rules (see Description). If not specified,
  13047. * `mediumDate` is used.
  13048. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  13049. *
  13050. * @example
  13051. <doc:example>
  13052. <doc:source>
  13053. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  13054. {{1288323623006 | date:'medium'}}<br>
  13055. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  13056. {{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
  13057. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  13058. {{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
  13059. </doc:source>
  13060. <doc:scenario>
  13061. it('should format date', function() {
  13062. expect(binding("1288323623006 | date:'medium'")).
  13063. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  13064. expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
  13065. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  13066. expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
  13067. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  13068. });
  13069. </doc:scenario>
  13070. </doc:example>
  13071. */
  13072. dateFilter.$inject = ['$locale'];
  13073. function dateFilter($locale) {
  13074. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  13075. // 1 2 3 4 5 6 7 8 9 10 11
  13076. function jsonStringToDate(string) {
  13077. var match;
  13078. if (match = string.match(R_ISO8601_STR)) {
  13079. var date = new Date(0),
  13080. tzHour = 0,
  13081. tzMin = 0,
  13082. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  13083. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  13084. if (match[9]) {
  13085. tzHour = int(match[9] + match[10]);
  13086. tzMin = int(match[9] + match[11]);
  13087. }
  13088. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  13089. var h = int(match[4]||0) - tzHour;
  13090. var m = int(match[5]||0) - tzMin;
  13091. var s = int(match[6]||0);
  13092. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  13093. timeSetter.call(date, h, m, s, ms);
  13094. return date;
  13095. }
  13096. return string;
  13097. }
  13098. return function(date, format) {
  13099. var text = '',
  13100. parts = [],
  13101. fn, match;
  13102. format = format || 'mediumDate';
  13103. format = $locale.DATETIME_FORMATS[format] || format;
  13104. if (isString(date)) {
  13105. if (NUMBER_STRING.test(date)) {
  13106. date = int(date);
  13107. } else {
  13108. date = jsonStringToDate(date);
  13109. }
  13110. }
  13111. if (isNumber(date)) {
  13112. date = new Date(date);
  13113. }
  13114. if (!isDate(date)) {
  13115. return date;
  13116. }
  13117. while(format) {
  13118. match = DATE_FORMATS_SPLIT.exec(format);
  13119. if (match) {
  13120. parts = concat(parts, match, 1);
  13121. format = parts.pop();
  13122. } else {
  13123. parts.push(format);
  13124. format = null;
  13125. }
  13126. }
  13127. forEach(parts, function(value){
  13128. fn = DATE_FORMATS[value];
  13129. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  13130. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  13131. });
  13132. return text;
  13133. };
  13134. }
  13135. /**
  13136. * @ngdoc filter
  13137. * @name ng.filter:json
  13138. * @function
  13139. *
  13140. * @description
  13141. * Allows you to convert a JavaScript object into JSON string.
  13142. *
  13143. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  13144. * the binding is automatically converted to JSON.
  13145. *
  13146. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  13147. * @returns {string} JSON string.
  13148. *
  13149. *
  13150. * @example:
  13151. <doc:example>
  13152. <doc:source>
  13153. <pre>{{ {'name':'value'} | json }}</pre>
  13154. </doc:source>
  13155. <doc:scenario>
  13156. it('should jsonify filtered objects', function() {
  13157. expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
  13158. });
  13159. </doc:scenario>
  13160. </doc:example>
  13161. *
  13162. */
  13163. function jsonFilter() {
  13164. return function(object) {
  13165. return toJson(object, true);
  13166. };
  13167. }
  13168. /**
  13169. * @ngdoc filter
  13170. * @name ng.filter:lowercase
  13171. * @function
  13172. * @description
  13173. * Converts string to lowercase.
  13174. * @see angular.lowercase
  13175. */
  13176. var lowercaseFilter = valueFn(lowercase);
  13177. /**
  13178. * @ngdoc filter
  13179. * @name ng.filter:uppercase
  13180. * @function
  13181. * @description
  13182. * Converts string to uppercase.
  13183. * @see angular.uppercase
  13184. */
  13185. var uppercaseFilter = valueFn(uppercase);
  13186. /**
  13187. * @ngdoc function
  13188. * @name ng.filter:limitTo
  13189. * @function
  13190. *
  13191. * @description
  13192. * Creates a new array or string containing only a specified number of elements. The elements
  13193. * are taken from either the beginning or the end of the source array or string, as specified by
  13194. * the value and sign (positive or negative) of `limit`.
  13195. *
  13196. * @param {Array|string} input Source array or string to be limited.
  13197. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  13198. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  13199. * If the number is negative, `limit` number of items from the end of the source array/string
  13200. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  13201. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  13202. * had less than `limit` elements.
  13203. *
  13204. * @example
  13205. <doc:example>
  13206. <doc:source>
  13207. <script>
  13208. function Ctrl($scope) {
  13209. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  13210. $scope.letters = "abcdefghi";
  13211. $scope.numLimit = 3;
  13212. $scope.letterLimit = 3;
  13213. }
  13214. </script>
  13215. <div ng-controller="Ctrl">
  13216. Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
  13217. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  13218. Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
  13219. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  13220. </div>
  13221. </doc:source>
  13222. <doc:scenario>
  13223. it('should limit the number array to first three items', function() {
  13224. expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3');
  13225. expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3');
  13226. expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]');
  13227. expect(binding('letters | limitTo:letterLimit')).toEqual('abc');
  13228. });
  13229. it('should update the output when -3 is entered', function() {
  13230. input('numLimit').enter(-3);
  13231. input('letterLimit').enter(-3);
  13232. expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]');
  13233. expect(binding('letters | limitTo:letterLimit')).toEqual('ghi');
  13234. });
  13235. it('should not exceed the maximum size of input array', function() {
  13236. input('numLimit').enter(100);
  13237. input('letterLimit').enter(100);
  13238. expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]');
  13239. expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi');
  13240. });
  13241. </doc:scenario>
  13242. </doc:example>
  13243. */
  13244. function limitToFilter(){
  13245. return function(input, limit) {
  13246. if (!isArray(input) && !isString(input)) return input;
  13247. limit = int(limit);
  13248. if (isString(input)) {
  13249. //NaN check on limit
  13250. if (limit) {
  13251. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  13252. } else {
  13253. return "";
  13254. }
  13255. }
  13256. var out = [],
  13257. i, n;
  13258. // if abs(limit) exceeds maximum length, trim it
  13259. if (limit > input.length)
  13260. limit = input.length;
  13261. else if (limit < -input.length)
  13262. limit = -input.length;
  13263. if (limit > 0) {
  13264. i = 0;
  13265. n = limit;
  13266. } else {
  13267. i = input.length + limit;
  13268. n = input.length;
  13269. }
  13270. for (; i<n; i++) {
  13271. out.push(input[i]);
  13272. }
  13273. return out;
  13274. };
  13275. }
  13276. /**
  13277. * @ngdoc function
  13278. * @name ng.filter:orderBy
  13279. * @function
  13280. *
  13281. * @description
  13282. * Orders a specified `array` by the `expression` predicate.
  13283. *
  13284. * @param {Array} array The array to sort.
  13285. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
  13286. * used by the comparator to determine the order of elements.
  13287. *
  13288. * Can be one of:
  13289. *
  13290. * - `function`: Getter function. The result of this function will be sorted using the
  13291. * `<`, `=`, `>` operator.
  13292. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
  13293. * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
  13294. * ascending or descending sort order (for example, +name or -name).
  13295. * - `Array`: An array of function or string predicates. The first predicate in the array
  13296. * is used for sorting, but when two items are equivalent, the next predicate is used.
  13297. *
  13298. * @param {boolean=} reverse Reverse the order the array.
  13299. * @returns {Array} Sorted copy of the source array.
  13300. *
  13301. * @example
  13302. <doc:example>
  13303. <doc:source>
  13304. <script>
  13305. function Ctrl($scope) {
  13306. $scope.friends =
  13307. [{name:'John', phone:'555-1212', age:10},
  13308. {name:'Mary', phone:'555-9876', age:19},
  13309. {name:'Mike', phone:'555-4321', age:21},
  13310. {name:'Adam', phone:'555-5678', age:35},
  13311. {name:'Julie', phone:'555-8765', age:29}]
  13312. $scope.predicate = '-age';
  13313. }
  13314. </script>
  13315. <div ng-controller="Ctrl">
  13316. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  13317. <hr/>
  13318. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  13319. <table class="friend">
  13320. <tr>
  13321. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  13322. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  13323. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  13324. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  13325. </tr>
  13326. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  13327. <td>{{friend.name}}</td>
  13328. <td>{{friend.phone}}</td>
  13329. <td>{{friend.age}}</td>
  13330. </tr>
  13331. </table>
  13332. </div>
  13333. </doc:source>
  13334. <doc:scenario>
  13335. it('should be reverse ordered by aged', function() {
  13336. expect(binding('predicate')).toBe('-age');
  13337. expect(repeater('table.friend', 'friend in friends').column('friend.age')).
  13338. toEqual(['35', '29', '21', '19', '10']);
  13339. expect(repeater('table.friend', 'friend in friends').column('friend.name')).
  13340. toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
  13341. });
  13342. it('should reorder the table when user selects different predicate', function() {
  13343. element('.doc-example-live a:contains("Name")').click();
  13344. expect(repeater('table.friend', 'friend in friends').column('friend.name')).
  13345. toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
  13346. expect(repeater('table.friend', 'friend in friends').column('friend.age')).
  13347. toEqual(['35', '10', '29', '19', '21']);
  13348. element('.doc-example-live a:contains("Phone")').click();
  13349. expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
  13350. toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
  13351. expect(repeater('table.friend', 'friend in friends').column('friend.name')).
  13352. toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
  13353. });
  13354. </doc:scenario>
  13355. </doc:example>
  13356. */
  13357. orderByFilter.$inject = ['$parse'];
  13358. function orderByFilter($parse){
  13359. return function(array, sortPredicate, reverseOrder) {
  13360. if (!isArray(array)) return array;
  13361. if (!sortPredicate) return array;
  13362. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  13363. sortPredicate = map(sortPredicate, function(predicate){
  13364. var descending = false, get = predicate || identity;
  13365. if (isString(predicate)) {
  13366. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  13367. descending = predicate.charAt(0) == '-';
  13368. predicate = predicate.substring(1);
  13369. }
  13370. get = $parse(predicate);
  13371. }
  13372. return reverseComparator(function(a,b){
  13373. return compare(get(a),get(b));
  13374. }, descending);
  13375. });
  13376. var arrayCopy = [];
  13377. for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  13378. return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
  13379. function comparator(o1, o2){
  13380. for ( var i = 0; i < sortPredicate.length; i++) {
  13381. var comp = sortPredicate[i](o1, o2);
  13382. if (comp !== 0) return comp;
  13383. }
  13384. return 0;
  13385. }
  13386. function reverseComparator(comp, descending) {
  13387. return toBoolean(descending)
  13388. ? function(a,b){return comp(b,a);}
  13389. : comp;
  13390. }
  13391. function compare(v1, v2){
  13392. var t1 = typeof v1;
  13393. var t2 = typeof v2;
  13394. if (t1 == t2) {
  13395. if (t1 == "string") {
  13396. v1 = v1.toLowerCase();
  13397. v2 = v2.toLowerCase();
  13398. }
  13399. if (v1 === v2) return 0;
  13400. return v1 < v2 ? -1 : 1;
  13401. } else {
  13402. return t1 < t2 ? -1 : 1;
  13403. }
  13404. }
  13405. };
  13406. }
  13407. function ngDirective(directive) {
  13408. if (isFunction(directive)) {
  13409. directive = {
  13410. link: directive
  13411. };
  13412. }
  13413. directive.restrict = directive.restrict || 'AC';
  13414. return valueFn(directive);
  13415. }
  13416. /**
  13417. * @ngdoc directive
  13418. * @name ng.directive:a
  13419. * @restrict E
  13420. *
  13421. * @description
  13422. * Modifies the default behavior of the html A tag so that the default action is prevented when
  13423. * the href attribute is empty.
  13424. *
  13425. * This change permits the easy creation of action links with the `ngClick` directive
  13426. * without changing the location or causing page reloads, e.g.:
  13427. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  13428. */
  13429. var htmlAnchorDirective = valueFn({
  13430. restrict: 'E',
  13431. compile: function(element, attr) {
  13432. if (msie <= 8) {
  13433. // turn <a href ng-click="..">link</a> into a stylable link in IE
  13434. // but only if it doesn't have name attribute, in which case it's an anchor
  13435. if (!attr.href && !attr.name) {
  13436. attr.$set('href', '');
  13437. }
  13438. // add a comment node to anchors to workaround IE bug that causes element content to be reset
  13439. // to new attribute content if attribute is updated with value containing @ and element also
  13440. // contains value with @
  13441. // see issue #1949
  13442. element.append(document.createComment('IE fix'));
  13443. }
  13444. if (!attr.href && !attr.name) {
  13445. return function(scope, element) {
  13446. element.on('click', function(event){
  13447. // if we have no href url, then don't navigate anywhere.
  13448. if (!element.attr('href')) {
  13449. event.preventDefault();
  13450. }
  13451. });
  13452. };
  13453. }
  13454. }
  13455. });
  13456. /**
  13457. * @ngdoc directive
  13458. * @name ng.directive:ngHref
  13459. * @restrict A
  13460. * @priority 99
  13461. *
  13462. * @description
  13463. * Using Angular markup like `{{hash}}` in an href attribute will
  13464. * make the link go to the wrong URL if the user clicks it before
  13465. * Angular has a chance to replace the `{{hash}}` markup with its
  13466. * value. Until Angular replaces the markup the link will be broken
  13467. * and will most likely return a 404 error.
  13468. *
  13469. * The `ngHref` directive solves this problem.
  13470. *
  13471. * The wrong way to write it:
  13472. * <pre>
  13473. * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
  13474. * </pre>
  13475. *
  13476. * The correct way to write it:
  13477. * <pre>
  13478. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
  13479. * </pre>
  13480. *
  13481. * @element A
  13482. * @param {template} ngHref any string which can contain `{{}}` markup.
  13483. *
  13484. * @example
  13485. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  13486. * in links and their different behaviors:
  13487. <doc:example>
  13488. <doc:source>
  13489. <input ng-model="value" /><br />
  13490. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  13491. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  13492. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  13493. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  13494. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  13495. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  13496. </doc:source>
  13497. <doc:scenario>
  13498. it('should execute ng-click but not reload when href without value', function() {
  13499. element('#link-1').click();
  13500. expect(input('value').val()).toEqual('1');
  13501. expect(element('#link-1').attr('href')).toBe("");
  13502. });
  13503. it('should execute ng-click but not reload when href empty string', function() {
  13504. element('#link-2').click();
  13505. expect(input('value').val()).toEqual('2');
  13506. expect(element('#link-2').attr('href')).toBe("");
  13507. });
  13508. it('should execute ng-click and change url when ng-href specified', function() {
  13509. expect(element('#link-3').attr('href')).toBe("/123");
  13510. element('#link-3').click();
  13511. expect(browser().window().path()).toEqual('/123');
  13512. });
  13513. it('should execute ng-click but not reload when href empty string and name specified', function() {
  13514. element('#link-4').click();
  13515. expect(input('value').val()).toEqual('4');
  13516. expect(element('#link-4').attr('href')).toBe('');
  13517. });
  13518. it('should execute ng-click but not reload when no href but name specified', function() {
  13519. element('#link-5').click();
  13520. expect(input('value').val()).toEqual('5');
  13521. expect(element('#link-5').attr('href')).toBe(undefined);
  13522. });
  13523. it('should only change url when only ng-href', function() {
  13524. input('value').enter('6');
  13525. expect(element('#link-6').attr('href')).toBe('6');
  13526. element('#link-6').click();
  13527. expect(browser().location().url()).toEqual('/6');
  13528. });
  13529. </doc:scenario>
  13530. </doc:example>
  13531. */
  13532. /**
  13533. * @ngdoc directive
  13534. * @name ng.directive:ngSrc
  13535. * @restrict A
  13536. * @priority 99
  13537. *
  13538. * @description
  13539. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  13540. * work right: The browser will fetch from the URL with the literal
  13541. * text `{{hash}}` until Angular replaces the expression inside
  13542. * `{{hash}}`. The `ngSrc` directive solves this problem.
  13543. *
  13544. * The buggy way to write it:
  13545. * <pre>
  13546. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  13547. * </pre>
  13548. *
  13549. * The correct way to write it:
  13550. * <pre>
  13551. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  13552. * </pre>
  13553. *
  13554. * @element IMG
  13555. * @param {template} ngSrc any string which can contain `{{}}` markup.
  13556. */
  13557. /**
  13558. * @ngdoc directive
  13559. * @name ng.directive:ngSrcset
  13560. * @restrict A
  13561. * @priority 99
  13562. *
  13563. * @description
  13564. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  13565. * work right: The browser will fetch from the URL with the literal
  13566. * text `{{hash}}` until Angular replaces the expression inside
  13567. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  13568. *
  13569. * The buggy way to write it:
  13570. * <pre>
  13571. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  13572. * </pre>
  13573. *
  13574. * The correct way to write it:
  13575. * <pre>
  13576. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  13577. * </pre>
  13578. *
  13579. * @element IMG
  13580. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  13581. */
  13582. /**
  13583. * @ngdoc directive
  13584. * @name ng.directive:ngDisabled
  13585. * @restrict A
  13586. * @priority 100
  13587. *
  13588. * @description
  13589. *
  13590. * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  13591. * <pre>
  13592. * <div ng-init="scope = { isDisabled: false }">
  13593. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  13594. * </div>
  13595. * </pre>
  13596. *
  13597. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13598. * such as disabled. (Their presence means true and their absence means false.)
  13599. * If we put an Angular interpolation expression into such an attribute then the
  13600. * binding information would be lost when the browser removes the attribute.
  13601. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  13602. * This complementary directive is not removed by the browser and so provides
  13603. * a permanent reliable place to store the binding information.
  13604. *
  13605. * @example
  13606. <doc:example>
  13607. <doc:source>
  13608. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  13609. <button ng-model="button" ng-disabled="checked">Button</button>
  13610. </doc:source>
  13611. <doc:scenario>
  13612. it('should toggle button', function() {
  13613. expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
  13614. input('checked').check();
  13615. expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
  13616. });
  13617. </doc:scenario>
  13618. </doc:example>
  13619. *
  13620. * @element INPUT
  13621. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  13622. * then special attribute "disabled" will be set on the element
  13623. */
  13624. /**
  13625. * @ngdoc directive
  13626. * @name ng.directive:ngChecked
  13627. * @restrict A
  13628. * @priority 100
  13629. *
  13630. * @description
  13631. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13632. * such as checked. (Their presence means true and their absence means false.)
  13633. * If we put an Angular interpolation expression into such an attribute then the
  13634. * binding information would be lost when the browser removes the attribute.
  13635. * The `ngChecked` directive solves this problem for the `checked` attribute.
  13636. * This complementary directive is not removed by the browser and so provides
  13637. * a permanent reliable place to store the binding information.
  13638. * @example
  13639. <doc:example>
  13640. <doc:source>
  13641. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  13642. <input id="checkSlave" type="checkbox" ng-checked="master">
  13643. </doc:source>
  13644. <doc:scenario>
  13645. it('should check both checkBoxes', function() {
  13646. expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
  13647. input('master').check();
  13648. expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
  13649. });
  13650. </doc:scenario>
  13651. </doc:example>
  13652. *
  13653. * @element INPUT
  13654. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  13655. * then special attribute "checked" will be set on the element
  13656. */
  13657. /**
  13658. * @ngdoc directive
  13659. * @name ng.directive:ngReadonly
  13660. * @restrict A
  13661. * @priority 100
  13662. *
  13663. * @description
  13664. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13665. * such as readonly. (Their presence means true and their absence means false.)
  13666. * If we put an Angular interpolation expression into such an attribute then the
  13667. * binding information would be lost when the browser removes the attribute.
  13668. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  13669. * This complementary directive is not removed by the browser and so provides
  13670. * a permanent reliable place to store the binding information.
  13671. * @example
  13672. <doc:example>
  13673. <doc:source>
  13674. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  13675. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  13676. </doc:source>
  13677. <doc:scenario>
  13678. it('should toggle readonly attr', function() {
  13679. expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
  13680. input('checked').check();
  13681. expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
  13682. });
  13683. </doc:scenario>
  13684. </doc:example>
  13685. *
  13686. * @element INPUT
  13687. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  13688. * then special attribute "readonly" will be set on the element
  13689. */
  13690. /**
  13691. * @ngdoc directive
  13692. * @name ng.directive:ngSelected
  13693. * @restrict A
  13694. * @priority 100
  13695. *
  13696. * @description
  13697. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13698. * such as selected. (Their presence means true and their absence means false.)
  13699. * If we put an Angular interpolation expression into such an attribute then the
  13700. * binding information would be lost when the browser removes the attribute.
  13701. * The `ngSelected` directive solves this problem for the `selected` atttribute.
  13702. * This complementary directive is not removed by the browser and so provides
  13703. * a permanent reliable place to store the binding information.
  13704. *
  13705. * @example
  13706. <doc:example>
  13707. <doc:source>
  13708. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  13709. <select>
  13710. <option>Hello!</option>
  13711. <option id="greet" ng-selected="selected">Greetings!</option>
  13712. </select>
  13713. </doc:source>
  13714. <doc:scenario>
  13715. it('should select Greetings!', function() {
  13716. expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
  13717. input('selected').check();
  13718. expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
  13719. });
  13720. </doc:scenario>
  13721. </doc:example>
  13722. *
  13723. * @element OPTION
  13724. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  13725. * then special attribute "selected" will be set on the element
  13726. */
  13727. /**
  13728. * @ngdoc directive
  13729. * @name ng.directive:ngOpen
  13730. * @restrict A
  13731. * @priority 100
  13732. *
  13733. * @description
  13734. * The HTML specification does not require browsers to preserve the values of boolean attributes
  13735. * such as open. (Their presence means true and their absence means false.)
  13736. * If we put an Angular interpolation expression into such an attribute then the
  13737. * binding information would be lost when the browser removes the attribute.
  13738. * The `ngOpen` directive solves this problem for the `open` attribute.
  13739. * This complementary directive is not removed by the browser and so provides
  13740. * a permanent reliable place to store the binding information.
  13741. * @example
  13742. <doc:example>
  13743. <doc:source>
  13744. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  13745. <details id="details" ng-open="open">
  13746. <summary>Show/Hide me</summary>
  13747. </details>
  13748. </doc:source>
  13749. <doc:scenario>
  13750. it('should toggle open', function() {
  13751. expect(element('#details').prop('open')).toBeFalsy();
  13752. input('open').check();
  13753. expect(element('#details').prop('open')).toBeTruthy();
  13754. });
  13755. </doc:scenario>
  13756. </doc:example>
  13757. *
  13758. * @element DETAILS
  13759. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  13760. * then special attribute "open" will be set on the element
  13761. */
  13762. var ngAttributeAliasDirectives = {};
  13763. // boolean attrs are evaluated
  13764. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  13765. // binding to multiple is not supported
  13766. if (propName == "multiple") return;
  13767. var normalized = directiveNormalize('ng-' + attrName);
  13768. ngAttributeAliasDirectives[normalized] = function() {
  13769. return {
  13770. priority: 100,
  13771. link: function(scope, element, attr) {
  13772. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  13773. attr.$set(attrName, !!value);
  13774. });
  13775. }
  13776. };
  13777. };
  13778. });
  13779. // ng-src, ng-srcset, ng-href are interpolated
  13780. forEach(['src', 'srcset', 'href'], function(attrName) {
  13781. var normalized = directiveNormalize('ng-' + attrName);
  13782. ngAttributeAliasDirectives[normalized] = function() {
  13783. return {
  13784. priority: 99, // it needs to run after the attributes are interpolated
  13785. link: function(scope, element, attr) {
  13786. attr.$observe(normalized, function(value) {
  13787. if (!value)
  13788. return;
  13789. attr.$set(attrName, value);
  13790. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  13791. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  13792. // to set the property as well to achieve the desired effect.
  13793. // we use attr[attrName] value since $set can sanitize the url.
  13794. if (msie) element.prop(attrName, attr[attrName]);
  13795. });
  13796. }
  13797. };
  13798. };
  13799. });
  13800. /* global -nullFormCtrl */
  13801. var nullFormCtrl = {
  13802. $addControl: noop,
  13803. $removeControl: noop,
  13804. $setValidity: noop,
  13805. $setDirty: noop,
  13806. $setPristine: noop
  13807. };
  13808. /**
  13809. * @ngdoc object
  13810. * @name ng.directive:form.FormController
  13811. *
  13812. * @property {boolean} $pristine True if user has not interacted with the form yet.
  13813. * @property {boolean} $dirty True if user has already interacted with the form.
  13814. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  13815. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  13816. *
  13817. * @property {Object} $error Is an object hash, containing references to all invalid controls or
  13818. * forms, where:
  13819. *
  13820. * - keys are validation tokens (error names),
  13821. * - values are arrays of controls or forms that are invalid for given error name.
  13822. *
  13823. *
  13824. * Built-in validation tokens:
  13825. *
  13826. * - `email`
  13827. * - `max`
  13828. * - `maxlength`
  13829. * - `min`
  13830. * - `minlength`
  13831. * - `number`
  13832. * - `pattern`
  13833. * - `required`
  13834. * - `url`
  13835. *
  13836. * @description
  13837. * `FormController` keeps track of all its controls and nested forms as well as state of them,
  13838. * such as being valid/invalid or dirty/pristine.
  13839. *
  13840. * Each {@link ng.directive:form form} directive creates an instance
  13841. * of `FormController`.
  13842. *
  13843. */
  13844. //asks for $scope to fool the BC controller module
  13845. FormController.$inject = ['$element', '$attrs', '$scope'];
  13846. function FormController(element, attrs) {
  13847. var form = this,
  13848. parentForm = element.parent().controller('form') || nullFormCtrl,
  13849. invalidCount = 0, // used to easily determine if we are valid
  13850. errors = form.$error = {},
  13851. controls = [];
  13852. // init state
  13853. form.$name = attrs.name || attrs.ngForm;
  13854. form.$dirty = false;
  13855. form.$pristine = true;
  13856. form.$valid = true;
  13857. form.$invalid = false;
  13858. parentForm.$addControl(form);
  13859. // Setup initial state of the control
  13860. element.addClass(PRISTINE_CLASS);
  13861. toggleValidCss(true);
  13862. // convenience method for easy toggling of classes
  13863. function toggleValidCss(isValid, validationErrorKey) {
  13864. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  13865. element.
  13866. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
  13867. addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  13868. }
  13869. /**
  13870. * @ngdoc function
  13871. * @name ng.directive:form.FormController#$addControl
  13872. * @methodOf ng.directive:form.FormController
  13873. *
  13874. * @description
  13875. * Register a control with the form.
  13876. *
  13877. * Input elements using ngModelController do this automatically when they are linked.
  13878. */
  13879. form.$addControl = function(control) {
  13880. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  13881. // and not added to the scope. Now we throw an error.
  13882. assertNotHasOwnProperty(control.$name, 'input');
  13883. controls.push(control);
  13884. if (control.$name) {
  13885. form[control.$name] = control;
  13886. }
  13887. };
  13888. /**
  13889. * @ngdoc function
  13890. * @name ng.directive:form.FormController#$removeControl
  13891. * @methodOf ng.directive:form.FormController
  13892. *
  13893. * @description
  13894. * Deregister a control from the form.
  13895. *
  13896. * Input elements using ngModelController do this automatically when they are destroyed.
  13897. */
  13898. form.$removeControl = function(control) {
  13899. if (control.$name && form[control.$name] === control) {
  13900. delete form[control.$name];
  13901. }
  13902. forEach(errors, function(queue, validationToken) {
  13903. form.$setValidity(validationToken, true, control);
  13904. });
  13905. arrayRemove(controls, control);
  13906. };
  13907. /**
  13908. * @ngdoc function
  13909. * @name ng.directive:form.FormController#$setValidity
  13910. * @methodOf ng.directive:form.FormController
  13911. *
  13912. * @description
  13913. * Sets the validity of a form control.
  13914. *
  13915. * This method will also propagate to parent forms.
  13916. */
  13917. form.$setValidity = function(validationToken, isValid, control) {
  13918. var queue = errors[validationToken];
  13919. if (isValid) {
  13920. if (queue) {
  13921. arrayRemove(queue, control);
  13922. if (!queue.length) {
  13923. invalidCount--;
  13924. if (!invalidCount) {
  13925. toggleValidCss(isValid);
  13926. form.$valid = true;
  13927. form.$invalid = false;
  13928. }
  13929. errors[validationToken] = false;
  13930. toggleValidCss(true, validationToken);
  13931. parentForm.$setValidity(validationToken, true, form);
  13932. }
  13933. }
  13934. } else {
  13935. if (!invalidCount) {
  13936. toggleValidCss(isValid);
  13937. }
  13938. if (queue) {
  13939. if (includes(queue, control)) return;
  13940. } else {
  13941. errors[validationToken] = queue = [];
  13942. invalidCount++;
  13943. toggleValidCss(false, validationToken);
  13944. parentForm.$setValidity(validationToken, false, form);
  13945. }
  13946. queue.push(control);
  13947. form.$valid = false;
  13948. form.$invalid = true;
  13949. }
  13950. };
  13951. /**
  13952. * @ngdoc function
  13953. * @name ng.directive:form.FormController#$setDirty
  13954. * @methodOf ng.directive:form.FormController
  13955. *
  13956. * @description
  13957. * Sets the form to a dirty state.
  13958. *
  13959. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  13960. * state (ng-dirty class). This method will also propagate to parent forms.
  13961. */
  13962. form.$setDirty = function() {
  13963. element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
  13964. form.$dirty = true;
  13965. form.$pristine = false;
  13966. parentForm.$setDirty();
  13967. };
  13968. /**
  13969. * @ngdoc function
  13970. * @name ng.directive:form.FormController#$setPristine
  13971. * @methodOf ng.directive:form.FormController
  13972. *
  13973. * @description
  13974. * Sets the form to its pristine state.
  13975. *
  13976. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  13977. * state (ng-pristine class). This method will also propagate to all the controls contained
  13978. * in this form.
  13979. *
  13980. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  13981. * saving or resetting it.
  13982. */
  13983. form.$setPristine = function () {
  13984. element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
  13985. form.$dirty = false;
  13986. form.$pristine = true;
  13987. forEach(controls, function(control) {
  13988. control.$setPristine();
  13989. });
  13990. };
  13991. }
  13992. /**
  13993. * @ngdoc directive
  13994. * @name ng.directive:ngForm
  13995. * @restrict EAC
  13996. *
  13997. * @description
  13998. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  13999. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  14000. * sub-group of controls needs to be determined.
  14001. *
  14002. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  14003. * related scope, under this name.
  14004. *
  14005. */
  14006. /**
  14007. * @ngdoc directive
  14008. * @name ng.directive:form
  14009. * @restrict E
  14010. *
  14011. * @description
  14012. * Directive that instantiates
  14013. * {@link ng.directive:form.FormController FormController}.
  14014. *
  14015. * If the `name` attribute is specified, the form controller is published onto the current scope under
  14016. * this name.
  14017. *
  14018. * # Alias: {@link ng.directive:ngForm `ngForm`}
  14019. *
  14020. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  14021. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  14022. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  14023. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  14024. * using Angular validation directives in forms that are dynamically generated using the
  14025. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  14026. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  14027. * `ngForm` directive and nest these in an outer `form` element.
  14028. *
  14029. *
  14030. * # CSS classes
  14031. * - `ng-valid` is set if the form is valid.
  14032. * - `ng-invalid` is set if the form is invalid.
  14033. * - `ng-pristine` is set if the form is pristine.
  14034. * - `ng-dirty` is set if the form is dirty.
  14035. *
  14036. *
  14037. * # Submitting a form and preventing the default action
  14038. *
  14039. * Since the role of forms in client-side Angular applications is different than in classical
  14040. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  14041. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  14042. * to handle the form submission in an application-specific way.
  14043. *
  14044. * For this reason, Angular prevents the default action (form submission to the server) unless the
  14045. * `<form>` element has an `action` attribute specified.
  14046. *
  14047. * You can use one of the following two ways to specify what javascript method should be called when
  14048. * a form is submitted:
  14049. *
  14050. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  14051. * - {@link ng.directive:ngClick ngClick} directive on the first
  14052. * button or input field of type submit (input[type=submit])
  14053. *
  14054. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  14055. * or {@link ng.directive:ngClick ngClick} directives.
  14056. * This is because of the following form submission rules in the HTML specification:
  14057. *
  14058. * - If a form has only one input field then hitting enter in this field triggers form submit
  14059. * (`ngSubmit`)
  14060. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  14061. * doesn't trigger submit
  14062. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  14063. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  14064. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  14065. *
  14066. * @param {string=} name Name of the form. If specified, the form controller will be published into
  14067. * related scope, under this name.
  14068. *
  14069. * @example
  14070. <doc:example>
  14071. <doc:source>
  14072. <script>
  14073. function Ctrl($scope) {
  14074. $scope.userType = 'guest';
  14075. }
  14076. </script>
  14077. <form name="myForm" ng-controller="Ctrl">
  14078. userType: <input name="input" ng-model="userType" required>
  14079. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  14080. <tt>userType = {{userType}}</tt><br>
  14081. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  14082. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  14083. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  14084. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  14085. </form>
  14086. </doc:source>
  14087. <doc:scenario>
  14088. it('should initialize to model', function() {
  14089. expect(binding('userType')).toEqual('guest');
  14090. expect(binding('myForm.input.$valid')).toEqual('true');
  14091. });
  14092. it('should be invalid if empty', function() {
  14093. input('userType').enter('');
  14094. expect(binding('userType')).toEqual('');
  14095. expect(binding('myForm.input.$valid')).toEqual('false');
  14096. });
  14097. </doc:scenario>
  14098. </doc:example>
  14099. */
  14100. var formDirectiveFactory = function(isNgForm) {
  14101. return ['$timeout', function($timeout) {
  14102. var formDirective = {
  14103. name: 'form',
  14104. restrict: isNgForm ? 'EAC' : 'E',
  14105. controller: FormController,
  14106. compile: function() {
  14107. return {
  14108. pre: function(scope, formElement, attr, controller) {
  14109. if (!attr.action) {
  14110. // we can't use jq events because if a form is destroyed during submission the default
  14111. // action is not prevented. see #1238
  14112. //
  14113. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  14114. // page reload if the form was destroyed by submission of the form via a click handler
  14115. // on a button in the form. Looks like an IE9 specific bug.
  14116. var preventDefaultListener = function(event) {
  14117. event.preventDefault
  14118. ? event.preventDefault()
  14119. : event.returnValue = false; // IE
  14120. };
  14121. addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  14122. // unregister the preventDefault listener so that we don't not leak memory but in a
  14123. // way that will achieve the prevention of the default action.
  14124. formElement.on('$destroy', function() {
  14125. $timeout(function() {
  14126. removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  14127. }, 0, false);
  14128. });
  14129. }
  14130. var parentFormCtrl = formElement.parent().controller('form'),
  14131. alias = attr.name || attr.ngForm;
  14132. if (alias) {
  14133. setter(scope, alias, controller, alias);
  14134. }
  14135. if (parentFormCtrl) {
  14136. formElement.on('$destroy', function() {
  14137. parentFormCtrl.$removeControl(controller);
  14138. if (alias) {
  14139. setter(scope, alias, undefined, alias);
  14140. }
  14141. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  14142. });
  14143. }
  14144. }
  14145. };
  14146. }
  14147. };
  14148. return formDirective;
  14149. }];
  14150. };
  14151. var formDirective = formDirectiveFactory();
  14152. var ngFormDirective = formDirectiveFactory(true);
  14153. /* global
  14154. -VALID_CLASS,
  14155. -INVALID_CLASS,
  14156. -PRISTINE_CLASS,
  14157. -DIRTY_CLASS
  14158. */
  14159. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  14160. var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/;
  14161. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  14162. var inputType = {
  14163. /**
  14164. * @ngdoc inputType
  14165. * @name ng.directive:input.text
  14166. *
  14167. * @description
  14168. * Standard HTML text input with angular data binding.
  14169. *
  14170. * @param {string} ngModel Assignable angular expression to data-bind to.
  14171. * @param {string=} name Property name of the form under which the control is published.
  14172. * @param {string=} required Adds `required` validation error key if the value is not entered.
  14173. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14174. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14175. * `required` when you want to data-bind to the `required` attribute.
  14176. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14177. * minlength.
  14178. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14179. * maxlength.
  14180. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14181. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14182. * patterns defined as scope expressions.
  14183. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14184. * interaction with the input element.
  14185. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  14186. *
  14187. * @example
  14188. <doc:example>
  14189. <doc:source>
  14190. <script>
  14191. function Ctrl($scope) {
  14192. $scope.text = 'guest';
  14193. $scope.word = /^\s*\w*\s*$/;
  14194. }
  14195. </script>
  14196. <form name="myForm" ng-controller="Ctrl">
  14197. Single word: <input type="text" name="input" ng-model="text"
  14198. ng-pattern="word" required ng-trim="false">
  14199. <span class="error" ng-show="myForm.input.$error.required">
  14200. Required!</span>
  14201. <span class="error" ng-show="myForm.input.$error.pattern">
  14202. Single word only!</span>
  14203. <tt>text = {{text}}</tt><br/>
  14204. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14205. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14206. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14207. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14208. </form>
  14209. </doc:source>
  14210. <doc:scenario>
  14211. it('should initialize to model', function() {
  14212. expect(binding('text')).toEqual('guest');
  14213. expect(binding('myForm.input.$valid')).toEqual('true');
  14214. });
  14215. it('should be invalid if empty', function() {
  14216. input('text').enter('');
  14217. expect(binding('text')).toEqual('');
  14218. expect(binding('myForm.input.$valid')).toEqual('false');
  14219. });
  14220. it('should be invalid if multi word', function() {
  14221. input('text').enter('hello world');
  14222. expect(binding('myForm.input.$valid')).toEqual('false');
  14223. });
  14224. it('should not be trimmed', function() {
  14225. input('text').enter('untrimmed ');
  14226. expect(binding('text')).toEqual('untrimmed ');
  14227. expect(binding('myForm.input.$valid')).toEqual('true');
  14228. });
  14229. </doc:scenario>
  14230. </doc:example>
  14231. */
  14232. 'text': textInputType,
  14233. /**
  14234. * @ngdoc inputType
  14235. * @name ng.directive:input.number
  14236. *
  14237. * @description
  14238. * Text input with number validation and transformation. Sets the `number` validation
  14239. * error if not a valid number.
  14240. *
  14241. * @param {string} ngModel Assignable angular expression to data-bind to.
  14242. * @param {string=} name Property name of the form under which the control is published.
  14243. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  14244. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  14245. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14246. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14247. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14248. * `required` when you want to data-bind to the `required` attribute.
  14249. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14250. * minlength.
  14251. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14252. * maxlength.
  14253. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14254. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14255. * patterns defined as scope expressions.
  14256. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14257. * interaction with the input element.
  14258. *
  14259. * @example
  14260. <doc:example>
  14261. <doc:source>
  14262. <script>
  14263. function Ctrl($scope) {
  14264. $scope.value = 12;
  14265. }
  14266. </script>
  14267. <form name="myForm" ng-controller="Ctrl">
  14268. Number: <input type="number" name="input" ng-model="value"
  14269. min="0" max="99" required>
  14270. <span class="error" ng-show="myForm.input.$error.required">
  14271. Required!</span>
  14272. <span class="error" ng-show="myForm.input.$error.number">
  14273. Not valid number!</span>
  14274. <tt>value = {{value}}</tt><br/>
  14275. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14276. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14277. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14278. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14279. </form>
  14280. </doc:source>
  14281. <doc:scenario>
  14282. it('should initialize to model', function() {
  14283. expect(binding('value')).toEqual('12');
  14284. expect(binding('myForm.input.$valid')).toEqual('true');
  14285. });
  14286. it('should be invalid if empty', function() {
  14287. input('value').enter('');
  14288. expect(binding('value')).toEqual('');
  14289. expect(binding('myForm.input.$valid')).toEqual('false');
  14290. });
  14291. it('should be invalid if over max', function() {
  14292. input('value').enter('123');
  14293. expect(binding('value')).toEqual('');
  14294. expect(binding('myForm.input.$valid')).toEqual('false');
  14295. });
  14296. </doc:scenario>
  14297. </doc:example>
  14298. */
  14299. 'number': numberInputType,
  14300. /**
  14301. * @ngdoc inputType
  14302. * @name ng.directive:input.url
  14303. *
  14304. * @description
  14305. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  14306. * valid URL.
  14307. *
  14308. * @param {string} ngModel Assignable angular expression to data-bind to.
  14309. * @param {string=} name Property name of the form under which the control is published.
  14310. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14311. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14312. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14313. * `required` when you want to data-bind to the `required` attribute.
  14314. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14315. * minlength.
  14316. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14317. * maxlength.
  14318. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14319. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14320. * patterns defined as scope expressions.
  14321. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14322. * interaction with the input element.
  14323. *
  14324. * @example
  14325. <doc:example>
  14326. <doc:source>
  14327. <script>
  14328. function Ctrl($scope) {
  14329. $scope.text = 'http://google.com';
  14330. }
  14331. </script>
  14332. <form name="myForm" ng-controller="Ctrl">
  14333. URL: <input type="url" name="input" ng-model="text" required>
  14334. <span class="error" ng-show="myForm.input.$error.required">
  14335. Required!</span>
  14336. <span class="error" ng-show="myForm.input.$error.url">
  14337. Not valid url!</span>
  14338. <tt>text = {{text}}</tt><br/>
  14339. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14340. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14341. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14342. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14343. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  14344. </form>
  14345. </doc:source>
  14346. <doc:scenario>
  14347. it('should initialize to model', function() {
  14348. expect(binding('text')).toEqual('http://google.com');
  14349. expect(binding('myForm.input.$valid')).toEqual('true');
  14350. });
  14351. it('should be invalid if empty', function() {
  14352. input('text').enter('');
  14353. expect(binding('text')).toEqual('');
  14354. expect(binding('myForm.input.$valid')).toEqual('false');
  14355. });
  14356. it('should be invalid if not url', function() {
  14357. input('text').enter('xxx');
  14358. expect(binding('myForm.input.$valid')).toEqual('false');
  14359. });
  14360. </doc:scenario>
  14361. </doc:example>
  14362. */
  14363. 'url': urlInputType,
  14364. /**
  14365. * @ngdoc inputType
  14366. * @name ng.directive:input.email
  14367. *
  14368. * @description
  14369. * Text input with email validation. Sets the `email` validation error key if not a valid email
  14370. * address.
  14371. *
  14372. * @param {string} ngModel Assignable angular expression to data-bind to.
  14373. * @param {string=} name Property name of the form under which the control is published.
  14374. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14375. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14376. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14377. * `required` when you want to data-bind to the `required` attribute.
  14378. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14379. * minlength.
  14380. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14381. * maxlength.
  14382. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14383. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14384. * patterns defined as scope expressions.
  14385. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14386. * interaction with the input element.
  14387. *
  14388. * @example
  14389. <doc:example>
  14390. <doc:source>
  14391. <script>
  14392. function Ctrl($scope) {
  14393. $scope.text = 'me@example.com';
  14394. }
  14395. </script>
  14396. <form name="myForm" ng-controller="Ctrl">
  14397. Email: <input type="email" name="input" ng-model="text" required>
  14398. <span class="error" ng-show="myForm.input.$error.required">
  14399. Required!</span>
  14400. <span class="error" ng-show="myForm.input.$error.email">
  14401. Not valid email!</span>
  14402. <tt>text = {{text}}</tt><br/>
  14403. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14404. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14405. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14406. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14407. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  14408. </form>
  14409. </doc:source>
  14410. <doc:scenario>
  14411. it('should initialize to model', function() {
  14412. expect(binding('text')).toEqual('me@example.com');
  14413. expect(binding('myForm.input.$valid')).toEqual('true');
  14414. });
  14415. it('should be invalid if empty', function() {
  14416. input('text').enter('');
  14417. expect(binding('text')).toEqual('');
  14418. expect(binding('myForm.input.$valid')).toEqual('false');
  14419. });
  14420. it('should be invalid if not email', function() {
  14421. input('text').enter('xxx');
  14422. expect(binding('myForm.input.$valid')).toEqual('false');
  14423. });
  14424. </doc:scenario>
  14425. </doc:example>
  14426. */
  14427. 'email': emailInputType,
  14428. /**
  14429. * @ngdoc inputType
  14430. * @name ng.directive:input.radio
  14431. *
  14432. * @description
  14433. * HTML radio button.
  14434. *
  14435. * @param {string} ngModel Assignable angular expression to data-bind to.
  14436. * @param {string} value The value to which the expression should be set when selected.
  14437. * @param {string=} name Property name of the form under which the control is published.
  14438. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14439. * interaction with the input element.
  14440. *
  14441. * @example
  14442. <doc:example>
  14443. <doc:source>
  14444. <script>
  14445. function Ctrl($scope) {
  14446. $scope.color = 'blue';
  14447. }
  14448. </script>
  14449. <form name="myForm" ng-controller="Ctrl">
  14450. <input type="radio" ng-model="color" value="red"> Red <br/>
  14451. <input type="radio" ng-model="color" value="green"> Green <br/>
  14452. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  14453. <tt>color = {{color}}</tt><br/>
  14454. </form>
  14455. </doc:source>
  14456. <doc:scenario>
  14457. it('should change state', function() {
  14458. expect(binding('color')).toEqual('blue');
  14459. input('color').select('red');
  14460. expect(binding('color')).toEqual('red');
  14461. });
  14462. </doc:scenario>
  14463. </doc:example>
  14464. */
  14465. 'radio': radioInputType,
  14466. /**
  14467. * @ngdoc inputType
  14468. * @name ng.directive:input.checkbox
  14469. *
  14470. * @description
  14471. * HTML checkbox.
  14472. *
  14473. * @param {string} ngModel Assignable angular expression to data-bind to.
  14474. * @param {string=} name Property name of the form under which the control is published.
  14475. * @param {string=} ngTrueValue The value to which the expression should be set when selected.
  14476. * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
  14477. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14478. * interaction with the input element.
  14479. *
  14480. * @example
  14481. <doc:example>
  14482. <doc:source>
  14483. <script>
  14484. function Ctrl($scope) {
  14485. $scope.value1 = true;
  14486. $scope.value2 = 'YES'
  14487. }
  14488. </script>
  14489. <form name="myForm" ng-controller="Ctrl">
  14490. Value1: <input type="checkbox" ng-model="value1"> <br/>
  14491. Value2: <input type="checkbox" ng-model="value2"
  14492. ng-true-value="YES" ng-false-value="NO"> <br/>
  14493. <tt>value1 = {{value1}}</tt><br/>
  14494. <tt>value2 = {{value2}}</tt><br/>
  14495. </form>
  14496. </doc:source>
  14497. <doc:scenario>
  14498. it('should change state', function() {
  14499. expect(binding('value1')).toEqual('true');
  14500. expect(binding('value2')).toEqual('YES');
  14501. input('value1').check();
  14502. input('value2').check();
  14503. expect(binding('value1')).toEqual('false');
  14504. expect(binding('value2')).toEqual('NO');
  14505. });
  14506. </doc:scenario>
  14507. </doc:example>
  14508. */
  14509. 'checkbox': checkboxInputType,
  14510. 'hidden': noop,
  14511. 'button': noop,
  14512. 'submit': noop,
  14513. 'reset': noop
  14514. };
  14515. // A helper function to call $setValidity and return the value / undefined,
  14516. // a pattern that is repeated a lot in the input validation logic.
  14517. function validate(ctrl, validatorName, validity, value){
  14518. ctrl.$setValidity(validatorName, validity);
  14519. return validity ? value : undefined;
  14520. }
  14521. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  14522. // In composition mode, users are still inputing intermediate text buffer,
  14523. // hold the listener until composition is done.
  14524. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  14525. if (!$sniffer.android) {
  14526. var composing = false;
  14527. element.on('compositionstart', function(data) {
  14528. composing = true;
  14529. });
  14530. element.on('compositionend', function() {
  14531. composing = false;
  14532. });
  14533. }
  14534. var listener = function() {
  14535. if (composing) return;
  14536. var value = element.val();
  14537. // By default we will trim the value
  14538. // If the attribute ng-trim exists we will avoid trimming
  14539. // e.g. <input ng-model="foo" ng-trim="false">
  14540. if (toBoolean(attr.ngTrim || 'T')) {
  14541. value = trim(value);
  14542. }
  14543. if (ctrl.$viewValue !== value) {
  14544. if (scope.$$phase) {
  14545. ctrl.$setViewValue(value);
  14546. } else {
  14547. scope.$apply(function() {
  14548. ctrl.$setViewValue(value);
  14549. });
  14550. }
  14551. }
  14552. };
  14553. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  14554. // input event on backspace, delete or cut
  14555. if ($sniffer.hasEvent('input')) {
  14556. element.on('input', listener);
  14557. } else {
  14558. var timeout;
  14559. var deferListener = function() {
  14560. if (!timeout) {
  14561. timeout = $browser.defer(function() {
  14562. listener();
  14563. timeout = null;
  14564. });
  14565. }
  14566. };
  14567. element.on('keydown', function(event) {
  14568. var key = event.keyCode;
  14569. // ignore
  14570. // command modifiers arrows
  14571. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  14572. deferListener();
  14573. });
  14574. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  14575. if ($sniffer.hasEvent('paste')) {
  14576. element.on('paste cut', deferListener);
  14577. }
  14578. }
  14579. // if user paste into input using mouse on older browser
  14580. // or form autocomplete on newer browser, we need "change" event to catch it
  14581. element.on('change', listener);
  14582. ctrl.$render = function() {
  14583. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  14584. };
  14585. // pattern validator
  14586. var pattern = attr.ngPattern,
  14587. patternValidator,
  14588. match;
  14589. if (pattern) {
  14590. var validateRegex = function(regexp, value) {
  14591. return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value);
  14592. };
  14593. match = pattern.match(/^\/(.*)\/([gim]*)$/);
  14594. if (match) {
  14595. pattern = new RegExp(match[1], match[2]);
  14596. patternValidator = function(value) {
  14597. return validateRegex(pattern, value);
  14598. };
  14599. } else {
  14600. patternValidator = function(value) {
  14601. var patternObj = scope.$eval(pattern);
  14602. if (!patternObj || !patternObj.test) {
  14603. throw minErr('ngPattern')('noregexp',
  14604. 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
  14605. patternObj, startingTag(element));
  14606. }
  14607. return validateRegex(patternObj, value);
  14608. };
  14609. }
  14610. ctrl.$formatters.push(patternValidator);
  14611. ctrl.$parsers.push(patternValidator);
  14612. }
  14613. // min length validator
  14614. if (attr.ngMinlength) {
  14615. var minlength = int(attr.ngMinlength);
  14616. var minLengthValidator = function(value) {
  14617. return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value);
  14618. };
  14619. ctrl.$parsers.push(minLengthValidator);
  14620. ctrl.$formatters.push(minLengthValidator);
  14621. }
  14622. // max length validator
  14623. if (attr.ngMaxlength) {
  14624. var maxlength = int(attr.ngMaxlength);
  14625. var maxLengthValidator = function(value) {
  14626. return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value);
  14627. };
  14628. ctrl.$parsers.push(maxLengthValidator);
  14629. ctrl.$formatters.push(maxLengthValidator);
  14630. }
  14631. }
  14632. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  14633. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  14634. ctrl.$parsers.push(function(value) {
  14635. var empty = ctrl.$isEmpty(value);
  14636. if (empty || NUMBER_REGEXP.test(value)) {
  14637. ctrl.$setValidity('number', true);
  14638. return value === '' ? null : (empty ? value : parseFloat(value));
  14639. } else {
  14640. ctrl.$setValidity('number', false);
  14641. return undefined;
  14642. }
  14643. });
  14644. ctrl.$formatters.push(function(value) {
  14645. return ctrl.$isEmpty(value) ? '' : '' + value;
  14646. });
  14647. if (attr.min) {
  14648. var minValidator = function(value) {
  14649. var min = parseFloat(attr.min);
  14650. return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
  14651. };
  14652. ctrl.$parsers.push(minValidator);
  14653. ctrl.$formatters.push(minValidator);
  14654. }
  14655. if (attr.max) {
  14656. var maxValidator = function(value) {
  14657. var max = parseFloat(attr.max);
  14658. return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
  14659. };
  14660. ctrl.$parsers.push(maxValidator);
  14661. ctrl.$formatters.push(maxValidator);
  14662. }
  14663. ctrl.$formatters.push(function(value) {
  14664. return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
  14665. });
  14666. }
  14667. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  14668. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  14669. var urlValidator = function(value) {
  14670. return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value);
  14671. };
  14672. ctrl.$formatters.push(urlValidator);
  14673. ctrl.$parsers.push(urlValidator);
  14674. }
  14675. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  14676. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  14677. var emailValidator = function(value) {
  14678. return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value);
  14679. };
  14680. ctrl.$formatters.push(emailValidator);
  14681. ctrl.$parsers.push(emailValidator);
  14682. }
  14683. function radioInputType(scope, element, attr, ctrl) {
  14684. // make the name unique, if not defined
  14685. if (isUndefined(attr.name)) {
  14686. element.attr('name', nextUid());
  14687. }
  14688. element.on('click', function() {
  14689. if (element[0].checked) {
  14690. scope.$apply(function() {
  14691. ctrl.$setViewValue(attr.value);
  14692. });
  14693. }
  14694. });
  14695. ctrl.$render = function() {
  14696. var value = attr.value;
  14697. element[0].checked = (value == ctrl.$viewValue);
  14698. };
  14699. attr.$observe('value', ctrl.$render);
  14700. }
  14701. function checkboxInputType(scope, element, attr, ctrl) {
  14702. var trueValue = attr.ngTrueValue,
  14703. falseValue = attr.ngFalseValue;
  14704. if (!isString(trueValue)) trueValue = true;
  14705. if (!isString(falseValue)) falseValue = false;
  14706. element.on('click', function() {
  14707. scope.$apply(function() {
  14708. ctrl.$setViewValue(element[0].checked);
  14709. });
  14710. });
  14711. ctrl.$render = function() {
  14712. element[0].checked = ctrl.$viewValue;
  14713. };
  14714. // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
  14715. ctrl.$isEmpty = function(value) {
  14716. return value !== trueValue;
  14717. };
  14718. ctrl.$formatters.push(function(value) {
  14719. return value === trueValue;
  14720. });
  14721. ctrl.$parsers.push(function(value) {
  14722. return value ? trueValue : falseValue;
  14723. });
  14724. }
  14725. /**
  14726. * @ngdoc directive
  14727. * @name ng.directive:textarea
  14728. * @restrict E
  14729. *
  14730. * @description
  14731. * HTML textarea element control with angular data-binding. The data-binding and validation
  14732. * properties of this element are exactly the same as those of the
  14733. * {@link ng.directive:input input element}.
  14734. *
  14735. * @param {string} ngModel Assignable angular expression to data-bind to.
  14736. * @param {string=} name Property name of the form under which the control is published.
  14737. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14738. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14739. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14740. * `required` when you want to data-bind to the `required` attribute.
  14741. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14742. * minlength.
  14743. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14744. * maxlength.
  14745. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14746. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14747. * patterns defined as scope expressions.
  14748. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14749. * interaction with the input element.
  14750. */
  14751. /**
  14752. * @ngdoc directive
  14753. * @name ng.directive:input
  14754. * @restrict E
  14755. *
  14756. * @description
  14757. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  14758. * and polyfills the HTML5 validation behavior for older browsers.
  14759. *
  14760. * @param {string} ngModel Assignable angular expression to data-bind to.
  14761. * @param {string=} name Property name of the form under which the control is published.
  14762. * @param {string=} required Sets `required` validation error key if the value is not entered.
  14763. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  14764. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14765. * minlength.
  14766. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14767. * maxlength.
  14768. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14769. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14770. * patterns defined as scope expressions.
  14771. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14772. * interaction with the input element.
  14773. *
  14774. * @example
  14775. <doc:example>
  14776. <doc:source>
  14777. <script>
  14778. function Ctrl($scope) {
  14779. $scope.user = {name: 'guest', last: 'visitor'};
  14780. }
  14781. </script>
  14782. <div ng-controller="Ctrl">
  14783. <form name="myForm">
  14784. User name: <input type="text" name="userName" ng-model="user.name" required>
  14785. <span class="error" ng-show="myForm.userName.$error.required">
  14786. Required!</span><br>
  14787. Last name: <input type="text" name="lastName" ng-model="user.last"
  14788. ng-minlength="3" ng-maxlength="10">
  14789. <span class="error" ng-show="myForm.lastName.$error.minlength">
  14790. Too short!</span>
  14791. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  14792. Too long!</span><br>
  14793. </form>
  14794. <hr>
  14795. <tt>user = {{user}}</tt><br/>
  14796. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  14797. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  14798. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  14799. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  14800. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  14801. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  14802. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  14803. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  14804. </div>
  14805. </doc:source>
  14806. <doc:scenario>
  14807. it('should initialize to model', function() {
  14808. expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
  14809. expect(binding('myForm.userName.$valid')).toEqual('true');
  14810. expect(binding('myForm.$valid')).toEqual('true');
  14811. });
  14812. it('should be invalid if empty when required', function() {
  14813. input('user.name').enter('');
  14814. expect(binding('user')).toEqual('{"last":"visitor"}');
  14815. expect(binding('myForm.userName.$valid')).toEqual('false');
  14816. expect(binding('myForm.$valid')).toEqual('false');
  14817. });
  14818. it('should be valid if empty when min length is set', function() {
  14819. input('user.last').enter('');
  14820. expect(binding('user')).toEqual('{"name":"guest","last":""}');
  14821. expect(binding('myForm.lastName.$valid')).toEqual('true');
  14822. expect(binding('myForm.$valid')).toEqual('true');
  14823. });
  14824. it('should be invalid if less than required min length', function() {
  14825. input('user.last').enter('xx');
  14826. expect(binding('user')).toEqual('{"name":"guest"}');
  14827. expect(binding('myForm.lastName.$valid')).toEqual('false');
  14828. expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
  14829. expect(binding('myForm.$valid')).toEqual('false');
  14830. });
  14831. it('should be invalid if longer than max length', function() {
  14832. input('user.last').enter('some ridiculously long name');
  14833. expect(binding('user'))
  14834. .toEqual('{"name":"guest"}');
  14835. expect(binding('myForm.lastName.$valid')).toEqual('false');
  14836. expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
  14837. expect(binding('myForm.$valid')).toEqual('false');
  14838. });
  14839. </doc:scenario>
  14840. </doc:example>
  14841. */
  14842. var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
  14843. return {
  14844. restrict: 'E',
  14845. require: '?ngModel',
  14846. link: function(scope, element, attr, ctrl) {
  14847. if (ctrl) {
  14848. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
  14849. $browser);
  14850. }
  14851. }
  14852. };
  14853. }];
  14854. var VALID_CLASS = 'ng-valid',
  14855. INVALID_CLASS = 'ng-invalid',
  14856. PRISTINE_CLASS = 'ng-pristine',
  14857. DIRTY_CLASS = 'ng-dirty';
  14858. /**
  14859. * @ngdoc object
  14860. * @name ng.directive:ngModel.NgModelController
  14861. *
  14862. * @property {string} $viewValue Actual string value in the view.
  14863. * @property {*} $modelValue The value in the model, that the control is bound to.
  14864. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  14865. the control reads value from the DOM. Each function is called, in turn, passing the value
  14866. through to the next. Used to sanitize / convert the value as well as validation.
  14867. For validation, the parsers should update the validity state using
  14868. {@link ng.directive:ngModel.NgModelController#methods_$setValidity $setValidity()},
  14869. and return `undefined` for invalid values.
  14870. *
  14871. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  14872. the model value changes. Each function is called, in turn, passing the value through to the
  14873. next. Used to format / convert values for display in the control and validation.
  14874. * <pre>
  14875. * function formatter(value) {
  14876. * if (value) {
  14877. * return value.toUpperCase();
  14878. * }
  14879. * }
  14880. * ngModel.$formatters.push(formatter);
  14881. * </pre>
  14882. *
  14883. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  14884. * view value has changed. It is called with no arguments, and its return value is ignored.
  14885. * This can be used in place of additional $watches against the model value.
  14886. *
  14887. * @property {Object} $error An object hash with all errors as keys.
  14888. *
  14889. * @property {boolean} $pristine True if user has not interacted with the control yet.
  14890. * @property {boolean} $dirty True if user has already interacted with the control.
  14891. * @property {boolean} $valid True if there is no error.
  14892. * @property {boolean} $invalid True if at least one error on the control.
  14893. *
  14894. * @description
  14895. *
  14896. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  14897. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  14898. * purposefully does not contain any logic which deals with DOM rendering or listening to
  14899. * DOM events. Such DOM related logic should be provided by other directives which make use of
  14900. * `NgModelController` for data-binding.
  14901. *
  14902. * ## Custom Control Example
  14903. * This example shows how to use `NgModelController` with a custom control to achieve
  14904. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  14905. * collaborate together to achieve the desired result.
  14906. *
  14907. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  14908. * contents be edited in place by the user. This will not work on older browsers.
  14909. *
  14910. * <example module="customControl">
  14911. <file name="style.css">
  14912. [contenteditable] {
  14913. border: 1px solid black;
  14914. background-color: white;
  14915. min-height: 20px;
  14916. }
  14917. .ng-invalid {
  14918. border: 1px solid red;
  14919. }
  14920. </file>
  14921. <file name="script.js">
  14922. angular.module('customControl', []).
  14923. directive('contenteditable', function() {
  14924. return {
  14925. restrict: 'A', // only activate on element attribute
  14926. require: '?ngModel', // get a hold of NgModelController
  14927. link: function(scope, element, attrs, ngModel) {
  14928. if(!ngModel) return; // do nothing if no ng-model
  14929. // Specify how UI should be updated
  14930. ngModel.$render = function() {
  14931. element.html(ngModel.$viewValue || '');
  14932. };
  14933. // Listen for change events to enable binding
  14934. element.on('blur keyup change', function() {
  14935. scope.$apply(read);
  14936. });
  14937. read(); // initialize
  14938. // Write data to the model
  14939. function read() {
  14940. var html = element.html();
  14941. // When we clear the content editable the browser leaves a <br> behind
  14942. // If strip-br attribute is provided then we strip this out
  14943. if( attrs.stripBr && html == '<br>' ) {
  14944. html = '';
  14945. }
  14946. ngModel.$setViewValue(html);
  14947. }
  14948. }
  14949. };
  14950. });
  14951. </file>
  14952. <file name="index.html">
  14953. <form name="myForm">
  14954. <div contenteditable
  14955. name="myWidget" ng-model="userContent"
  14956. strip-br="true"
  14957. required>Change me!</div>
  14958. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  14959. <hr>
  14960. <textarea ng-model="userContent"></textarea>
  14961. </form>
  14962. </file>
  14963. <file name="scenario.js">
  14964. it('should data-bind and become invalid', function() {
  14965. var contentEditable = element('[contenteditable]');
  14966. expect(contentEditable.text()).toEqual('Change me!');
  14967. input('userContent').enter('');
  14968. expect(contentEditable.text()).toEqual('');
  14969. expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
  14970. });
  14971. </file>
  14972. * </example>
  14973. *
  14974. *
  14975. */
  14976. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
  14977. function($scope, $exceptionHandler, $attr, $element, $parse) {
  14978. this.$viewValue = Number.NaN;
  14979. this.$modelValue = Number.NaN;
  14980. this.$parsers = [];
  14981. this.$formatters = [];
  14982. this.$viewChangeListeners = [];
  14983. this.$pristine = true;
  14984. this.$dirty = false;
  14985. this.$valid = true;
  14986. this.$invalid = false;
  14987. this.$name = $attr.name;
  14988. var ngModelGet = $parse($attr.ngModel),
  14989. ngModelSet = ngModelGet.assign;
  14990. if (!ngModelSet) {
  14991. throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  14992. $attr.ngModel, startingTag($element));
  14993. }
  14994. /**
  14995. * @ngdoc function
  14996. * @name ng.directive:ngModel.NgModelController#$render
  14997. * @methodOf ng.directive:ngModel.NgModelController
  14998. *
  14999. * @description
  15000. * Called when the view needs to be updated. It is expected that the user of the ng-model
  15001. * directive will implement this method.
  15002. */
  15003. this.$render = noop;
  15004. /**
  15005. * @ngdoc function
  15006. * @name { ng.directive:ngModel.NgModelController#$isEmpty
  15007. * @methodOf ng.directive:ngModel.NgModelController
  15008. *
  15009. * @description
  15010. * This is called when we need to determine if the value of the input is empty.
  15011. *
  15012. * For instance, the required directive does this to work out if the input has data or not.
  15013. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  15014. *
  15015. * You can override this for input directives whose concept of being empty is different to the
  15016. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  15017. * implies empty.
  15018. */
  15019. this.$isEmpty = function(value) {
  15020. return isUndefined(value) || value === '' || value === null || value !== value;
  15021. };
  15022. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  15023. invalidCount = 0, // used to easily determine if we are valid
  15024. $error = this.$error = {}; // keep invalid keys here
  15025. // Setup initial state of the control
  15026. $element.addClass(PRISTINE_CLASS);
  15027. toggleValidCss(true);
  15028. // convenience method for easy toggling of classes
  15029. function toggleValidCss(isValid, validationErrorKey) {
  15030. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  15031. $element.
  15032. removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
  15033. addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  15034. }
  15035. /**
  15036. * @ngdoc function
  15037. * @name ng.directive:ngModel.NgModelController#$setValidity
  15038. * @methodOf ng.directive:ngModel.NgModelController
  15039. *
  15040. * @description
  15041. * Change the validity state, and notifies the form when the control changes validity. (i.e. it
  15042. * does not notify form if given validator is already marked as invalid).
  15043. *
  15044. * This method should be called by validators - i.e. the parser or formatter functions.
  15045. *
  15046. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  15047. * to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
  15048. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  15049. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  15050. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  15051. * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
  15052. */
  15053. this.$setValidity = function(validationErrorKey, isValid) {
  15054. // Purposeful use of ! here to cast isValid to boolean in case it is undefined
  15055. // jshint -W018
  15056. if ($error[validationErrorKey] === !isValid) return;
  15057. // jshint +W018
  15058. if (isValid) {
  15059. if ($error[validationErrorKey]) invalidCount--;
  15060. if (!invalidCount) {
  15061. toggleValidCss(true);
  15062. this.$valid = true;
  15063. this.$invalid = false;
  15064. }
  15065. } else {
  15066. toggleValidCss(false);
  15067. this.$invalid = true;
  15068. this.$valid = false;
  15069. invalidCount++;
  15070. }
  15071. $error[validationErrorKey] = !isValid;
  15072. toggleValidCss(isValid, validationErrorKey);
  15073. parentForm.$setValidity(validationErrorKey, isValid, this);
  15074. };
  15075. /**
  15076. * @ngdoc function
  15077. * @name ng.directive:ngModel.NgModelController#$setPristine
  15078. * @methodOf ng.directive:ngModel.NgModelController
  15079. *
  15080. * @description
  15081. * Sets the control to its pristine state.
  15082. *
  15083. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  15084. * state (ng-pristine class).
  15085. */
  15086. this.$setPristine = function () {
  15087. this.$dirty = false;
  15088. this.$pristine = true;
  15089. $element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
  15090. };
  15091. /**
  15092. * @ngdoc function
  15093. * @name ng.directive:ngModel.NgModelController#$setViewValue
  15094. * @methodOf ng.directive:ngModel.NgModelController
  15095. *
  15096. * @description
  15097. * Update the view value.
  15098. *
  15099. * This method should be called when the view value changes, typically from within a DOM event handler.
  15100. * For example {@link ng.directive:input input} and
  15101. * {@link ng.directive:select select} directives call it.
  15102. *
  15103. * It will update the $viewValue, then pass this value through each of the functions in `$parsers`,
  15104. * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to
  15105. * `$modelValue` and the **expression** specified in the `ng-model` attribute.
  15106. *
  15107. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  15108. *
  15109. * Note that calling this function does not trigger a `$digest`.
  15110. *
  15111. * @param {string} value Value from the view.
  15112. */
  15113. this.$setViewValue = function(value) {
  15114. this.$viewValue = value;
  15115. // change to dirty
  15116. if (this.$pristine) {
  15117. this.$dirty = true;
  15118. this.$pristine = false;
  15119. $element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
  15120. parentForm.$setDirty();
  15121. }
  15122. forEach(this.$parsers, function(fn) {
  15123. value = fn(value);
  15124. });
  15125. if (this.$modelValue !== value) {
  15126. this.$modelValue = value;
  15127. ngModelSet($scope, value);
  15128. forEach(this.$viewChangeListeners, function(listener) {
  15129. try {
  15130. listener();
  15131. } catch(e) {
  15132. $exceptionHandler(e);
  15133. }
  15134. });
  15135. }
  15136. };
  15137. // model -> value
  15138. var ctrl = this;
  15139. $scope.$watch(function ngModelWatch() {
  15140. var value = ngModelGet($scope);
  15141. // if scope model value and ngModel value are out of sync
  15142. if (ctrl.$modelValue !== value) {
  15143. var formatters = ctrl.$formatters,
  15144. idx = formatters.length;
  15145. ctrl.$modelValue = value;
  15146. while(idx--) {
  15147. value = formatters[idx](value);
  15148. }
  15149. if (ctrl.$viewValue !== value) {
  15150. ctrl.$viewValue = value;
  15151. ctrl.$render();
  15152. }
  15153. }
  15154. return value;
  15155. });
  15156. }];
  15157. /**
  15158. * @ngdoc directive
  15159. * @name ng.directive:ngModel
  15160. *
  15161. * @element input
  15162. *
  15163. * @description
  15164. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  15165. * property on the scope using {@link ng.directive:ngModel.NgModelController NgModelController},
  15166. * which is created and exposed by this directive.
  15167. *
  15168. * `ngModel` is responsible for:
  15169. *
  15170. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  15171. * require.
  15172. * - Providing validation behavior (i.e. required, number, email, url).
  15173. * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
  15174. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`).
  15175. * - Registering the control with its parent {@link ng.directive:form form}.
  15176. *
  15177. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  15178. * current scope. If the property doesn't already exist on this scope, it will be created
  15179. * implicitly and added to the scope.
  15180. *
  15181. * For best practices on using `ngModel`, see:
  15182. *
  15183. * - {@link https://github.com/angular/angular.js/wiki/Understanding-Scopes}
  15184. *
  15185. * For basic examples, how to use `ngModel`, see:
  15186. *
  15187. * - {@link ng.directive:input input}
  15188. * - {@link ng.directive:input.text text}
  15189. * - {@link ng.directive:input.checkbox checkbox}
  15190. * - {@link ng.directive:input.radio radio}
  15191. * - {@link ng.directive:input.number number}
  15192. * - {@link ng.directive:input.email email}
  15193. * - {@link ng.directive:input.url url}
  15194. * - {@link ng.directive:select select}
  15195. * - {@link ng.directive:textarea textarea}
  15196. *
  15197. */
  15198. var ngModelDirective = function() {
  15199. return {
  15200. require: ['ngModel', '^?form'],
  15201. controller: NgModelController,
  15202. link: function(scope, element, attr, ctrls) {
  15203. // notify others, especially parent forms
  15204. var modelCtrl = ctrls[0],
  15205. formCtrl = ctrls[1] || nullFormCtrl;
  15206. formCtrl.$addControl(modelCtrl);
  15207. scope.$on('$destroy', function() {
  15208. formCtrl.$removeControl(modelCtrl);
  15209. });
  15210. }
  15211. };
  15212. };
  15213. /**
  15214. * @ngdoc directive
  15215. * @name ng.directive:ngChange
  15216. *
  15217. * @description
  15218. * Evaluate given expression when user changes the input.
  15219. * The expression is not evaluated when the value change is coming from the model.
  15220. *
  15221. * Note, this directive requires `ngModel` to be present.
  15222. *
  15223. * @element input
  15224. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  15225. * in input value.
  15226. *
  15227. * @example
  15228. * <doc:example>
  15229. * <doc:source>
  15230. * <script>
  15231. * function Controller($scope) {
  15232. * $scope.counter = 0;
  15233. * $scope.change = function() {
  15234. * $scope.counter++;
  15235. * };
  15236. * }
  15237. * </script>
  15238. * <div ng-controller="Controller">
  15239. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  15240. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  15241. * <label for="ng-change-example2">Confirmed</label><br />
  15242. * debug = {{confirmed}}<br />
  15243. * counter = {{counter}}
  15244. * </div>
  15245. * </doc:source>
  15246. * <doc:scenario>
  15247. * it('should evaluate the expression if changing from view', function() {
  15248. * expect(binding('counter')).toEqual('0');
  15249. * element('#ng-change-example1').click();
  15250. * expect(binding('counter')).toEqual('1');
  15251. * expect(binding('confirmed')).toEqual('true');
  15252. * });
  15253. *
  15254. * it('should not evaluate the expression if changing from model', function() {
  15255. * element('#ng-change-example2').click();
  15256. * expect(binding('counter')).toEqual('0');
  15257. * expect(binding('confirmed')).toEqual('true');
  15258. * });
  15259. * </doc:scenario>
  15260. * </doc:example>
  15261. */
  15262. var ngChangeDirective = valueFn({
  15263. require: 'ngModel',
  15264. link: function(scope, element, attr, ctrl) {
  15265. ctrl.$viewChangeListeners.push(function() {
  15266. scope.$eval(attr.ngChange);
  15267. });
  15268. }
  15269. });
  15270. var requiredDirective = function() {
  15271. return {
  15272. require: '?ngModel',
  15273. link: function(scope, elm, attr, ctrl) {
  15274. if (!ctrl) return;
  15275. attr.required = true; // force truthy in case we are on non input element
  15276. var validator = function(value) {
  15277. if (attr.required && ctrl.$isEmpty(value)) {
  15278. ctrl.$setValidity('required', false);
  15279. return;
  15280. } else {
  15281. ctrl.$setValidity('required', true);
  15282. return value;
  15283. }
  15284. };
  15285. ctrl.$formatters.push(validator);
  15286. ctrl.$parsers.unshift(validator);
  15287. attr.$observe('required', function() {
  15288. validator(ctrl.$viewValue);
  15289. });
  15290. }
  15291. };
  15292. };
  15293. /**
  15294. * @ngdoc directive
  15295. * @name ng.directive:ngList
  15296. *
  15297. * @description
  15298. * Text input that converts between a delimited string and an array of strings. The delimiter
  15299. * can be a fixed string (by default a comma) or a regular expression.
  15300. *
  15301. * @element input
  15302. * @param {string=} ngList optional delimiter that should be used to split the value. If
  15303. * specified in form `/something/` then the value will be converted into a regular expression.
  15304. *
  15305. * @example
  15306. <doc:example>
  15307. <doc:source>
  15308. <script>
  15309. function Ctrl($scope) {
  15310. $scope.names = ['igor', 'misko', 'vojta'];
  15311. }
  15312. </script>
  15313. <form name="myForm" ng-controller="Ctrl">
  15314. List: <input name="namesInput" ng-model="names" ng-list required>
  15315. <span class="error" ng-show="myForm.namesInput.$error.required">
  15316. Required!</span>
  15317. <br>
  15318. <tt>names = {{names}}</tt><br/>
  15319. <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  15320. <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  15321. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15322. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15323. </form>
  15324. </doc:source>
  15325. <doc:scenario>
  15326. it('should initialize to model', function() {
  15327. expect(binding('names')).toEqual('["igor","misko","vojta"]');
  15328. expect(binding('myForm.namesInput.$valid')).toEqual('true');
  15329. expect(element('span.error').css('display')).toBe('none');
  15330. });
  15331. it('should be invalid if empty', function() {
  15332. input('names').enter('');
  15333. expect(binding('names')).toEqual('');
  15334. expect(binding('myForm.namesInput.$valid')).toEqual('false');
  15335. expect(element('span.error').css('display')).not().toBe('none');
  15336. });
  15337. </doc:scenario>
  15338. </doc:example>
  15339. */
  15340. var ngListDirective = function() {
  15341. return {
  15342. require: 'ngModel',
  15343. link: function(scope, element, attr, ctrl) {
  15344. var match = /\/(.*)\//.exec(attr.ngList),
  15345. separator = match && new RegExp(match[1]) || attr.ngList || ',';
  15346. var parse = function(viewValue) {
  15347. // If the viewValue is invalid (say required but empty) it will be `undefined`
  15348. if (isUndefined(viewValue)) return;
  15349. var list = [];
  15350. if (viewValue) {
  15351. forEach(viewValue.split(separator), function(value) {
  15352. if (value) list.push(trim(value));
  15353. });
  15354. }
  15355. return list;
  15356. };
  15357. ctrl.$parsers.push(parse);
  15358. ctrl.$formatters.push(function(value) {
  15359. if (isArray(value)) {
  15360. return value.join(', ');
  15361. }
  15362. return undefined;
  15363. });
  15364. // Override the standard $isEmpty because an empty array means the input is empty.
  15365. ctrl.$isEmpty = function(value) {
  15366. return !value || !value.length;
  15367. };
  15368. }
  15369. };
  15370. };
  15371. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  15372. /**
  15373. * @ngdoc directive
  15374. * @name ng.directive:ngValue
  15375. *
  15376. * @description
  15377. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  15378. * that when the element is selected, the `ngModel` of that element is set to the
  15379. * bound value.
  15380. *
  15381. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  15382. * shown below.
  15383. *
  15384. * @element input
  15385. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  15386. * of the `input` element
  15387. *
  15388. * @example
  15389. <doc:example>
  15390. <doc:source>
  15391. <script>
  15392. function Ctrl($scope) {
  15393. $scope.names = ['pizza', 'unicorns', 'robots'];
  15394. $scope.my = { favorite: 'unicorns' };
  15395. }
  15396. </script>
  15397. <form ng-controller="Ctrl">
  15398. <h2>Which is your favorite?</h2>
  15399. <label ng-repeat="name in names" for="{{name}}">
  15400. {{name}}
  15401. <input type="radio"
  15402. ng-model="my.favorite"
  15403. ng-value="name"
  15404. id="{{name}}"
  15405. name="favorite">
  15406. </label>
  15407. <div>You chose {{my.favorite}}</div>
  15408. </form>
  15409. </doc:source>
  15410. <doc:scenario>
  15411. it('should initialize to model', function() {
  15412. expect(binding('my.favorite')).toEqual('unicorns');
  15413. });
  15414. it('should bind the values to the inputs', function() {
  15415. input('my.favorite').select('pizza');
  15416. expect(binding('my.favorite')).toEqual('pizza');
  15417. });
  15418. </doc:scenario>
  15419. </doc:example>
  15420. */
  15421. var ngValueDirective = function() {
  15422. return {
  15423. priority: 100,
  15424. compile: function(tpl, tplAttr) {
  15425. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  15426. return function ngValueConstantLink(scope, elm, attr) {
  15427. attr.$set('value', scope.$eval(attr.ngValue));
  15428. };
  15429. } else {
  15430. return function ngValueLink(scope, elm, attr) {
  15431. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  15432. attr.$set('value', value);
  15433. });
  15434. };
  15435. }
  15436. }
  15437. };
  15438. };
  15439. /**
  15440. * @ngdoc directive
  15441. * @name ng.directive:ngBind
  15442. * @restrict AC
  15443. *
  15444. * @description
  15445. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  15446. * with the value of a given expression, and to update the text content when the value of that
  15447. * expression changes.
  15448. *
  15449. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  15450. * `{{ expression }}` which is similar but less verbose.
  15451. *
  15452. * It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily
  15453. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  15454. * element attribute, it makes the bindings invisible to the user while the page is loading.
  15455. *
  15456. * An alternative solution to this problem would be using the
  15457. * {@link ng.directive:ngCloak ngCloak} directive.
  15458. *
  15459. *
  15460. * @element ANY
  15461. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  15462. *
  15463. * @example
  15464. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  15465. <doc:example>
  15466. <doc:source>
  15467. <script>
  15468. function Ctrl($scope) {
  15469. $scope.name = 'Whirled';
  15470. }
  15471. </script>
  15472. <div ng-controller="Ctrl">
  15473. Enter name: <input type="text" ng-model="name"><br>
  15474. Hello <span ng-bind="name"></span>!
  15475. </div>
  15476. </doc:source>
  15477. <doc:scenario>
  15478. it('should check ng-bind', function() {
  15479. expect(using('.doc-example-live').binding('name')).toBe('Whirled');
  15480. using('.doc-example-live').input('name').enter('world');
  15481. expect(using('.doc-example-live').binding('name')).toBe('world');
  15482. });
  15483. </doc:scenario>
  15484. </doc:example>
  15485. */
  15486. var ngBindDirective = ngDirective(function(scope, element, attr) {
  15487. element.addClass('ng-binding').data('$binding', attr.ngBind);
  15488. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  15489. // We are purposefully using == here rather than === because we want to
  15490. // catch when value is "null or undefined"
  15491. // jshint -W041
  15492. element.text(value == undefined ? '' : value);
  15493. });
  15494. });
  15495. /**
  15496. * @ngdoc directive
  15497. * @name ng.directive:ngBindTemplate
  15498. *
  15499. * @description
  15500. * The `ngBindTemplate` directive specifies that the element
  15501. * text content should be replaced with the interpolation of the template
  15502. * in the `ngBindTemplate` attribute.
  15503. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  15504. * expressions. This directive is needed since some HTML elements
  15505. * (such as TITLE and OPTION) cannot contain SPAN elements.
  15506. *
  15507. * @element ANY
  15508. * @param {string} ngBindTemplate template of form
  15509. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  15510. *
  15511. * @example
  15512. * Try it here: enter text in text box and watch the greeting change.
  15513. <doc:example>
  15514. <doc:source>
  15515. <script>
  15516. function Ctrl($scope) {
  15517. $scope.salutation = 'Hello';
  15518. $scope.name = 'World';
  15519. }
  15520. </script>
  15521. <div ng-controller="Ctrl">
  15522. Salutation: <input type="text" ng-model="salutation"><br>
  15523. Name: <input type="text" ng-model="name"><br>
  15524. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  15525. </div>
  15526. </doc:source>
  15527. <doc:scenario>
  15528. it('should check ng-bind', function() {
  15529. expect(using('.doc-example-live').binding('salutation')).
  15530. toBe('Hello');
  15531. expect(using('.doc-example-live').binding('name')).
  15532. toBe('World');
  15533. using('.doc-example-live').input('salutation').enter('Greetings');
  15534. using('.doc-example-live').input('name').enter('user');
  15535. expect(using('.doc-example-live').binding('salutation')).
  15536. toBe('Greetings');
  15537. expect(using('.doc-example-live').binding('name')).
  15538. toBe('user');
  15539. });
  15540. </doc:scenario>
  15541. </doc:example>
  15542. */
  15543. var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
  15544. return function(scope, element, attr) {
  15545. // TODO: move this to scenario runner
  15546. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  15547. element.addClass('ng-binding').data('$binding', interpolateFn);
  15548. attr.$observe('ngBindTemplate', function(value) {
  15549. element.text(value);
  15550. });
  15551. };
  15552. }];
  15553. /**
  15554. * @ngdoc directive
  15555. * @name ng.directive:ngBindHtml
  15556. *
  15557. * @description
  15558. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  15559. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  15560. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  15561. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  15562. * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to
  15563. * an explicitly trusted value via {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}. See the example
  15564. * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
  15565. *
  15566. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  15567. * will have an exception (instead of an exploit.)
  15568. *
  15569. * @element ANY
  15570. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  15571. *
  15572. * @example
  15573. Try it here: enter text in text box and watch the greeting change.
  15574. <example module="ngBindHtmlExample" deps="angular-sanitize.js">
  15575. <file name="index.html">
  15576. <div ng-controller="ngBindHtmlCtrl">
  15577. <p ng-bind-html="myHTML"></p>
  15578. </div>
  15579. </file>
  15580. <file name="script.js">
  15581. angular.module('ngBindHtmlExample', ['ngSanitize'])
  15582. .controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) {
  15583. $scope.myHTML =
  15584. 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>';
  15585. }]);
  15586. </file>
  15587. <file name="scenario.js">
  15588. it('should check ng-bind-html', function() {
  15589. expect(using('.doc-example-live').binding('myHTML')).
  15590. toBe(
  15591. 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>'
  15592. );
  15593. });
  15594. </file>
  15595. </example>
  15596. */
  15597. var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  15598. return function(scope, element, attr) {
  15599. element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
  15600. var parsed = $parse(attr.ngBindHtml);
  15601. function getStringValue() { return (parsed(scope) || '').toString(); }
  15602. scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
  15603. element.html($sce.getTrustedHtml(parsed(scope)) || '');
  15604. });
  15605. };
  15606. }];
  15607. function classDirective(name, selector) {
  15608. name = 'ngClass' + name;
  15609. return function() {
  15610. return {
  15611. restrict: 'AC',
  15612. link: function(scope, element, attr) {
  15613. var oldVal;
  15614. scope.$watch(attr[name], ngClassWatchAction, true);
  15615. attr.$observe('class', function(value) {
  15616. ngClassWatchAction(scope.$eval(attr[name]));
  15617. });
  15618. if (name !== 'ngClass') {
  15619. scope.$watch('$index', function($index, old$index) {
  15620. // jshint bitwise: false
  15621. var mod = $index & 1;
  15622. if (mod !== old$index & 1) {
  15623. var classes = flattenClasses(scope.$eval(attr[name]));
  15624. mod === selector ?
  15625. attr.$addClass(classes) :
  15626. attr.$removeClass(classes);
  15627. }
  15628. });
  15629. }
  15630. function ngClassWatchAction(newVal) {
  15631. if (selector === true || scope.$index % 2 === selector) {
  15632. var newClasses = flattenClasses(newVal || '');
  15633. if(!oldVal) {
  15634. attr.$addClass(newClasses);
  15635. } else if(!equals(newVal,oldVal)) {
  15636. attr.$updateClass(newClasses, flattenClasses(oldVal));
  15637. }
  15638. }
  15639. oldVal = copy(newVal);
  15640. }
  15641. function flattenClasses(classVal) {
  15642. if(isArray(classVal)) {
  15643. return classVal.join(' ');
  15644. } else if (isObject(classVal)) {
  15645. var classes = [], i = 0;
  15646. forEach(classVal, function(v, k) {
  15647. if (v) {
  15648. classes.push(k);
  15649. }
  15650. });
  15651. return classes.join(' ');
  15652. }
  15653. return classVal;
  15654. }
  15655. }
  15656. };
  15657. };
  15658. }
  15659. /**
  15660. * @ngdoc directive
  15661. * @name ng.directive:ngClass
  15662. * @restrict AC
  15663. *
  15664. * @description
  15665. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  15666. * an expression that represents all classes to be added.
  15667. *
  15668. * The directive won't add duplicate classes if a particular class was already set.
  15669. *
  15670. * When the expression changes, the previously added classes are removed and only then the
  15671. * new classes are added.
  15672. *
  15673. * @animations
  15674. * add - happens just before the class is applied to the element
  15675. * remove - happens just before the class is removed from the element
  15676. *
  15677. * @element ANY
  15678. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  15679. * of the evaluation can be a string representing space delimited class
  15680. * names, an array, or a map of class names to boolean values. In the case of a map, the
  15681. * names of the properties whose values are truthy will be added as css classes to the
  15682. * element.
  15683. *
  15684. * @example Example that demonstrates basic bindings via ngClass directive.
  15685. <example>
  15686. <file name="index.html">
  15687. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  15688. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  15689. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  15690. <input type="checkbox" ng-model="error"> error (apply "red" class)
  15691. <hr>
  15692. <p ng-class="style">Using String Syntax</p>
  15693. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  15694. <hr>
  15695. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  15696. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  15697. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  15698. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  15699. </file>
  15700. <file name="style.css">
  15701. .strike {
  15702. text-decoration: line-through;
  15703. }
  15704. .bold {
  15705. font-weight: bold;
  15706. }
  15707. .red {
  15708. color: red;
  15709. }
  15710. </file>
  15711. <file name="scenario.js">
  15712. it('should let you toggle the class', function() {
  15713. expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/bold/);
  15714. expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/red/);
  15715. input('important').check();
  15716. expect(element('.doc-example-live p:first').prop('className')).toMatch(/bold/);
  15717. input('error').check();
  15718. expect(element('.doc-example-live p:first').prop('className')).toMatch(/red/);
  15719. });
  15720. it('should let you toggle string example', function() {
  15721. expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('');
  15722. input('style').enter('red');
  15723. expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('red');
  15724. });
  15725. it('array example should have 3 classes', function() {
  15726. expect(element('.doc-example-live p:last').prop('className')).toBe('');
  15727. input('style1').enter('bold');
  15728. input('style2').enter('strike');
  15729. input('style3').enter('red');
  15730. expect(element('.doc-example-live p:last').prop('className')).toBe('bold strike red');
  15731. });
  15732. </file>
  15733. </example>
  15734. ## Animations
  15735. The example below demonstrates how to perform animations using ngClass.
  15736. <example animations="true">
  15737. <file name="index.html">
  15738. <input type="button" value="set" ng-click="myVar='my-class'">
  15739. <input type="button" value="clear" ng-click="myVar=''">
  15740. <br>
  15741. <span class="base-class" ng-class="myVar">Sample Text</span>
  15742. </file>
  15743. <file name="style.css">
  15744. .base-class {
  15745. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  15746. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  15747. }
  15748. .base-class.my-class {
  15749. color: red;
  15750. font-size:3em;
  15751. }
  15752. </file>
  15753. <file name="scenario.js">
  15754. it('should check ng-class', function() {
  15755. expect(element('.doc-example-live span').prop('className')).not().
  15756. toMatch(/my-class/);
  15757. using('.doc-example-live').element(':button:first').click();
  15758. expect(element('.doc-example-live span').prop('className')).
  15759. toMatch(/my-class/);
  15760. using('.doc-example-live').element(':button:last').click();
  15761. expect(element('.doc-example-live span').prop('className')).not().
  15762. toMatch(/my-class/);
  15763. });
  15764. </file>
  15765. </example>
  15766. ## ngClass and pre-existing CSS3 Transitions/Animations
  15767. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  15768. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  15769. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  15770. to view the step by step details of {@link ngAnimate.$animate#methods_addclass $animate.addClass} and
  15771. {@link ngAnimate.$animate#methods_removeclass $animate.removeClass}.
  15772. */
  15773. var ngClassDirective = classDirective('', true);
  15774. /**
  15775. * @ngdoc directive
  15776. * @name ng.directive:ngClassOdd
  15777. * @restrict AC
  15778. *
  15779. * @description
  15780. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  15781. * {@link ng.directive:ngClass ngClass}, except they work in
  15782. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  15783. *
  15784. * This directive can be applied only within the scope of an
  15785. * {@link ng.directive:ngRepeat ngRepeat}.
  15786. *
  15787. * @element ANY
  15788. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  15789. * of the evaluation can be a string representing space delimited class names or an array.
  15790. *
  15791. * @example
  15792. <example>
  15793. <file name="index.html">
  15794. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  15795. <li ng-repeat="name in names">
  15796. <span ng-class-odd="'odd'" ng-class-even="'even'">
  15797. {{name}}
  15798. </span>
  15799. </li>
  15800. </ol>
  15801. </file>
  15802. <file name="style.css">
  15803. .odd {
  15804. color: red;
  15805. }
  15806. .even {
  15807. color: blue;
  15808. }
  15809. </file>
  15810. <file name="scenario.js">
  15811. it('should check ng-class-odd and ng-class-even', function() {
  15812. expect(element('.doc-example-live li:first span').prop('className')).
  15813. toMatch(/odd/);
  15814. expect(element('.doc-example-live li:last span').prop('className')).
  15815. toMatch(/even/);
  15816. });
  15817. </file>
  15818. </example>
  15819. */
  15820. var ngClassOddDirective = classDirective('Odd', 0);
  15821. /**
  15822. * @ngdoc directive
  15823. * @name ng.directive:ngClassEven
  15824. * @restrict AC
  15825. *
  15826. * @description
  15827. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  15828. * {@link ng.directive:ngClass ngClass}, except they work in
  15829. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  15830. *
  15831. * This directive can be applied only within the scope of an
  15832. * {@link ng.directive:ngRepeat ngRepeat}.
  15833. *
  15834. * @element ANY
  15835. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  15836. * result of the evaluation can be a string representing space delimited class names or an array.
  15837. *
  15838. * @example
  15839. <example>
  15840. <file name="index.html">
  15841. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  15842. <li ng-repeat="name in names">
  15843. <span ng-class-odd="'odd'" ng-class-even="'even'">
  15844. {{name}} &nbsp; &nbsp; &nbsp;
  15845. </span>
  15846. </li>
  15847. </ol>
  15848. </file>
  15849. <file name="style.css">
  15850. .odd {
  15851. color: red;
  15852. }
  15853. .even {
  15854. color: blue;
  15855. }
  15856. </file>
  15857. <file name="scenario.js">
  15858. it('should check ng-class-odd and ng-class-even', function() {
  15859. expect(element('.doc-example-live li:first span').prop('className')).
  15860. toMatch(/odd/);
  15861. expect(element('.doc-example-live li:last span').prop('className')).
  15862. toMatch(/even/);
  15863. });
  15864. </file>
  15865. </example>
  15866. */
  15867. var ngClassEvenDirective = classDirective('Even', 1);
  15868. /**
  15869. * @ngdoc directive
  15870. * @name ng.directive:ngCloak
  15871. * @restrict AC
  15872. *
  15873. * @description
  15874. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  15875. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  15876. * directive to avoid the undesirable flicker effect caused by the html template display.
  15877. *
  15878. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  15879. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  15880. * of the browser view.
  15881. *
  15882. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  15883. * `angular.min.js`.
  15884. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  15885. *
  15886. * <pre>
  15887. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  15888. * display: none !important;
  15889. * }
  15890. * </pre>
  15891. *
  15892. * When this css rule is loaded by the browser, all html elements (including their children) that
  15893. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  15894. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  15895. * the compiled element visible.
  15896. *
  15897. * For the best result, the `angular.js` script must be loaded in the head section of the html
  15898. * document; alternatively, the css rule above must be included in the external stylesheet of the
  15899. * application.
  15900. *
  15901. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  15902. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  15903. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  15904. *
  15905. * @element ANY
  15906. *
  15907. * @example
  15908. <doc:example>
  15909. <doc:source>
  15910. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  15911. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  15912. </doc:source>
  15913. <doc:scenario>
  15914. it('should remove the template directive and css class', function() {
  15915. expect(element('.doc-example-live #template1').attr('ng-cloak')).
  15916. not().toBeDefined();
  15917. expect(element('.doc-example-live #template2').attr('ng-cloak')).
  15918. not().toBeDefined();
  15919. });
  15920. </doc:scenario>
  15921. </doc:example>
  15922. *
  15923. */
  15924. var ngCloakDirective = ngDirective({
  15925. compile: function(element, attr) {
  15926. attr.$set('ngCloak', undefined);
  15927. element.removeClass('ng-cloak');
  15928. }
  15929. });
  15930. /**
  15931. * @ngdoc directive
  15932. * @name ng.directive:ngController
  15933. *
  15934. * @description
  15935. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  15936. * supports the principles behind the Model-View-Controller design pattern.
  15937. *
  15938. * MVC components in angular:
  15939. *
  15940. * * Model — The Model is scope properties; scopes are attached to the DOM where scope properties
  15941. * are accessed through bindings.
  15942. * * View — The template (HTML with data bindings) that is rendered into the View.
  15943. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  15944. * logic behind the application to decorate the scope with functions and values
  15945. *
  15946. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  15947. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  15948. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  15949. * and executed twice.
  15950. *
  15951. * @element ANY
  15952. * @scope
  15953. * @param {expression} ngController Name of a globally accessible constructor function or an
  15954. * {@link guide/expression expression} that on the current scope evaluates to a
  15955. * constructor function. The controller instance can be published into a scope property
  15956. * by specifying `as propertyName`.
  15957. *
  15958. * @example
  15959. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  15960. * greeting are methods declared on the controller (see source tab). These methods can
  15961. * easily be called from the angular markup. Notice that the scope becomes the `this` for the
  15962. * controller's instance. This allows for easy access to the view data from the controller. Also
  15963. * notice that any changes to the data are automatically reflected in the View without the need
  15964. * for a manual update. The example is shown in two different declaration styles you may use
  15965. * according to preference.
  15966. <doc:example>
  15967. <doc:source>
  15968. <script>
  15969. function SettingsController1() {
  15970. this.name = "John Smith";
  15971. this.contacts = [
  15972. {type: 'phone', value: '408 555 1212'},
  15973. {type: 'email', value: 'john.smith@example.org'} ];
  15974. };
  15975. SettingsController1.prototype.greet = function() {
  15976. alert(this.name);
  15977. };
  15978. SettingsController1.prototype.addContact = function() {
  15979. this.contacts.push({type: 'email', value: 'yourname@example.org'});
  15980. };
  15981. SettingsController1.prototype.removeContact = function(contactToRemove) {
  15982. var index = this.contacts.indexOf(contactToRemove);
  15983. this.contacts.splice(index, 1);
  15984. };
  15985. SettingsController1.prototype.clearContact = function(contact) {
  15986. contact.type = 'phone';
  15987. contact.value = '';
  15988. };
  15989. </script>
  15990. <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  15991. Name: <input type="text" ng-model="settings.name"/>
  15992. [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  15993. Contact:
  15994. <ul>
  15995. <li ng-repeat="contact in settings.contacts">
  15996. <select ng-model="contact.type">
  15997. <option>phone</option>
  15998. <option>email</option>
  15999. </select>
  16000. <input type="text" ng-model="contact.value"/>
  16001. [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  16002. | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  16003. </li>
  16004. <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  16005. </ul>
  16006. </div>
  16007. </doc:source>
  16008. <doc:scenario>
  16009. it('should check controller as', function() {
  16010. expect(element('#ctrl-as-exmpl>:input').val()).toBe('John Smith');
  16011. expect(element('#ctrl-as-exmpl li:nth-child(1) input').val())
  16012. .toBe('408 555 1212');
  16013. expect(element('#ctrl-as-exmpl li:nth-child(2) input').val())
  16014. .toBe('john.smith@example.org');
  16015. element('#ctrl-as-exmpl li:first a:contains("clear")').click();
  16016. expect(element('#ctrl-as-exmpl li:first input').val()).toBe('');
  16017. element('#ctrl-as-exmpl li:last a:contains("add")').click();
  16018. expect(element('#ctrl-as-exmpl li:nth-child(3) input').val())
  16019. .toBe('yourname@example.org');
  16020. });
  16021. </doc:scenario>
  16022. </doc:example>
  16023. <doc:example>
  16024. <doc:source>
  16025. <script>
  16026. function SettingsController2($scope) {
  16027. $scope.name = "John Smith";
  16028. $scope.contacts = [
  16029. {type:'phone', value:'408 555 1212'},
  16030. {type:'email', value:'john.smith@example.org'} ];
  16031. $scope.greet = function() {
  16032. alert(this.name);
  16033. };
  16034. $scope.addContact = function() {
  16035. this.contacts.push({type:'email', value:'yourname@example.org'});
  16036. };
  16037. $scope.removeContact = function(contactToRemove) {
  16038. var index = this.contacts.indexOf(contactToRemove);
  16039. this.contacts.splice(index, 1);
  16040. };
  16041. $scope.clearContact = function(contact) {
  16042. contact.type = 'phone';
  16043. contact.value = '';
  16044. };
  16045. }
  16046. </script>
  16047. <div id="ctrl-exmpl" ng-controller="SettingsController2">
  16048. Name: <input type="text" ng-model="name"/>
  16049. [ <a href="" ng-click="greet()">greet</a> ]<br/>
  16050. Contact:
  16051. <ul>
  16052. <li ng-repeat="contact in contacts">
  16053. <select ng-model="contact.type">
  16054. <option>phone</option>
  16055. <option>email</option>
  16056. </select>
  16057. <input type="text" ng-model="contact.value"/>
  16058. [ <a href="" ng-click="clearContact(contact)">clear</a>
  16059. | <a href="" ng-click="removeContact(contact)">X</a> ]
  16060. </li>
  16061. <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  16062. </ul>
  16063. </div>
  16064. </doc:source>
  16065. <doc:scenario>
  16066. it('should check controller', function() {
  16067. expect(element('#ctrl-exmpl>:input').val()).toBe('John Smith');
  16068. expect(element('#ctrl-exmpl li:nth-child(1) input').val())
  16069. .toBe('408 555 1212');
  16070. expect(element('#ctrl-exmpl li:nth-child(2) input').val())
  16071. .toBe('john.smith@example.org');
  16072. element('#ctrl-exmpl li:first a:contains("clear")').click();
  16073. expect(element('#ctrl-exmpl li:first input').val()).toBe('');
  16074. element('#ctrl-exmpl li:last a:contains("add")').click();
  16075. expect(element('#ctrl-exmpl li:nth-child(3) input').val())
  16076. .toBe('yourname@example.org');
  16077. });
  16078. </doc:scenario>
  16079. </doc:example>
  16080. */
  16081. var ngControllerDirective = [function() {
  16082. return {
  16083. scope: true,
  16084. controller: '@',
  16085. priority: 500
  16086. };
  16087. }];
  16088. /**
  16089. * @ngdoc directive
  16090. * @name ng.directive:ngCsp
  16091. *
  16092. * @element html
  16093. * @description
  16094. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  16095. *
  16096. * This is necessary when developing things like Google Chrome Extensions.
  16097. *
  16098. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  16099. * For us to be compatible, we just need to implement the "getterFn" in $parse without violating
  16100. * any of these restrictions.
  16101. *
  16102. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  16103. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  16104. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  16105. * be raised.
  16106. *
  16107. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  16108. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  16109. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  16110. *
  16111. * In order to use this feature put the `ngCsp` directive on the root element of the application.
  16112. *
  16113. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  16114. *
  16115. * @example
  16116. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  16117. <pre>
  16118. <!doctype html>
  16119. <html ng-app ng-csp>
  16120. ...
  16121. ...
  16122. </html>
  16123. </pre>
  16124. */
  16125. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap
  16126. // the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute
  16127. // anywhere in the current doc
  16128. /**
  16129. * @ngdoc directive
  16130. * @name ng.directive:ngClick
  16131. *
  16132. * @description
  16133. * The ngClick directive allows you to specify custom behavior when
  16134. * an element is clicked.
  16135. *
  16136. * @element ANY
  16137. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  16138. * click. (Event object is available as `$event`)
  16139. *
  16140. * @example
  16141. <doc:example>
  16142. <doc:source>
  16143. <button ng-click="count = count + 1" ng-init="count=0">
  16144. Increment
  16145. </button>
  16146. count: {{count}}
  16147. </doc:source>
  16148. <doc:protractor>
  16149. it('should check ng-click', function() {
  16150. expect(element(by.binding('count')).getText()).toMatch('0');
  16151. element(by.css('.doc-example-live button')).click();
  16152. expect(element(by.binding('count')).getText()).toMatch('1');
  16153. });
  16154. </doc:protractor>
  16155. </doc:example>
  16156. */
  16157. /*
  16158. * A directive that allows creation of custom onclick handlers that are defined as angular
  16159. * expressions and are compiled and executed within the current scope.
  16160. *
  16161. * Events that are handled via these handler are always configured not to propagate further.
  16162. */
  16163. var ngEventDirectives = {};
  16164. forEach(
  16165. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  16166. function(name) {
  16167. var directiveName = directiveNormalize('ng-' + name);
  16168. ngEventDirectives[directiveName] = ['$parse', function($parse) {
  16169. return {
  16170. compile: function($element, attr) {
  16171. var fn = $parse(attr[directiveName]);
  16172. return function(scope, element, attr) {
  16173. element.on(lowercase(name), function(event) {
  16174. scope.$apply(function() {
  16175. fn(scope, {$event:event});
  16176. });
  16177. });
  16178. };
  16179. }
  16180. };
  16181. }];
  16182. }
  16183. );
  16184. /**
  16185. * @ngdoc directive
  16186. * @name ng.directive:ngDblclick
  16187. *
  16188. * @description
  16189. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  16190. *
  16191. * @element ANY
  16192. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  16193. * a dblclick. (The Event object is available as `$event`)
  16194. *
  16195. * @example
  16196. <doc:example>
  16197. <doc:source>
  16198. <button ng-dblclick="count = count + 1" ng-init="count=0">
  16199. Increment (on double click)
  16200. </button>
  16201. count: {{count}}
  16202. </doc:source>
  16203. </doc:example>
  16204. */
  16205. /**
  16206. * @ngdoc directive
  16207. * @name ng.directive:ngMousedown
  16208. *
  16209. * @description
  16210. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  16211. *
  16212. * @element ANY
  16213. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  16214. * mousedown. (Event object is available as `$event`)
  16215. *
  16216. * @example
  16217. <doc:example>
  16218. <doc:source>
  16219. <button ng-mousedown="count = count + 1" ng-init="count=0">
  16220. Increment (on mouse down)
  16221. </button>
  16222. count: {{count}}
  16223. </doc:source>
  16224. </doc:example>
  16225. */
  16226. /**
  16227. * @ngdoc directive
  16228. * @name ng.directive:ngMouseup
  16229. *
  16230. * @description
  16231. * Specify custom behavior on mouseup event.
  16232. *
  16233. * @element ANY
  16234. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  16235. * mouseup. (Event object is available as `$event`)
  16236. *
  16237. * @example
  16238. <doc:example>
  16239. <doc:source>
  16240. <button ng-mouseup="count = count + 1" ng-init="count=0">
  16241. Increment (on mouse up)
  16242. </button>
  16243. count: {{count}}
  16244. </doc:source>
  16245. </doc:example>
  16246. */
  16247. /**
  16248. * @ngdoc directive
  16249. * @name ng.directive:ngMouseover
  16250. *
  16251. * @description
  16252. * Specify custom behavior on mouseover event.
  16253. *
  16254. * @element ANY
  16255. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  16256. * mouseover. (Event object is available as `$event`)
  16257. *
  16258. * @example
  16259. <doc:example>
  16260. <doc:source>
  16261. <button ng-mouseover="count = count + 1" ng-init="count=0">
  16262. Increment (when mouse is over)
  16263. </button>
  16264. count: {{count}}
  16265. </doc:source>
  16266. </doc:example>
  16267. */
  16268. /**
  16269. * @ngdoc directive
  16270. * @name ng.directive:ngMouseenter
  16271. *
  16272. * @description
  16273. * Specify custom behavior on mouseenter event.
  16274. *
  16275. * @element ANY
  16276. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  16277. * mouseenter. (Event object is available as `$event`)
  16278. *
  16279. * @example
  16280. <doc:example>
  16281. <doc:source>
  16282. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  16283. Increment (when mouse enters)
  16284. </button>
  16285. count: {{count}}
  16286. </doc:source>
  16287. </doc:example>
  16288. */
  16289. /**
  16290. * @ngdoc directive
  16291. * @name ng.directive:ngMouseleave
  16292. *
  16293. * @description
  16294. * Specify custom behavior on mouseleave event.
  16295. *
  16296. * @element ANY
  16297. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  16298. * mouseleave. (Event object is available as `$event`)
  16299. *
  16300. * @example
  16301. <doc:example>
  16302. <doc:source>
  16303. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  16304. Increment (when mouse leaves)
  16305. </button>
  16306. count: {{count}}
  16307. </doc:source>
  16308. </doc:example>
  16309. */
  16310. /**
  16311. * @ngdoc directive
  16312. * @name ng.directive:ngMousemove
  16313. *
  16314. * @description
  16315. * Specify custom behavior on mousemove event.
  16316. *
  16317. * @element ANY
  16318. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  16319. * mousemove. (Event object is available as `$event`)
  16320. *
  16321. * @example
  16322. <doc:example>
  16323. <doc:source>
  16324. <button ng-mousemove="count = count + 1" ng-init="count=0">
  16325. Increment (when mouse moves)
  16326. </button>
  16327. count: {{count}}
  16328. </doc:source>
  16329. </doc:example>
  16330. */
  16331. /**
  16332. * @ngdoc directive
  16333. * @name ng.directive:ngKeydown
  16334. *
  16335. * @description
  16336. * Specify custom behavior on keydown event.
  16337. *
  16338. * @element ANY
  16339. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  16340. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  16341. *
  16342. * @example
  16343. <doc:example>
  16344. <doc:source>
  16345. <input ng-keydown="count = count + 1" ng-init="count=0">
  16346. key down count: {{count}}
  16347. </doc:source>
  16348. </doc:example>
  16349. */
  16350. /**
  16351. * @ngdoc directive
  16352. * @name ng.directive:ngKeyup
  16353. *
  16354. * @description
  16355. * Specify custom behavior on keyup event.
  16356. *
  16357. * @element ANY
  16358. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  16359. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  16360. *
  16361. * @example
  16362. <doc:example>
  16363. <doc:source>
  16364. <input ng-keyup="count = count + 1" ng-init="count=0">
  16365. key up count: {{count}}
  16366. </doc:source>
  16367. </doc:example>
  16368. */
  16369. /**
  16370. * @ngdoc directive
  16371. * @name ng.directive:ngKeypress
  16372. *
  16373. * @description
  16374. * Specify custom behavior on keypress event.
  16375. *
  16376. * @element ANY
  16377. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  16378. * keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  16379. *
  16380. * @example
  16381. <doc:example>
  16382. <doc:source>
  16383. <input ng-keypress="count = count + 1" ng-init="count=0">
  16384. key press count: {{count}}
  16385. </doc:source>
  16386. </doc:example>
  16387. */
  16388. /**
  16389. * @ngdoc directive
  16390. * @name ng.directive:ngSubmit
  16391. *
  16392. * @description
  16393. * Enables binding angular expressions to onsubmit events.
  16394. *
  16395. * Additionally it prevents the default action (which for form means sending the request to the
  16396. * server and reloading the current page) **but only if the form does not contain an `action`
  16397. * attribute**.
  16398. *
  16399. * @element form
  16400. * @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`)
  16401. *
  16402. * @example
  16403. <doc:example>
  16404. <doc:source>
  16405. <script>
  16406. function Ctrl($scope) {
  16407. $scope.list = [];
  16408. $scope.text = 'hello';
  16409. $scope.submit = function() {
  16410. if (this.text) {
  16411. this.list.push(this.text);
  16412. this.text = '';
  16413. }
  16414. };
  16415. }
  16416. </script>
  16417. <form ng-submit="submit()" ng-controller="Ctrl">
  16418. Enter text and hit enter:
  16419. <input type="text" ng-model="text" name="text" />
  16420. <input type="submit" id="submit" value="Submit" />
  16421. <pre>list={{list}}</pre>
  16422. </form>
  16423. </doc:source>
  16424. <doc:scenario>
  16425. it('should check ng-submit', function() {
  16426. expect(binding('list')).toBe('[]');
  16427. element('.doc-example-live #submit').click();
  16428. expect(binding('list')).toBe('["hello"]');
  16429. expect(input('text').val()).toBe('');
  16430. });
  16431. it('should ignore empty strings', function() {
  16432. expect(binding('list')).toBe('[]');
  16433. element('.doc-example-live #submit').click();
  16434. element('.doc-example-live #submit').click();
  16435. expect(binding('list')).toBe('["hello"]');
  16436. });
  16437. </doc:scenario>
  16438. </doc:example>
  16439. */
  16440. /**
  16441. * @ngdoc directive
  16442. * @name ng.directive:ngFocus
  16443. *
  16444. * @description
  16445. * Specify custom behavior on focus event.
  16446. *
  16447. * @element window, input, select, textarea, a
  16448. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  16449. * focus. (Event object is available as `$event`)
  16450. *
  16451. * @example
  16452. * See {@link ng.directive:ngClick ngClick}
  16453. */
  16454. /**
  16455. * @ngdoc directive
  16456. * @name ng.directive:ngBlur
  16457. *
  16458. * @description
  16459. * Specify custom behavior on blur event.
  16460. *
  16461. * @element window, input, select, textarea, a
  16462. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  16463. * blur. (Event object is available as `$event`)
  16464. *
  16465. * @example
  16466. * See {@link ng.directive:ngClick ngClick}
  16467. */
  16468. /**
  16469. * @ngdoc directive
  16470. * @name ng.directive:ngCopy
  16471. *
  16472. * @description
  16473. * Specify custom behavior on copy event.
  16474. *
  16475. * @element window, input, select, textarea, a
  16476. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  16477. * copy. (Event object is available as `$event`)
  16478. *
  16479. * @example
  16480. <doc:example>
  16481. <doc:source>
  16482. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  16483. copied: {{copied}}
  16484. </doc:source>
  16485. </doc:example>
  16486. */
  16487. /**
  16488. * @ngdoc directive
  16489. * @name ng.directive:ngCut
  16490. *
  16491. * @description
  16492. * Specify custom behavior on cut event.
  16493. *
  16494. * @element window, input, select, textarea, a
  16495. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  16496. * cut. (Event object is available as `$event`)
  16497. *
  16498. * @example
  16499. <doc:example>
  16500. <doc:source>
  16501. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  16502. cut: {{cut}}
  16503. </doc:source>
  16504. </doc:example>
  16505. */
  16506. /**
  16507. * @ngdoc directive
  16508. * @name ng.directive:ngPaste
  16509. *
  16510. * @description
  16511. * Specify custom behavior on paste event.
  16512. *
  16513. * @element window, input, select, textarea, a
  16514. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  16515. * paste. (Event object is available as `$event`)
  16516. *
  16517. * @example
  16518. <doc:example>
  16519. <doc:source>
  16520. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  16521. pasted: {{paste}}
  16522. </doc:source>
  16523. </doc:example>
  16524. */
  16525. /**
  16526. * @ngdoc directive
  16527. * @name ng.directive:ngIf
  16528. * @restrict A
  16529. *
  16530. * @description
  16531. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  16532. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  16533. * value then the element is removed from the DOM, otherwise a clone of the
  16534. * element is reinserted into the DOM.
  16535. *
  16536. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  16537. * element in the DOM rather than changing its visibility via the `display` css property. A common
  16538. * case when this difference is significant is when using css selectors that rely on an element's
  16539. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  16540. *
  16541. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  16542. * is created when the element is restored. The scope created within `ngIf` inherits from
  16543. * its parent scope using
  16544. * {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}.
  16545. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  16546. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  16547. * variable within the child scope will override (hide) the value in the parent scope.
  16548. *
  16549. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  16550. * is if an element's class attribute is directly modified after it's compiled, using something like
  16551. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  16552. * the added class will be lost because the original compiled state is used to regenerate the element.
  16553. *
  16554. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  16555. * and `leave` effects.
  16556. *
  16557. * @animations
  16558. * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
  16559. * leave - happens just before the ngIf contents are removed from the DOM
  16560. *
  16561. * @element ANY
  16562. * @scope
  16563. * @priority 600
  16564. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  16565. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  16566. * element is added to the DOM tree.
  16567. *
  16568. * @example
  16569. <example animations="true">
  16570. <file name="index.html">
  16571. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  16572. Show when checked:
  16573. <span ng-if="checked" class="animate-if">
  16574. I'm removed when the checkbox is unchecked.
  16575. </span>
  16576. </file>
  16577. <file name="animations.css">
  16578. .animate-if {
  16579. background:white;
  16580. border:1px solid black;
  16581. padding:10px;
  16582. }
  16583. .animate-if.ng-enter, .animate-if.ng-leave {
  16584. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16585. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16586. }
  16587. .animate-if.ng-enter,
  16588. .animate-if.ng-leave.ng-leave-active {
  16589. opacity:0;
  16590. }
  16591. .animate-if.ng-leave,
  16592. .animate-if.ng-enter.ng-enter-active {
  16593. opacity:1;
  16594. }
  16595. </file>
  16596. </example>
  16597. */
  16598. var ngIfDirective = ['$animate', function($animate) {
  16599. return {
  16600. transclude: 'element',
  16601. priority: 600,
  16602. terminal: true,
  16603. restrict: 'A',
  16604. $$tlb: true,
  16605. link: function ($scope, $element, $attr, ctrl, $transclude) {
  16606. var block, childScope;
  16607. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  16608. if (toBoolean(value)) {
  16609. if (!childScope) {
  16610. childScope = $scope.$new();
  16611. $transclude(childScope, function (clone) {
  16612. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  16613. // Note: We only need the first/last node of the cloned nodes.
  16614. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  16615. // by a directive with templateUrl when it's template arrives.
  16616. block = {
  16617. clone: clone
  16618. };
  16619. $animate.enter(clone, $element.parent(), $element);
  16620. });
  16621. }
  16622. } else {
  16623. if (childScope) {
  16624. childScope.$destroy();
  16625. childScope = null;
  16626. }
  16627. if (block) {
  16628. $animate.leave(getBlockElements(block.clone));
  16629. block = null;
  16630. }
  16631. }
  16632. });
  16633. }
  16634. };
  16635. }];
  16636. /**
  16637. * @ngdoc directive
  16638. * @name ng.directive:ngInclude
  16639. * @restrict ECA
  16640. *
  16641. * @description
  16642. * Fetches, compiles and includes an external HTML fragment.
  16643. *
  16644. * By default, the template URL is restricted to the same domain and protocol as the
  16645. * application document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl
  16646. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  16647. * you may either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist them} or
  16648. * {@link ng.$sce#methods_trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  16649. * ng.$sce Strict Contextual Escaping}.
  16650. *
  16651. * In addition, the browser's
  16652. * {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
  16653. * Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing
  16654. * (CORS)} policy may further restrict whether the template is successfully loaded.
  16655. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  16656. * access on some browsers.
  16657. *
  16658. * @animations
  16659. * enter - animation is used to bring new content into the browser.
  16660. * leave - animation is used to animate existing content away.
  16661. *
  16662. * The enter and leave animation occur concurrently.
  16663. *
  16664. * @scope
  16665. * @priority 400
  16666. *
  16667. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  16668. * make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
  16669. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  16670. *
  16671. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  16672. * $anchorScroll} to scroll the viewport after the content is loaded.
  16673. *
  16674. * - If the attribute is not set, disable scrolling.
  16675. * - If the attribute is set without value, enable scrolling.
  16676. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  16677. *
  16678. * @example
  16679. <example animations="true">
  16680. <file name="index.html">
  16681. <div ng-controller="Ctrl">
  16682. <select ng-model="template" ng-options="t.name for t in templates">
  16683. <option value="">(blank)</option>
  16684. </select>
  16685. url of the template: <tt>{{template.url}}</tt>
  16686. <hr/>
  16687. <div class="slide-animate-container">
  16688. <div class="slide-animate" ng-include="template.url"></div>
  16689. </div>
  16690. </div>
  16691. </file>
  16692. <file name="script.js">
  16693. function Ctrl($scope) {
  16694. $scope.templates =
  16695. [ { name: 'template1.html', url: 'template1.html'}
  16696. , { name: 'template2.html', url: 'template2.html'} ];
  16697. $scope.template = $scope.templates[0];
  16698. }
  16699. </file>
  16700. <file name="template1.html">
  16701. Content of template1.html
  16702. </file>
  16703. <file name="template2.html">
  16704. Content of template2.html
  16705. </file>
  16706. <file name="animations.css">
  16707. .slide-animate-container {
  16708. position:relative;
  16709. background:white;
  16710. border:1px solid black;
  16711. height:40px;
  16712. overflow:hidden;
  16713. }
  16714. .slide-animate {
  16715. padding:10px;
  16716. }
  16717. .slide-animate.ng-enter, .slide-animate.ng-leave {
  16718. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16719. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16720. position:absolute;
  16721. top:0;
  16722. left:0;
  16723. right:0;
  16724. bottom:0;
  16725. display:block;
  16726. padding:10px;
  16727. }
  16728. .slide-animate.ng-enter {
  16729. top:-50px;
  16730. }
  16731. .slide-animate.ng-enter.ng-enter-active {
  16732. top:0;
  16733. }
  16734. .slide-animate.ng-leave {
  16735. top:0;
  16736. }
  16737. .slide-animate.ng-leave.ng-leave-active {
  16738. top:50px;
  16739. }
  16740. </file>
  16741. <file name="scenario.js">
  16742. it('should load template1.html', function() {
  16743. expect(element('.doc-example-live [ng-include]').text()).
  16744. toMatch(/Content of template1.html/);
  16745. });
  16746. it('should load template2.html', function() {
  16747. select('template').option('1');
  16748. expect(element('.doc-example-live [ng-include]').text()).
  16749. toMatch(/Content of template2.html/);
  16750. });
  16751. it('should change to blank', function() {
  16752. select('template').option('');
  16753. expect(element('.doc-example-live [ng-include]')).toBe(undefined);
  16754. });
  16755. </file>
  16756. </example>
  16757. */
  16758. /**
  16759. * @ngdoc event
  16760. * @name ng.directive:ngInclude#$includeContentRequested
  16761. * @eventOf ng.directive:ngInclude
  16762. * @eventType emit on the scope ngInclude was declared in
  16763. * @description
  16764. * Emitted every time the ngInclude content is requested.
  16765. */
  16766. /**
  16767. * @ngdoc event
  16768. * @name ng.directive:ngInclude#$includeContentLoaded
  16769. * @eventOf ng.directive:ngInclude
  16770. * @eventType emit on the current ngInclude scope
  16771. * @description
  16772. * Emitted every time the ngInclude content is reloaded.
  16773. */
  16774. var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
  16775. function($http, $templateCache, $anchorScroll, $animate, $sce) {
  16776. return {
  16777. restrict: 'ECA',
  16778. priority: 400,
  16779. terminal: true,
  16780. transclude: 'element',
  16781. controller: angular.noop,
  16782. compile: function(element, attr) {
  16783. var srcExp = attr.ngInclude || attr.src,
  16784. onloadExp = attr.onload || '',
  16785. autoScrollExp = attr.autoscroll;
  16786. return function(scope, $element, $attr, ctrl, $transclude) {
  16787. var changeCounter = 0,
  16788. currentScope,
  16789. currentElement;
  16790. var cleanupLastIncludeContent = function() {
  16791. if (currentScope) {
  16792. currentScope.$destroy();
  16793. currentScope = null;
  16794. }
  16795. if(currentElement) {
  16796. $animate.leave(currentElement);
  16797. currentElement = null;
  16798. }
  16799. };
  16800. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  16801. var afterAnimation = function() {
  16802. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  16803. $anchorScroll();
  16804. }
  16805. };
  16806. var thisChangeId = ++changeCounter;
  16807. if (src) {
  16808. $http.get(src, {cache: $templateCache}).success(function(response) {
  16809. if (thisChangeId !== changeCounter) return;
  16810. var newScope = scope.$new();
  16811. ctrl.template = response;
  16812. // Note: This will also link all children of ng-include that were contained in the original
  16813. // html. If that content contains controllers, ... they could pollute/change the scope.
  16814. // However, using ng-include on an element with additional content does not make sense...
  16815. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  16816. // function is called before linking the content, which would apply child
  16817. // directives to non existing elements.
  16818. var clone = $transclude(newScope, function(clone) {
  16819. cleanupLastIncludeContent();
  16820. $animate.enter(clone, null, $element, afterAnimation);
  16821. });
  16822. currentScope = newScope;
  16823. currentElement = clone;
  16824. currentScope.$emit('$includeContentLoaded');
  16825. scope.$eval(onloadExp);
  16826. }).error(function() {
  16827. if (thisChangeId === changeCounter) cleanupLastIncludeContent();
  16828. });
  16829. scope.$emit('$includeContentRequested');
  16830. } else {
  16831. cleanupLastIncludeContent();
  16832. ctrl.template = null;
  16833. }
  16834. });
  16835. };
  16836. }
  16837. };
  16838. }];
  16839. // This directive is called during the $transclude call of the first `ngInclude` directive.
  16840. // It will replace and compile the content of the element with the loaded template.
  16841. // We need this directive so that the element content is already filled when
  16842. // the link function of another directive on the same element as ngInclude
  16843. // is called.
  16844. var ngIncludeFillContentDirective = ['$compile',
  16845. function($compile) {
  16846. return {
  16847. restrict: 'ECA',
  16848. priority: -400,
  16849. require: 'ngInclude',
  16850. link: function(scope, $element, $attr, ctrl) {
  16851. $element.html(ctrl.template);
  16852. $compile($element.contents())(scope);
  16853. }
  16854. };
  16855. }];
  16856. /**
  16857. * @ngdoc directive
  16858. * @name ng.directive:ngInit
  16859. * @restrict AC
  16860. *
  16861. * @description
  16862. * The `ngInit` directive allows you to evaluate an expression in the
  16863. * current scope.
  16864. *
  16865. * <div class="alert alert-error">
  16866. * The only appropriate use of `ngInit` is for aliasing special properties of
  16867. * {@link api/ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  16868. * should use {@link guide/controller controllers} rather than `ngInit`
  16869. * to initialize values on a scope.
  16870. * </div>
  16871. *
  16872. * @priority 450
  16873. *
  16874. * @element ANY
  16875. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  16876. *
  16877. * @example
  16878. <doc:example>
  16879. <doc:source>
  16880. <script>
  16881. function Ctrl($scope) {
  16882. $scope.list = [['a', 'b'], ['c', 'd']];
  16883. }
  16884. </script>
  16885. <div ng-controller="Ctrl">
  16886. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  16887. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  16888. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  16889. </div>
  16890. </div>
  16891. </div>
  16892. </doc:source>
  16893. <doc:scenario>
  16894. it('should alias index positions', function() {
  16895. expect(element('.example-init').text())
  16896. .toBe('list[ 0 ][ 0 ] = a;' +
  16897. 'list[ 0 ][ 1 ] = b;' +
  16898. 'list[ 1 ][ 0 ] = c;' +
  16899. 'list[ 1 ][ 1 ] = d;');
  16900. });
  16901. </doc:scenario>
  16902. </doc:example>
  16903. */
  16904. var ngInitDirective = ngDirective({
  16905. priority: 450,
  16906. compile: function() {
  16907. return {
  16908. pre: function(scope, element, attrs) {
  16909. scope.$eval(attrs.ngInit);
  16910. }
  16911. };
  16912. }
  16913. });
  16914. /**
  16915. * @ngdoc directive
  16916. * @name ng.directive:ngNonBindable
  16917. * @restrict AC
  16918. * @priority 1000
  16919. *
  16920. * @description
  16921. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  16922. * DOM element. This is useful if the element contains what appears to be Angular directives and
  16923. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  16924. * displays snippets of code, for instance.
  16925. *
  16926. * @element ANY
  16927. *
  16928. * @example
  16929. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  16930. * but the one wrapped in `ngNonBindable` is left alone.
  16931. *
  16932. * @example
  16933. <doc:example>
  16934. <doc:source>
  16935. <div>Normal: {{1 + 2}}</div>
  16936. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  16937. </doc:source>
  16938. <doc:scenario>
  16939. it('should check ng-non-bindable', function() {
  16940. expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
  16941. expect(using('.doc-example-live').element('div:last').text()).
  16942. toMatch(/1 \+ 2/);
  16943. });
  16944. </doc:scenario>
  16945. </doc:example>
  16946. */
  16947. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  16948. /**
  16949. * @ngdoc directive
  16950. * @name ng.directive:ngPluralize
  16951. * @restrict EA
  16952. *
  16953. * @description
  16954. * # Overview
  16955. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  16956. * These rules are bundled with angular.js, but can be overridden
  16957. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  16958. * by specifying the mappings between
  16959. * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
  16960. * plural categories} and the strings to be displayed.
  16961. *
  16962. * # Plural categories and explicit number rules
  16963. * There are two
  16964. * {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
  16965. * plural categories} in Angular's default en-US locale: "one" and "other".
  16966. *
  16967. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  16968. * any number that is not 1), an explicit number rule can only match one number. For example, the
  16969. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  16970. * and explicit number rules throughout the rest of this documentation.
  16971. *
  16972. * # Configuring ngPluralize
  16973. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  16974. * You can also provide an optional attribute, `offset`.
  16975. *
  16976. * The value of the `count` attribute can be either a string or an {@link guide/expression
  16977. * Angular expression}; these are evaluated on the current scope for its bound value.
  16978. *
  16979. * The `when` attribute specifies the mappings between plural categories and the actual
  16980. * string to be displayed. The value of the attribute should be a JSON object.
  16981. *
  16982. * The following example shows how to configure ngPluralize:
  16983. *
  16984. * <pre>
  16985. * <ng-pluralize count="personCount"
  16986. when="{'0': 'Nobody is viewing.',
  16987. * 'one': '1 person is viewing.',
  16988. * 'other': '{} people are viewing.'}">
  16989. * </ng-pluralize>
  16990. *</pre>
  16991. *
  16992. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  16993. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  16994. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  16995. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  16996. * show "a dozen people are viewing".
  16997. *
  16998. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  16999. * into pluralized strings. In the previous example, Angular will replace `{}` with
  17000. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  17001. * for <span ng-non-bindable>{{numberExpression}}</span>.
  17002. *
  17003. * # Configuring ngPluralize with offset
  17004. * The `offset` attribute allows further customization of pluralized text, which can result in
  17005. * a better user experience. For example, instead of the message "4 people are viewing this document",
  17006. * you might display "John, Kate and 2 others are viewing this document".
  17007. * The offset attribute allows you to offset a number by any desired value.
  17008. * Let's take a look at an example:
  17009. *
  17010. * <pre>
  17011. * <ng-pluralize count="personCount" offset=2
  17012. * when="{'0': 'Nobody is viewing.',
  17013. * '1': '{{person1}} is viewing.',
  17014. * '2': '{{person1}} and {{person2}} are viewing.',
  17015. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  17016. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  17017. * </ng-pluralize>
  17018. * </pre>
  17019. *
  17020. * Notice that we are still using two plural categories(one, other), but we added
  17021. * three explicit number rules 0, 1 and 2.
  17022. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  17023. * When three people view the document, no explicit number rule is found, so
  17024. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  17025. * In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
  17026. * is shown.
  17027. *
  17028. * Note that when you specify offsets, you must provide explicit number rules for
  17029. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  17030. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  17031. * plural categories "one" and "other".
  17032. *
  17033. * @param {string|expression} count The variable to be bounded to.
  17034. * @param {string} when The mapping between plural category to its corresponding strings.
  17035. * @param {number=} offset Offset to deduct from the total number.
  17036. *
  17037. * @example
  17038. <doc:example>
  17039. <doc:source>
  17040. <script>
  17041. function Ctrl($scope) {
  17042. $scope.person1 = 'Igor';
  17043. $scope.person2 = 'Misko';
  17044. $scope.personCount = 1;
  17045. }
  17046. </script>
  17047. <div ng-controller="Ctrl">
  17048. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  17049. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  17050. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  17051. <!--- Example with simple pluralization rules for en locale --->
  17052. Without Offset:
  17053. <ng-pluralize count="personCount"
  17054. when="{'0': 'Nobody is viewing.',
  17055. 'one': '1 person is viewing.',
  17056. 'other': '{} people are viewing.'}">
  17057. </ng-pluralize><br>
  17058. <!--- Example with offset --->
  17059. With Offset(2):
  17060. <ng-pluralize count="personCount" offset=2
  17061. when="{'0': 'Nobody is viewing.',
  17062. '1': '{{person1}} is viewing.',
  17063. '2': '{{person1}} and {{person2}} are viewing.',
  17064. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  17065. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  17066. </ng-pluralize>
  17067. </div>
  17068. </doc:source>
  17069. <doc:scenario>
  17070. it('should show correct pluralized string', function() {
  17071. expect(element('.doc-example-live ng-pluralize:first').text()).
  17072. toBe('1 person is viewing.');
  17073. expect(element('.doc-example-live ng-pluralize:last').text()).
  17074. toBe('Igor is viewing.');
  17075. using('.doc-example-live').input('personCount').enter('0');
  17076. expect(element('.doc-example-live ng-pluralize:first').text()).
  17077. toBe('Nobody is viewing.');
  17078. expect(element('.doc-example-live ng-pluralize:last').text()).
  17079. toBe('Nobody is viewing.');
  17080. using('.doc-example-live').input('personCount').enter('2');
  17081. expect(element('.doc-example-live ng-pluralize:first').text()).
  17082. toBe('2 people are viewing.');
  17083. expect(element('.doc-example-live ng-pluralize:last').text()).
  17084. toBe('Igor and Misko are viewing.');
  17085. using('.doc-example-live').input('personCount').enter('3');
  17086. expect(element('.doc-example-live ng-pluralize:first').text()).
  17087. toBe('3 people are viewing.');
  17088. expect(element('.doc-example-live ng-pluralize:last').text()).
  17089. toBe('Igor, Misko and one other person are viewing.');
  17090. using('.doc-example-live').input('personCount').enter('4');
  17091. expect(element('.doc-example-live ng-pluralize:first').text()).
  17092. toBe('4 people are viewing.');
  17093. expect(element('.doc-example-live ng-pluralize:last').text()).
  17094. toBe('Igor, Misko and 2 other people are viewing.');
  17095. });
  17096. it('should show data-binded names', function() {
  17097. using('.doc-example-live').input('personCount').enter('4');
  17098. expect(element('.doc-example-live ng-pluralize:last').text()).
  17099. toBe('Igor, Misko and 2 other people are viewing.');
  17100. using('.doc-example-live').input('person1').enter('Di');
  17101. using('.doc-example-live').input('person2').enter('Vojta');
  17102. expect(element('.doc-example-live ng-pluralize:last').text()).
  17103. toBe('Di, Vojta and 2 other people are viewing.');
  17104. });
  17105. </doc:scenario>
  17106. </doc:example>
  17107. */
  17108. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  17109. var BRACE = /{}/g;
  17110. return {
  17111. restrict: 'EA',
  17112. link: function(scope, element, attr) {
  17113. var numberExp = attr.count,
  17114. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  17115. offset = attr.offset || 0,
  17116. whens = scope.$eval(whenExp) || {},
  17117. whensExpFns = {},
  17118. startSymbol = $interpolate.startSymbol(),
  17119. endSymbol = $interpolate.endSymbol(),
  17120. isWhen = /^when(Minus)?(.+)$/;
  17121. forEach(attr, function(expression, attributeName) {
  17122. if (isWhen.test(attributeName)) {
  17123. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  17124. element.attr(attr.$attr[attributeName]);
  17125. }
  17126. });
  17127. forEach(whens, function(expression, key) {
  17128. whensExpFns[key] =
  17129. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  17130. offset + endSymbol));
  17131. });
  17132. scope.$watch(function ngPluralizeWatch() {
  17133. var value = parseFloat(scope.$eval(numberExp));
  17134. if (!isNaN(value)) {
  17135. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  17136. //check it against pluralization rules in $locale service
  17137. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  17138. return whensExpFns[value](scope, element, true);
  17139. } else {
  17140. return '';
  17141. }
  17142. }, function ngPluralizeWatchAction(newVal) {
  17143. element.text(newVal);
  17144. });
  17145. }
  17146. };
  17147. }];
  17148. /**
  17149. * @ngdoc directive
  17150. * @name ng.directive:ngRepeat
  17151. *
  17152. * @description
  17153. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  17154. * instance gets its own scope, where the given loop variable is set to the current collection item,
  17155. * and `$index` is set to the item index or key.
  17156. *
  17157. * Special properties are exposed on the local scope of each template instance, including:
  17158. *
  17159. * | Variable | Type | Details |
  17160. * |-----------|-----------------|-----------------------------------------------------------------------------|
  17161. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  17162. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  17163. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  17164. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  17165. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  17166. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  17167. *
  17168. * Creating aliases for these properties is possible with {@link api/ng.directive:ngInit `ngInit`}.
  17169. * This may be useful when, for instance, nesting ngRepeats.
  17170. *
  17171. * # Special repeat start and end points
  17172. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  17173. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  17174. * 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)
  17175. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  17176. *
  17177. * The example below makes use of this feature:
  17178. * <pre>
  17179. * <header ng-repeat-start="item in items">
  17180. * Header {{ item }}
  17181. * </header>
  17182. * <div class="body">
  17183. * Body {{ item }}
  17184. * </div>
  17185. * <footer ng-repeat-end>
  17186. * Footer {{ item }}
  17187. * </footer>
  17188. * </pre>
  17189. *
  17190. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  17191. * <pre>
  17192. * <header>
  17193. * Header A
  17194. * </header>
  17195. * <div class="body">
  17196. * Body A
  17197. * </div>
  17198. * <footer>
  17199. * Footer A
  17200. * </footer>
  17201. * <header>
  17202. * Header B
  17203. * </header>
  17204. * <div class="body">
  17205. * Body B
  17206. * </div>
  17207. * <footer>
  17208. * Footer B
  17209. * </footer>
  17210. * </pre>
  17211. *
  17212. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  17213. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  17214. *
  17215. * @animations
  17216. * enter - when a new item is added to the list or when an item is revealed after a filter
  17217. * leave - when an item is removed from the list or when an item is filtered out
  17218. * move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  17219. *
  17220. * @element ANY
  17221. * @scope
  17222. * @priority 1000
  17223. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  17224. * formats are currently supported:
  17225. *
  17226. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  17227. * is a scope expression giving the collection to enumerate.
  17228. *
  17229. * For example: `album in artist.albums`.
  17230. *
  17231. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  17232. * and `expression` is the scope expression giving the collection to enumerate.
  17233. *
  17234. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  17235. *
  17236. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  17237. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  17238. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  17239. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  17240. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  17241. * before specifying a tracking expression.
  17242. *
  17243. * For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements
  17244. * will be associated by item identity in the array.
  17245. *
  17246. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  17247. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  17248. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  17249. * element in the same way in the DOM.
  17250. *
  17251. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  17252. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  17253. * property is same.
  17254. *
  17255. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  17256. * to items in conjunction with a tracking expression.
  17257. *
  17258. * @example
  17259. * This example initializes the scope to a list of names and
  17260. * then uses `ngRepeat` to display every person:
  17261. <example animations="true">
  17262. <file name="index.html">
  17263. <div ng-init="friends = [
  17264. {name:'John', age:25, gender:'boy'},
  17265. {name:'Jessie', age:30, gender:'girl'},
  17266. {name:'Johanna', age:28, gender:'girl'},
  17267. {name:'Joy', age:15, gender:'girl'},
  17268. {name:'Mary', age:28, gender:'girl'},
  17269. {name:'Peter', age:95, gender:'boy'},
  17270. {name:'Sebastian', age:50, gender:'boy'},
  17271. {name:'Erika', age:27, gender:'girl'},
  17272. {name:'Patrick', age:40, gender:'boy'},
  17273. {name:'Samantha', age:60, gender:'girl'}
  17274. ]">
  17275. I have {{friends.length}} friends. They are:
  17276. <input type="search" ng-model="q" placeholder="filter friends..." />
  17277. <ul class="example-animate-container">
  17278. <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
  17279. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  17280. </li>
  17281. </ul>
  17282. </div>
  17283. </file>
  17284. <file name="animations.css">
  17285. .example-animate-container {
  17286. background:white;
  17287. border:1px solid black;
  17288. list-style:none;
  17289. margin:0;
  17290. padding:0 10px;
  17291. }
  17292. .animate-repeat {
  17293. line-height:40px;
  17294. list-style:none;
  17295. box-sizing:border-box;
  17296. }
  17297. .animate-repeat.ng-move,
  17298. .animate-repeat.ng-enter,
  17299. .animate-repeat.ng-leave {
  17300. -webkit-transition:all linear 0.5s;
  17301. transition:all linear 0.5s;
  17302. }
  17303. .animate-repeat.ng-leave.ng-leave-active,
  17304. .animate-repeat.ng-move,
  17305. .animate-repeat.ng-enter {
  17306. opacity:0;
  17307. max-height:0;
  17308. }
  17309. .animate-repeat.ng-leave,
  17310. .animate-repeat.ng-move.ng-move-active,
  17311. .animate-repeat.ng-enter.ng-enter-active {
  17312. opacity:1;
  17313. max-height:40px;
  17314. }
  17315. </file>
  17316. <file name="scenario.js">
  17317. it('should render initial data set', function() {
  17318. var r = using('.doc-example-live').repeater('ul li');
  17319. expect(r.count()).toBe(10);
  17320. expect(r.row(0)).toEqual(["1","John","25"]);
  17321. expect(r.row(1)).toEqual(["2","Jessie","30"]);
  17322. expect(r.row(9)).toEqual(["10","Samantha","60"]);
  17323. expect(binding('friends.length')).toBe("10");
  17324. });
  17325. it('should update repeater when filter predicate changes', function() {
  17326. var r = using('.doc-example-live').repeater('ul li');
  17327. expect(r.count()).toBe(10);
  17328. input('q').enter('ma');
  17329. expect(r.count()).toBe(2);
  17330. expect(r.row(0)).toEqual(["1","Mary","28"]);
  17331. expect(r.row(1)).toEqual(["2","Samantha","60"]);
  17332. });
  17333. </file>
  17334. </example>
  17335. */
  17336. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  17337. var NG_REMOVED = '$$NG_REMOVED';
  17338. var ngRepeatMinErr = minErr('ngRepeat');
  17339. return {
  17340. transclude: 'element',
  17341. priority: 1000,
  17342. terminal: true,
  17343. $$tlb: true,
  17344. link: function($scope, $element, $attr, ctrl, $transclude){
  17345. var expression = $attr.ngRepeat;
  17346. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
  17347. trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
  17348. lhs, rhs, valueIdentifier, keyIdentifier,
  17349. hashFnLocals = {$id: hashKey};
  17350. if (!match) {
  17351. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  17352. expression);
  17353. }
  17354. lhs = match[1];
  17355. rhs = match[2];
  17356. trackByExp = match[3];
  17357. if (trackByExp) {
  17358. trackByExpGetter = $parse(trackByExp);
  17359. trackByIdExpFn = function(key, value, index) {
  17360. // assign key, value, and $index to the locals so that they can be used in hash functions
  17361. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  17362. hashFnLocals[valueIdentifier] = value;
  17363. hashFnLocals.$index = index;
  17364. return trackByExpGetter($scope, hashFnLocals);
  17365. };
  17366. } else {
  17367. trackByIdArrayFn = function(key, value) {
  17368. return hashKey(value);
  17369. };
  17370. trackByIdObjFn = function(key) {
  17371. return key;
  17372. };
  17373. }
  17374. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  17375. if (!match) {
  17376. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  17377. lhs);
  17378. }
  17379. valueIdentifier = match[3] || match[1];
  17380. keyIdentifier = match[2];
  17381. // Store a list of elements from previous run. This is a hash where key is the item from the
  17382. // iterator, and the value is objects with following properties.
  17383. // - scope: bound scope
  17384. // - element: previous element.
  17385. // - index: position
  17386. var lastBlockMap = {};
  17387. //watch props
  17388. $scope.$watchCollection(rhs, function ngRepeatAction(collection){
  17389. var index, length,
  17390. previousNode = $element[0], // current position of the node
  17391. nextNode,
  17392. // Same as lastBlockMap but it has the current state. It will become the
  17393. // lastBlockMap on the next iteration.
  17394. nextBlockMap = {},
  17395. arrayLength,
  17396. childScope,
  17397. key, value, // key/value of iteration
  17398. trackById,
  17399. trackByIdFn,
  17400. collectionKeys,
  17401. block, // last object information {scope, element, id}
  17402. nextBlockOrder = [],
  17403. elementsToRemove;
  17404. if (isArrayLike(collection)) {
  17405. collectionKeys = collection;
  17406. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  17407. } else {
  17408. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  17409. // if object, extract keys, sort them and use to determine order of iteration over obj props
  17410. collectionKeys = [];
  17411. for (key in collection) {
  17412. if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
  17413. collectionKeys.push(key);
  17414. }
  17415. }
  17416. collectionKeys.sort();
  17417. }
  17418. arrayLength = collectionKeys.length;
  17419. // locate existing items
  17420. length = nextBlockOrder.length = collectionKeys.length;
  17421. for(index = 0; index < length; index++) {
  17422. key = (collection === collectionKeys) ? index : collectionKeys[index];
  17423. value = collection[key];
  17424. trackById = trackByIdFn(key, value, index);
  17425. assertNotHasOwnProperty(trackById, '`track by` id');
  17426. if(lastBlockMap.hasOwnProperty(trackById)) {
  17427. block = lastBlockMap[trackById];
  17428. delete lastBlockMap[trackById];
  17429. nextBlockMap[trackById] = block;
  17430. nextBlockOrder[index] = block;
  17431. } else if (nextBlockMap.hasOwnProperty(trackById)) {
  17432. // restore lastBlockMap
  17433. forEach(nextBlockOrder, function(block) {
  17434. if (block && block.scope) lastBlockMap[block.id] = block;
  17435. });
  17436. // This is a duplicate and we need to throw an error
  17437. throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
  17438. expression, trackById);
  17439. } else {
  17440. // new never before seen block
  17441. nextBlockOrder[index] = { id: trackById };
  17442. nextBlockMap[trackById] = false;
  17443. }
  17444. }
  17445. // remove existing items
  17446. for (key in lastBlockMap) {
  17447. // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
  17448. if (lastBlockMap.hasOwnProperty(key)) {
  17449. block = lastBlockMap[key];
  17450. elementsToRemove = getBlockElements(block.clone);
  17451. $animate.leave(elementsToRemove);
  17452. forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
  17453. block.scope.$destroy();
  17454. }
  17455. }
  17456. // we are not using forEach for perf reasons (trying to avoid #call)
  17457. for (index = 0, length = collectionKeys.length; index < length; index++) {
  17458. key = (collection === collectionKeys) ? index : collectionKeys[index];
  17459. value = collection[key];
  17460. block = nextBlockOrder[index];
  17461. if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
  17462. if (block.scope) {
  17463. // if we have already seen this object, then we need to reuse the
  17464. // associated scope/element
  17465. childScope = block.scope;
  17466. nextNode = previousNode;
  17467. do {
  17468. nextNode = nextNode.nextSibling;
  17469. } while(nextNode && nextNode[NG_REMOVED]);
  17470. if (getBlockStart(block) != nextNode) {
  17471. // existing item which got moved
  17472. $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
  17473. }
  17474. previousNode = getBlockEnd(block);
  17475. } else {
  17476. // new item which we don't know about
  17477. childScope = $scope.$new();
  17478. }
  17479. childScope[valueIdentifier] = value;
  17480. if (keyIdentifier) childScope[keyIdentifier] = key;
  17481. childScope.$index = index;
  17482. childScope.$first = (index === 0);
  17483. childScope.$last = (index === (arrayLength - 1));
  17484. childScope.$middle = !(childScope.$first || childScope.$last);
  17485. // jshint bitwise: false
  17486. childScope.$odd = !(childScope.$even = (index&1) === 0);
  17487. // jshint bitwise: true
  17488. if (!block.scope) {
  17489. $transclude(childScope, function(clone) {
  17490. clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
  17491. $animate.enter(clone, null, jqLite(previousNode));
  17492. previousNode = clone;
  17493. block.scope = childScope;
  17494. // Note: We only need the first/last node of the cloned nodes.
  17495. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  17496. // by a directive with templateUrl when it's template arrives.
  17497. block.clone = clone;
  17498. nextBlockMap[block.id] = block;
  17499. });
  17500. }
  17501. }
  17502. lastBlockMap = nextBlockMap;
  17503. });
  17504. }
  17505. };
  17506. function getBlockStart(block) {
  17507. return block.clone[0];
  17508. }
  17509. function getBlockEnd(block) {
  17510. return block.clone[block.clone.length - 1];
  17511. }
  17512. }];
  17513. /**
  17514. * @ngdoc directive
  17515. * @name ng.directive:ngShow
  17516. *
  17517. * @description
  17518. * The `ngShow` directive shows or hides the given HTML element based on the expression
  17519. * provided to the ngShow attribute. The element is shown or hidden by removing or adding
  17520. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  17521. * in AngularJS and sets the display style to none (using an !important flag).
  17522. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  17523. *
  17524. * <pre>
  17525. * <!-- when $scope.myValue is truthy (element is visible) -->
  17526. * <div ng-show="myValue"></div>
  17527. *
  17528. * <!-- when $scope.myValue is falsy (element is hidden) -->
  17529. * <div ng-show="myValue" class="ng-hide"></div>
  17530. * </pre>
  17531. *
  17532. * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute
  17533. * on the element causing it to become hidden. When true, the ng-hide CSS class is removed
  17534. * from the element causing the element not to appear hidden.
  17535. *
  17536. * ## Why is !important used?
  17537. *
  17538. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  17539. * can be easily overridden by heavier selectors. For example, something as simple
  17540. * as changing the display style on a HTML list item would make hidden elements appear visible.
  17541. * This also becomes a bigger issue when dealing with CSS frameworks.
  17542. *
  17543. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  17544. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  17545. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  17546. *
  17547. * ### Overriding .ng-hide
  17548. *
  17549. * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
  17550. * restating the styles for the .ng-hide class in CSS:
  17551. * <pre>
  17552. * .ng-hide {
  17553. * //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
  17554. * display:block!important;
  17555. *
  17556. * //this is just another form of hiding an element
  17557. * position:absolute;
  17558. * top:-9999px;
  17559. * left:-9999px;
  17560. * }
  17561. * </pre>
  17562. *
  17563. * Just remember to include the important flag so the CSS override will function.
  17564. *
  17565. * ## A note about animations with ngShow
  17566. *
  17567. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  17568. * is true and false. This system works like the animation system present with ngClass except that
  17569. * you must also include the !important flag to override the display property
  17570. * so that you can perform an animation when the element is hidden during the time of the animation.
  17571. *
  17572. * <pre>
  17573. * //
  17574. * //a working example can be found at the bottom of this page
  17575. * //
  17576. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  17577. * transition:0.5s linear all;
  17578. * display:block!important;
  17579. * }
  17580. *
  17581. * .my-element.ng-hide-add { ... }
  17582. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  17583. * .my-element.ng-hide-remove { ... }
  17584. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  17585. * </pre>
  17586. *
  17587. * @animations
  17588. * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
  17589. * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
  17590. *
  17591. * @element ANY
  17592. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  17593. * then the element is shown or hidden respectively.
  17594. *
  17595. * @example
  17596. <example animations="true">
  17597. <file name="index.html">
  17598. Click me: <input type="checkbox" ng-model="checked"><br/>
  17599. <div>
  17600. Show:
  17601. <div class="check-element animate-show" ng-show="checked">
  17602. <span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
  17603. </div>
  17604. </div>
  17605. <div>
  17606. Hide:
  17607. <div class="check-element animate-show" ng-hide="checked">
  17608. <span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
  17609. </div>
  17610. </div>
  17611. </file>
  17612. <file name="animations.css">
  17613. .animate-show {
  17614. -webkit-transition:all linear 0.5s;
  17615. transition:all linear 0.5s;
  17616. line-height:20px;
  17617. opacity:1;
  17618. padding:10px;
  17619. border:1px solid black;
  17620. background:white;
  17621. }
  17622. .animate-show.ng-hide-add,
  17623. .animate-show.ng-hide-remove {
  17624. display:block!important;
  17625. }
  17626. .animate-show.ng-hide {
  17627. line-height:0;
  17628. opacity:0;
  17629. padding:0 10px;
  17630. }
  17631. .check-element {
  17632. padding:10px;
  17633. border:1px solid black;
  17634. background:white;
  17635. }
  17636. </file>
  17637. <file name="scenario.js">
  17638. it('should check ng-show / ng-hide', function() {
  17639. expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
  17640. expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
  17641. input('checked').check();
  17642. expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
  17643. expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
  17644. });
  17645. </file>
  17646. </example>
  17647. */
  17648. var ngShowDirective = ['$animate', function($animate) {
  17649. return function(scope, element, attr) {
  17650. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  17651. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
  17652. });
  17653. };
  17654. }];
  17655. /**
  17656. * @ngdoc directive
  17657. * @name ng.directive:ngHide
  17658. *
  17659. * @description
  17660. * The `ngHide` directive shows or hides the given HTML element based on the expression
  17661. * provided to the ngHide attribute. The element is shown or hidden by removing or adding
  17662. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  17663. * in AngularJS and sets the display style to none (using an !important flag).
  17664. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  17665. *
  17666. * <pre>
  17667. * <!-- when $scope.myValue is truthy (element is hidden) -->
  17668. * <div ng-hide="myValue"></div>
  17669. *
  17670. * <!-- when $scope.myValue is falsy (element is visible) -->
  17671. * <div ng-hide="myValue" class="ng-hide"></div>
  17672. * </pre>
  17673. *
  17674. * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute
  17675. * on the element causing it to become hidden. When false, the ng-hide CSS class is removed
  17676. * from the element causing the element not to appear hidden.
  17677. *
  17678. * ## Why is !important used?
  17679. *
  17680. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  17681. * can be easily overridden by heavier selectors. For example, something as simple
  17682. * as changing the display style on a HTML list item would make hidden elements appear visible.
  17683. * This also becomes a bigger issue when dealing with CSS frameworks.
  17684. *
  17685. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  17686. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  17687. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  17688. *
  17689. * ### Overriding .ng-hide
  17690. *
  17691. * If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
  17692. * restating the styles for the .ng-hide class in CSS:
  17693. * <pre>
  17694. * .ng-hide {
  17695. * //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
  17696. * display:block!important;
  17697. *
  17698. * //this is just another form of hiding an element
  17699. * position:absolute;
  17700. * top:-9999px;
  17701. * left:-9999px;
  17702. * }
  17703. * </pre>
  17704. *
  17705. * Just remember to include the important flag so the CSS override will function.
  17706. *
  17707. * ## A note about animations with ngHide
  17708. *
  17709. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  17710. * is true and false. This system works like the animation system present with ngClass, except that
  17711. * you must also include the !important flag to override the display property so
  17712. * that you can perform an animation when the element is hidden during the time of the animation.
  17713. *
  17714. * <pre>
  17715. * //
  17716. * //a working example can be found at the bottom of this page
  17717. * //
  17718. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  17719. * transition:0.5s linear all;
  17720. * display:block!important;
  17721. * }
  17722. *
  17723. * .my-element.ng-hide-add { ... }
  17724. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  17725. * .my-element.ng-hide-remove { ... }
  17726. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  17727. * </pre>
  17728. *
  17729. * @animations
  17730. * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
  17731. * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
  17732. *
  17733. * @element ANY
  17734. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  17735. * the element is shown or hidden respectively.
  17736. *
  17737. * @example
  17738. <example animations="true">
  17739. <file name="index.html">
  17740. Click me: <input type="checkbox" ng-model="checked"><br/>
  17741. <div>
  17742. Show:
  17743. <div class="check-element animate-hide" ng-show="checked">
  17744. <span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
  17745. </div>
  17746. </div>
  17747. <div>
  17748. Hide:
  17749. <div class="check-element animate-hide" ng-hide="checked">
  17750. <span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
  17751. </div>
  17752. </div>
  17753. </file>
  17754. <file name="animations.css">
  17755. .animate-hide {
  17756. -webkit-transition:all linear 0.5s;
  17757. transition:all linear 0.5s;
  17758. line-height:20px;
  17759. opacity:1;
  17760. padding:10px;
  17761. border:1px solid black;
  17762. background:white;
  17763. }
  17764. .animate-hide.ng-hide-add,
  17765. .animate-hide.ng-hide-remove {
  17766. display:block!important;
  17767. }
  17768. .animate-hide.ng-hide {
  17769. line-height:0;
  17770. opacity:0;
  17771. padding:0 10px;
  17772. }
  17773. .check-element {
  17774. padding:10px;
  17775. border:1px solid black;
  17776. background:white;
  17777. }
  17778. </file>
  17779. <file name="scenario.js">
  17780. it('should check ng-show / ng-hide', function() {
  17781. expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1);
  17782. expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1);
  17783. input('checked').check();
  17784. expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1);
  17785. expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1);
  17786. });
  17787. </file>
  17788. </example>
  17789. */
  17790. var ngHideDirective = ['$animate', function($animate) {
  17791. return function(scope, element, attr) {
  17792. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  17793. $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
  17794. });
  17795. };
  17796. }];
  17797. /**
  17798. * @ngdoc directive
  17799. * @name ng.directive:ngStyle
  17800. * @restrict AC
  17801. *
  17802. * @description
  17803. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  17804. *
  17805. * @element ANY
  17806. * @param {expression} ngStyle {@link guide/expression Expression} which evals to an
  17807. * object whose keys are CSS style names and values are corresponding values for those CSS
  17808. * keys.
  17809. *
  17810. * @example
  17811. <example>
  17812. <file name="index.html">
  17813. <input type="button" value="set" ng-click="myStyle={color:'red'}">
  17814. <input type="button" value="clear" ng-click="myStyle={}">
  17815. <br/>
  17816. <span ng-style="myStyle">Sample Text</span>
  17817. <pre>myStyle={{myStyle}}</pre>
  17818. </file>
  17819. <file name="style.css">
  17820. span {
  17821. color: black;
  17822. }
  17823. </file>
  17824. <file name="scenario.js">
  17825. it('should check ng-style', function() {
  17826. expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
  17827. element('.doc-example-live :button[value=set]').click();
  17828. expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
  17829. element('.doc-example-live :button[value=clear]').click();
  17830. expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
  17831. });
  17832. </file>
  17833. </example>
  17834. */
  17835. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  17836. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  17837. if (oldStyles && (newStyles !== oldStyles)) {
  17838. forEach(oldStyles, function(val, style) { element.css(style, '');});
  17839. }
  17840. if (newStyles) element.css(newStyles);
  17841. }, true);
  17842. });
  17843. /**
  17844. * @ngdoc directive
  17845. * @name ng.directive:ngSwitch
  17846. * @restrict EA
  17847. *
  17848. * @description
  17849. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  17850. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  17851. * as specified in the template.
  17852. *
  17853. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  17854. * from the template cache), `ngSwitch` simply choses one of the nested elements and makes it visible based on which element
  17855. * matches the value obtained from the evaluated expression. In other words, you define a container element
  17856. * (where you place the directive), place an expression on the **`on="..."` attribute**
  17857. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  17858. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  17859. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  17860. * attribute is displayed.
  17861. *
  17862. * <div class="alert alert-info">
  17863. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  17864. * as literal string values to match against.
  17865. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  17866. * value of the expression `$scope.someVal`.
  17867. * </div>
  17868. * @animations
  17869. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  17870. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  17871. *
  17872. * @usage
  17873. * <ANY ng-switch="expression">
  17874. * <ANY ng-switch-when="matchValue1">...</ANY>
  17875. * <ANY ng-switch-when="matchValue2">...</ANY>
  17876. * <ANY ng-switch-default>...</ANY>
  17877. * </ANY>
  17878. *
  17879. *
  17880. * @scope
  17881. * @priority 800
  17882. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  17883. * @paramDescription
  17884. * On child elements add:
  17885. *
  17886. * * `ngSwitchWhen`: the case statement to match against. If match then this
  17887. * case will be displayed. If the same match appears multiple times, all the
  17888. * elements will be displayed.
  17889. * * `ngSwitchDefault`: the default case when no other case match. If there
  17890. * are multiple default cases, all of them will be displayed when no other
  17891. * case match.
  17892. *
  17893. *
  17894. * @example
  17895. <example animations="true">
  17896. <file name="index.html">
  17897. <div ng-controller="Ctrl">
  17898. <select ng-model="selection" ng-options="item for item in items">
  17899. </select>
  17900. <tt>selection={{selection}}</tt>
  17901. <hr/>
  17902. <div class="animate-switch-container"
  17903. ng-switch on="selection">
  17904. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  17905. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  17906. <div class="animate-switch" ng-switch-default>default</div>
  17907. </div>
  17908. </div>
  17909. </file>
  17910. <file name="script.js">
  17911. function Ctrl($scope) {
  17912. $scope.items = ['settings', 'home', 'other'];
  17913. $scope.selection = $scope.items[0];
  17914. }
  17915. </file>
  17916. <file name="animations.css">
  17917. .animate-switch-container {
  17918. position:relative;
  17919. background:white;
  17920. border:1px solid black;
  17921. height:40px;
  17922. overflow:hidden;
  17923. }
  17924. .animate-switch {
  17925. padding:10px;
  17926. }
  17927. .animate-switch.ng-animate {
  17928. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17929. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17930. position:absolute;
  17931. top:0;
  17932. left:0;
  17933. right:0;
  17934. bottom:0;
  17935. }
  17936. .animate-switch.ng-leave.ng-leave-active,
  17937. .animate-switch.ng-enter {
  17938. top:-50px;
  17939. }
  17940. .animate-switch.ng-leave,
  17941. .animate-switch.ng-enter.ng-enter-active {
  17942. top:0;
  17943. }
  17944. </file>
  17945. <file name="scenario.js">
  17946. it('should start in settings', function() {
  17947. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
  17948. });
  17949. it('should change to home', function() {
  17950. select('selection').option('home');
  17951. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
  17952. });
  17953. it('should select default', function() {
  17954. select('selection').option('other');
  17955. expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
  17956. });
  17957. </file>
  17958. </example>
  17959. */
  17960. var ngSwitchDirective = ['$animate', function($animate) {
  17961. return {
  17962. restrict: 'EA',
  17963. require: 'ngSwitch',
  17964. // asks for $scope to fool the BC controller module
  17965. controller: ['$scope', function ngSwitchController() {
  17966. this.cases = {};
  17967. }],
  17968. link: function(scope, element, attr, ngSwitchController) {
  17969. var watchExpr = attr.ngSwitch || attr.on,
  17970. selectedTranscludes,
  17971. selectedElements,
  17972. selectedScopes = [];
  17973. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  17974. for (var i= 0, ii=selectedScopes.length; i<ii; i++) {
  17975. selectedScopes[i].$destroy();
  17976. $animate.leave(selectedElements[i]);
  17977. }
  17978. selectedElements = [];
  17979. selectedScopes = [];
  17980. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  17981. scope.$eval(attr.change);
  17982. forEach(selectedTranscludes, function(selectedTransclude) {
  17983. var selectedScope = scope.$new();
  17984. selectedScopes.push(selectedScope);
  17985. selectedTransclude.transclude(selectedScope, function(caseElement) {
  17986. var anchor = selectedTransclude.element;
  17987. selectedElements.push(caseElement);
  17988. $animate.enter(caseElement, anchor.parent(), anchor);
  17989. });
  17990. });
  17991. }
  17992. });
  17993. }
  17994. };
  17995. }];
  17996. var ngSwitchWhenDirective = ngDirective({
  17997. transclude: 'element',
  17998. priority: 800,
  17999. require: '^ngSwitch',
  18000. link: function(scope, element, attrs, ctrl, $transclude) {
  18001. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  18002. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  18003. }
  18004. });
  18005. var ngSwitchDefaultDirective = ngDirective({
  18006. transclude: 'element',
  18007. priority: 800,
  18008. require: '^ngSwitch',
  18009. link: function(scope, element, attr, ctrl, $transclude) {
  18010. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  18011. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  18012. }
  18013. });
  18014. /**
  18015. * @ngdoc directive
  18016. * @name ng.directive:ngTransclude
  18017. * @restrict AC
  18018. *
  18019. * @description
  18020. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  18021. *
  18022. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  18023. *
  18024. * @element ANY
  18025. *
  18026. * @example
  18027. <doc:example module="transclude">
  18028. <doc:source>
  18029. <script>
  18030. function Ctrl($scope) {
  18031. $scope.title = 'Lorem Ipsum';
  18032. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  18033. }
  18034. angular.module('transclude', [])
  18035. .directive('pane', function(){
  18036. return {
  18037. restrict: 'E',
  18038. transclude: true,
  18039. scope: { title:'@' },
  18040. template: '<div style="border: 1px solid black;">' +
  18041. '<div style="background-color: gray">{{title}}</div>' +
  18042. '<div ng-transclude></div>' +
  18043. '</div>'
  18044. };
  18045. });
  18046. </script>
  18047. <div ng-controller="Ctrl">
  18048. <input ng-model="title"><br>
  18049. <textarea ng-model="text"></textarea> <br/>
  18050. <pane title="{{title}}">{{text}}</pane>
  18051. </div>
  18052. </doc:source>
  18053. <doc:scenario>
  18054. it('should have transcluded', function() {
  18055. input('title').enter('TITLE');
  18056. input('text').enter('TEXT');
  18057. expect(binding('title')).toEqual('TITLE');
  18058. expect(binding('text')).toEqual('TEXT');
  18059. });
  18060. </doc:scenario>
  18061. </doc:example>
  18062. *
  18063. */
  18064. var ngTranscludeDirective = ngDirective({
  18065. controller: ['$element', '$transclude', function($element, $transclude) {
  18066. if (!$transclude) {
  18067. throw minErr('ngTransclude')('orphan',
  18068. 'Illegal use of ngTransclude directive in the template! ' +
  18069. 'No parent directive that requires a transclusion found. ' +
  18070. 'Element: {0}',
  18071. startingTag($element));
  18072. }
  18073. // remember the transclusion fn but call it during linking so that we don't process transclusion before directives on
  18074. // the parent element even when the transclusion replaces the current element. (we can't use priority here because
  18075. // that applies only to compile fns and not controllers
  18076. this.$transclude = $transclude;
  18077. }],
  18078. link: function($scope, $element, $attrs, controller) {
  18079. controller.$transclude(function(clone) {
  18080. $element.empty();
  18081. $element.append(clone);
  18082. });
  18083. }
  18084. });
  18085. /**
  18086. * @ngdoc directive
  18087. * @name ng.directive:script
  18088. * @restrict E
  18089. *
  18090. * @description
  18091. * Load the content of a `<script>` element into {@link api/ng.$templateCache `$templateCache`}, so that the
  18092. * template can be used by {@link api/ng.directive:ngInclude `ngInclude`},
  18093. * {@link api/ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  18094. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  18095. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  18096. *
  18097. * @param {'text/ng-template'} type Must be set to `'text/ng-template'`.
  18098. * @param {string} id Cache name of the template.
  18099. *
  18100. * @example
  18101. <doc:example>
  18102. <doc:source>
  18103. <script type="text/ng-template" id="/tpl.html">
  18104. Content of the template.
  18105. </script>
  18106. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  18107. <div id="tpl-content" ng-include src="currentTpl"></div>
  18108. </doc:source>
  18109. <doc:scenario>
  18110. it('should load template defined inside script tag', function() {
  18111. element('#tpl-link').click();
  18112. expect(element('#tpl-content').text()).toMatch(/Content of the template/);
  18113. });
  18114. </doc:scenario>
  18115. </doc:example>
  18116. */
  18117. var scriptDirective = ['$templateCache', function($templateCache) {
  18118. return {
  18119. restrict: 'E',
  18120. terminal: true,
  18121. compile: function(element, attr) {
  18122. if (attr.type == 'text/ng-template') {
  18123. var templateUrl = attr.id,
  18124. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  18125. text = element[0].text;
  18126. $templateCache.put(templateUrl, text);
  18127. }
  18128. }
  18129. };
  18130. }];
  18131. var ngOptionsMinErr = minErr('ngOptions');
  18132. /**
  18133. * @ngdoc directive
  18134. * @name ng.directive:select
  18135. * @restrict E
  18136. *
  18137. * @description
  18138. * HTML `SELECT` element with angular data-binding.
  18139. *
  18140. * # `ngOptions`
  18141. *
  18142. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  18143. * elements for the `<select>` element using the array or object obtained by evaluating the
  18144. * `ngOptions` comprehension_expression.
  18145. *
  18146. * When an item in the `<select>` menu is selected, the array element or object property
  18147. * represented by the selected option will be bound to the model identified by the `ngModel`
  18148. * directive.
  18149. *
  18150. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  18151. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  18152. * option. See example below for demonstration.
  18153. *
  18154. * Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
  18155. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  18156. * `select` model to be bound to a non-string value. This is because an option element can only
  18157. * be bound to string values at present.
  18158. *
  18159. * @param {string} ngModel Assignable angular expression to data-bind to.
  18160. * @param {string=} name Property name of the form under which the control is published.
  18161. * @param {string=} required The control is considered valid only if value is entered.
  18162. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18163. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18164. * `required` when you want to data-bind to the `required` attribute.
  18165. * @param {comprehension_expression=} ngOptions in one of the following forms:
  18166. *
  18167. * * for array data sources:
  18168. * * `label` **`for`** `value` **`in`** `array`
  18169. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  18170. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  18171. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  18172. * * for object data sources:
  18173. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  18174. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  18175. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  18176. * * `select` **`as`** `label` **`group by`** `group`
  18177. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  18178. *
  18179. * Where:
  18180. *
  18181. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  18182. * * `value`: local variable which will refer to each item in the `array` or each property value
  18183. * of `object` during iteration.
  18184. * * `key`: local variable which will refer to a property name in `object` during iteration.
  18185. * * `label`: The result of this expression will be the label for `<option>` element. The
  18186. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  18187. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  18188. * element. If not specified, `select` expression will default to `value`.
  18189. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  18190. * DOM element.
  18191. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  18192. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  18193. * `value` variable (e.g. `value.propertyName`).
  18194. *
  18195. * @example
  18196. <doc:example>
  18197. <doc:source>
  18198. <script>
  18199. function MyCntrl($scope) {
  18200. $scope.colors = [
  18201. {name:'black', shade:'dark'},
  18202. {name:'white', shade:'light'},
  18203. {name:'red', shade:'dark'},
  18204. {name:'blue', shade:'dark'},
  18205. {name:'yellow', shade:'light'}
  18206. ];
  18207. $scope.color = $scope.colors[2]; // red
  18208. }
  18209. </script>
  18210. <div ng-controller="MyCntrl">
  18211. <ul>
  18212. <li ng-repeat="color in colors">
  18213. Name: <input ng-model="color.name">
  18214. [<a href ng-click="colors.splice($index, 1)">X</a>]
  18215. </li>
  18216. <li>
  18217. [<a href ng-click="colors.push({})">add</a>]
  18218. </li>
  18219. </ul>
  18220. <hr/>
  18221. Color (null not allowed):
  18222. <select ng-model="color" ng-options="c.name for c in colors"></select><br>
  18223. Color (null allowed):
  18224. <span class="nullable">
  18225. <select ng-model="color" ng-options="c.name for c in colors">
  18226. <option value="">-- choose color --</option>
  18227. </select>
  18228. </span><br/>
  18229. Color grouped by shade:
  18230. <select ng-model="color" ng-options="c.name group by c.shade for c in colors">
  18231. </select><br/>
  18232. Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
  18233. <hr/>
  18234. Currently selected: {{ {selected_color:color} }}
  18235. <div style="border:solid 1px black; height:20px"
  18236. ng-style="{'background-color':color.name}">
  18237. </div>
  18238. </div>
  18239. </doc:source>
  18240. <doc:scenario>
  18241. it('should check ng-options', function() {
  18242. expect(binding('{selected_color:color}')).toMatch('red');
  18243. select('color').option('0');
  18244. expect(binding('{selected_color:color}')).toMatch('black');
  18245. using('.nullable').select('color').option('');
  18246. expect(binding('{selected_color:color}')).toMatch('null');
  18247. });
  18248. </doc:scenario>
  18249. </doc:example>
  18250. */
  18251. var ngOptionsDirective = valueFn({ terminal: true });
  18252. // jshint maxlen: false
  18253. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  18254. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  18255. var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?$/,
  18256. nullModelCtrl = {$setViewValue: noop};
  18257. // jshint maxlen: 100
  18258. return {
  18259. restrict: 'E',
  18260. require: ['select', '?ngModel'],
  18261. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  18262. var self = this,
  18263. optionsMap = {},
  18264. ngModelCtrl = nullModelCtrl,
  18265. nullOption,
  18266. unknownOption;
  18267. self.databound = $attrs.ngModel;
  18268. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  18269. ngModelCtrl = ngModelCtrl_;
  18270. nullOption = nullOption_;
  18271. unknownOption = unknownOption_;
  18272. };
  18273. self.addOption = function(value) {
  18274. assertNotHasOwnProperty(value, '"option value"');
  18275. optionsMap[value] = true;
  18276. if (ngModelCtrl.$viewValue == value) {
  18277. $element.val(value);
  18278. if (unknownOption.parent()) unknownOption.remove();
  18279. }
  18280. };
  18281. self.removeOption = function(value) {
  18282. if (this.hasOption(value)) {
  18283. delete optionsMap[value];
  18284. if (ngModelCtrl.$viewValue == value) {
  18285. this.renderUnknownOption(value);
  18286. }
  18287. }
  18288. };
  18289. self.renderUnknownOption = function(val) {
  18290. var unknownVal = '? ' + hashKey(val) + ' ?';
  18291. unknownOption.val(unknownVal);
  18292. $element.prepend(unknownOption);
  18293. $element.val(unknownVal);
  18294. unknownOption.prop('selected', true); // needed for IE
  18295. };
  18296. self.hasOption = function(value) {
  18297. return optionsMap.hasOwnProperty(value);
  18298. };
  18299. $scope.$on('$destroy', function() {
  18300. // disable unknown option so that we don't do work when the whole select is being destroyed
  18301. self.renderUnknownOption = noop;
  18302. });
  18303. }],
  18304. link: function(scope, element, attr, ctrls) {
  18305. // if ngModel is not defined, we don't need to do anything
  18306. if (!ctrls[1]) return;
  18307. var selectCtrl = ctrls[0],
  18308. ngModelCtrl = ctrls[1],
  18309. multiple = attr.multiple,
  18310. optionsExp = attr.ngOptions,
  18311. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  18312. emptyOption,
  18313. // we can't just jqLite('<option>') since jqLite is not smart enough
  18314. // to create it in <select> and IE barfs otherwise.
  18315. optionTemplate = jqLite(document.createElement('option')),
  18316. optGroupTemplate =jqLite(document.createElement('optgroup')),
  18317. unknownOption = optionTemplate.clone();
  18318. // find "null" option
  18319. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  18320. if (children[i].value === '') {
  18321. emptyOption = nullOption = children.eq(i);
  18322. break;
  18323. }
  18324. }
  18325. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  18326. // required validator
  18327. if (multiple) {
  18328. ngModelCtrl.$isEmpty = function(value) {
  18329. return !value || value.length === 0;
  18330. };
  18331. }
  18332. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  18333. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  18334. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  18335. ////////////////////////////
  18336. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  18337. ngModelCtrl.$render = function() {
  18338. var viewValue = ngModelCtrl.$viewValue;
  18339. if (selectCtrl.hasOption(viewValue)) {
  18340. if (unknownOption.parent()) unknownOption.remove();
  18341. selectElement.val(viewValue);
  18342. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  18343. } else {
  18344. if (isUndefined(viewValue) && emptyOption) {
  18345. selectElement.val('');
  18346. } else {
  18347. selectCtrl.renderUnknownOption(viewValue);
  18348. }
  18349. }
  18350. };
  18351. selectElement.on('change', function() {
  18352. scope.$apply(function() {
  18353. if (unknownOption.parent()) unknownOption.remove();
  18354. ngModelCtrl.$setViewValue(selectElement.val());
  18355. });
  18356. });
  18357. }
  18358. function setupAsMultiple(scope, selectElement, ctrl) {
  18359. var lastView;
  18360. ctrl.$render = function() {
  18361. var items = new HashMap(ctrl.$viewValue);
  18362. forEach(selectElement.find('option'), function(option) {
  18363. option.selected = isDefined(items.get(option.value));
  18364. });
  18365. };
  18366. // we have to do it on each watch since ngModel watches reference, but
  18367. // we need to work of an array, so we need to see if anything was inserted/removed
  18368. scope.$watch(function selectMultipleWatch() {
  18369. if (!equals(lastView, ctrl.$viewValue)) {
  18370. lastView = copy(ctrl.$viewValue);
  18371. ctrl.$render();
  18372. }
  18373. });
  18374. selectElement.on('change', function() {
  18375. scope.$apply(function() {
  18376. var array = [];
  18377. forEach(selectElement.find('option'), function(option) {
  18378. if (option.selected) {
  18379. array.push(option.value);
  18380. }
  18381. });
  18382. ctrl.$setViewValue(array);
  18383. });
  18384. });
  18385. }
  18386. function setupAsOptions(scope, selectElement, ctrl) {
  18387. var match;
  18388. if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  18389. throw ngOptionsMinErr('iexp',
  18390. "Expected expression in form of " +
  18391. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  18392. " but got '{0}'. Element: {1}",
  18393. optionsExp, startingTag(selectElement));
  18394. }
  18395. var displayFn = $parse(match[2] || match[1]),
  18396. valueName = match[4] || match[6],
  18397. keyName = match[5],
  18398. groupByFn = $parse(match[3] || ''),
  18399. valueFn = $parse(match[2] ? match[1] : valueName),
  18400. valuesFn = $parse(match[7]),
  18401. track = match[8],
  18402. trackFn = track ? $parse(match[8]) : null,
  18403. // This is an array of array of existing option groups in DOM.
  18404. // We try to reuse these if possible
  18405. // - optionGroupsCache[0] is the options with no option group
  18406. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  18407. optionGroupsCache = [[{element: selectElement, label:''}]];
  18408. if (nullOption) {
  18409. // compile the element since there might be bindings in it
  18410. $compile(nullOption)(scope);
  18411. // remove the class, which is added automatically because we recompile the element and it
  18412. // becomes the compilation root
  18413. nullOption.removeClass('ng-scope');
  18414. // we need to remove it before calling selectElement.empty() because otherwise IE will
  18415. // remove the label from the element. wtf?
  18416. nullOption.remove();
  18417. }
  18418. // clear contents, we'll add what's needed based on the model
  18419. selectElement.empty();
  18420. selectElement.on('change', function() {
  18421. scope.$apply(function() {
  18422. var optionGroup,
  18423. collection = valuesFn(scope) || [],
  18424. locals = {},
  18425. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  18426. if (multiple) {
  18427. value = [];
  18428. for (groupIndex = 0, groupLength = optionGroupsCache.length;
  18429. groupIndex < groupLength;
  18430. groupIndex++) {
  18431. // list of options for that group. (first item has the parent)
  18432. optionGroup = optionGroupsCache[groupIndex];
  18433. for(index = 1, length = optionGroup.length; index < length; index++) {
  18434. if ((optionElement = optionGroup[index].element)[0].selected) {
  18435. key = optionElement.val();
  18436. if (keyName) locals[keyName] = key;
  18437. if (trackFn) {
  18438. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  18439. locals[valueName] = collection[trackIndex];
  18440. if (trackFn(scope, locals) == key) break;
  18441. }
  18442. } else {
  18443. locals[valueName] = collection[key];
  18444. }
  18445. value.push(valueFn(scope, locals));
  18446. }
  18447. }
  18448. }
  18449. } else {
  18450. key = selectElement.val();
  18451. if (key == '?') {
  18452. value = undefined;
  18453. } else if (key === ''){
  18454. value = null;
  18455. } else {
  18456. if (trackFn) {
  18457. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  18458. locals[valueName] = collection[trackIndex];
  18459. if (trackFn(scope, locals) == key) {
  18460. value = valueFn(scope, locals);
  18461. break;
  18462. }
  18463. }
  18464. } else {
  18465. locals[valueName] = collection[key];
  18466. if (keyName) locals[keyName] = key;
  18467. value = valueFn(scope, locals);
  18468. }
  18469. }
  18470. }
  18471. ctrl.$setViewValue(value);
  18472. });
  18473. });
  18474. ctrl.$render = render;
  18475. // TODO(vojta): can't we optimize this ?
  18476. scope.$watch(render);
  18477. function render() {
  18478. // Temporary location for the option groups before we render them
  18479. var optionGroups = {'':[]},
  18480. optionGroupNames = [''],
  18481. optionGroupName,
  18482. optionGroup,
  18483. option,
  18484. existingParent, existingOptions, existingOption,
  18485. modelValue = ctrl.$modelValue,
  18486. values = valuesFn(scope) || [],
  18487. keys = keyName ? sortedKeys(values) : values,
  18488. key,
  18489. groupLength, length,
  18490. groupIndex, index,
  18491. locals = {},
  18492. selected,
  18493. selectedSet = false, // nothing is selected yet
  18494. lastElement,
  18495. element,
  18496. label;
  18497. if (multiple) {
  18498. if (trackFn && isArray(modelValue)) {
  18499. selectedSet = new HashMap([]);
  18500. for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
  18501. locals[valueName] = modelValue[trackIndex];
  18502. selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
  18503. }
  18504. } else {
  18505. selectedSet = new HashMap(modelValue);
  18506. }
  18507. }
  18508. // We now build up the list of options we need (we merge later)
  18509. for (index = 0; length = keys.length, index < length; index++) {
  18510. key = index;
  18511. if (keyName) {
  18512. key = keys[index];
  18513. if ( key.charAt(0) === '$' ) continue;
  18514. locals[keyName] = key;
  18515. }
  18516. locals[valueName] = values[key];
  18517. optionGroupName = groupByFn(scope, locals) || '';
  18518. if (!(optionGroup = optionGroups[optionGroupName])) {
  18519. optionGroup = optionGroups[optionGroupName] = [];
  18520. optionGroupNames.push(optionGroupName);
  18521. }
  18522. if (multiple) {
  18523. selected = isDefined(
  18524. selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
  18525. );
  18526. } else {
  18527. if (trackFn) {
  18528. var modelCast = {};
  18529. modelCast[valueName] = modelValue;
  18530. selected = trackFn(scope, modelCast) === trackFn(scope, locals);
  18531. } else {
  18532. selected = modelValue === valueFn(scope, locals);
  18533. }
  18534. selectedSet = selectedSet || selected; // see if at least one item is selected
  18535. }
  18536. label = displayFn(scope, locals); // what will be seen by the user
  18537. // doing displayFn(scope, locals) || '' overwrites zero values
  18538. label = isDefined(label) ? label : '';
  18539. optionGroup.push({
  18540. // either the index into array or key from object
  18541. id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
  18542. label: label,
  18543. selected: selected // determine if we should be selected
  18544. });
  18545. }
  18546. if (!multiple) {
  18547. if (nullOption || modelValue === null) {
  18548. // insert null option if we have a placeholder, or the model is null
  18549. optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
  18550. } else if (!selectedSet) {
  18551. // option could not be found, we have to insert the undefined item
  18552. optionGroups[''].unshift({id:'?', label:'', selected:true});
  18553. }
  18554. }
  18555. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  18556. for (groupIndex = 0, groupLength = optionGroupNames.length;
  18557. groupIndex < groupLength;
  18558. groupIndex++) {
  18559. // current option group name or '' if no group
  18560. optionGroupName = optionGroupNames[groupIndex];
  18561. // list of options for that group. (first item has the parent)
  18562. optionGroup = optionGroups[optionGroupName];
  18563. if (optionGroupsCache.length <= groupIndex) {
  18564. // we need to grow the optionGroups
  18565. existingParent = {
  18566. element: optGroupTemplate.clone().attr('label', optionGroupName),
  18567. label: optionGroup.label
  18568. };
  18569. existingOptions = [existingParent];
  18570. optionGroupsCache.push(existingOptions);
  18571. selectElement.append(existingParent.element);
  18572. } else {
  18573. existingOptions = optionGroupsCache[groupIndex];
  18574. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  18575. // update the OPTGROUP label if not the same.
  18576. if (existingParent.label != optionGroupName) {
  18577. existingParent.element.attr('label', existingParent.label = optionGroupName);
  18578. }
  18579. }
  18580. lastElement = null; // start at the beginning
  18581. for(index = 0, length = optionGroup.length; index < length; index++) {
  18582. option = optionGroup[index];
  18583. if ((existingOption = existingOptions[index+1])) {
  18584. // reuse elements
  18585. lastElement = existingOption.element;
  18586. if (existingOption.label !== option.label) {
  18587. lastElement.text(existingOption.label = option.label);
  18588. }
  18589. if (existingOption.id !== option.id) {
  18590. lastElement.val(existingOption.id = option.id);
  18591. }
  18592. // lastElement.prop('selected') provided by jQuery has side-effects
  18593. if (lastElement[0].selected !== option.selected) {
  18594. lastElement.prop('selected', (existingOption.selected = option.selected));
  18595. }
  18596. } else {
  18597. // grow elements
  18598. // if it's a null option
  18599. if (option.id === '' && nullOption) {
  18600. // put back the pre-compiled element
  18601. element = nullOption;
  18602. } else {
  18603. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  18604. // in this version of jQuery on some browser the .text() returns a string
  18605. // rather then the element.
  18606. (element = optionTemplate.clone())
  18607. .val(option.id)
  18608. .attr('selected', option.selected)
  18609. .text(option.label);
  18610. }
  18611. existingOptions.push(existingOption = {
  18612. element: element,
  18613. label: option.label,
  18614. id: option.id,
  18615. selected: option.selected
  18616. });
  18617. if (lastElement) {
  18618. lastElement.after(element);
  18619. } else {
  18620. existingParent.element.append(element);
  18621. }
  18622. lastElement = element;
  18623. }
  18624. }
  18625. // remove any excessive OPTIONs in a group
  18626. index++; // increment since the existingOptions[0] is parent element not OPTION
  18627. while(existingOptions.length > index) {
  18628. existingOptions.pop().element.remove();
  18629. }
  18630. }
  18631. // remove any excessive OPTGROUPs from select
  18632. while(optionGroupsCache.length > groupIndex) {
  18633. optionGroupsCache.pop()[0].element.remove();
  18634. }
  18635. }
  18636. }
  18637. }
  18638. };
  18639. }];
  18640. var optionDirective = ['$interpolate', function($interpolate) {
  18641. var nullSelectCtrl = {
  18642. addOption: noop,
  18643. removeOption: noop
  18644. };
  18645. return {
  18646. restrict: 'E',
  18647. priority: 100,
  18648. compile: function(element, attr) {
  18649. if (isUndefined(attr.value)) {
  18650. var interpolateFn = $interpolate(element.text(), true);
  18651. if (!interpolateFn) {
  18652. attr.$set('value', element.text());
  18653. }
  18654. }
  18655. return function (scope, element, attr) {
  18656. var selectCtrlName = '$selectController',
  18657. parent = element.parent(),
  18658. selectCtrl = parent.data(selectCtrlName) ||
  18659. parent.parent().data(selectCtrlName); // in case we are in optgroup
  18660. if (selectCtrl && selectCtrl.databound) {
  18661. // For some reason Opera defaults to true and if not overridden this messes up the repeater.
  18662. // We don't want the view to drive the initialization of the model anyway.
  18663. element.prop('selected', false);
  18664. } else {
  18665. selectCtrl = nullSelectCtrl;
  18666. }
  18667. if (interpolateFn) {
  18668. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  18669. attr.$set('value', newVal);
  18670. if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
  18671. selectCtrl.addOption(newVal);
  18672. });
  18673. } else {
  18674. selectCtrl.addOption(attr.value);
  18675. }
  18676. element.on('$destroy', function() {
  18677. selectCtrl.removeOption(attr.value);
  18678. });
  18679. };
  18680. }
  18681. };
  18682. }];
  18683. var styleDirective = valueFn({
  18684. restrict: 'E',
  18685. terminal: true
  18686. });
  18687. //try to bind to jquery now so that one can write angular.element().read()
  18688. //but we will rebind on bootstrap again.
  18689. bindJQuery();
  18690. publishExternalAPI(angular);
  18691. jqLite(document).ready(function() {
  18692. angularInit(document, bootstrap);
  18693. });
  18694. })(window, document);
  18695. !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;}</style>');