angular.js 760 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883
  1. /**
  2. * @license AngularJS v1.2.21
  3. * (c) 2010-2014 Google, Inc. http://angularjs.org
  4. * License: MIT
  5. */
  6. (function(window, document, undefined) {'use strict';
  7. /**
  8. * @description
  9. *
  10. * This object provides a utility for producing rich Error messages within
  11. * Angular. It can be called as follows:
  12. *
  13. * var exampleMinErr = minErr('example');
  14. * throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
  15. *
  16. * The above creates an instance of minErr in the example namespace. The
  17. * resulting error will have a namespaced error code of example.one. The
  18. * resulting error will replace {0} with the value of foo, and {1} with the
  19. * value of bar. The object is not restricted in the number of arguments it can
  20. * take.
  21. *
  22. * If fewer arguments are specified than necessary for interpolation, the extra
  23. * interpolation markers will be preserved in the final string.
  24. *
  25. * Since data will be parsed statically during a build step, some restrictions
  26. * are applied with respect to how minErr instances are created and called.
  27. * Instances should have names of the form namespaceMinErr for a minErr created
  28. * using minErr('namespace') . Error codes, namespaces and template strings
  29. * should all be static strings, not variables or general expressions.
  30. *
  31. * @param {string} module The namespace to use for the new minErr instance.
  32. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  33. */
  34. function minErr(module) {
  35. return function () {
  36. var code = arguments[0],
  37. prefix = '[' + (module ? module + ':' : '') + code + '] ',
  38. template = arguments[1],
  39. templateArgs = arguments,
  40. stringify = function (obj) {
  41. if (typeof obj === 'function') {
  42. return obj.toString().replace(/ \{[\s\S]*$/, '');
  43. } else if (typeof obj === 'undefined') {
  44. return 'undefined';
  45. } else if (typeof obj !== 'string') {
  46. return JSON.stringify(obj);
  47. }
  48. return obj;
  49. },
  50. message, i;
  51. message = prefix + template.replace(/\{\d+\}/g, function (match) {
  52. var index = +match.slice(1, -1), arg;
  53. if (index + 2 < templateArgs.length) {
  54. arg = templateArgs[index + 2];
  55. if (typeof arg === 'function') {
  56. return arg.toString().replace(/ ?\{[\s\S]*$/, '');
  57. } else if (typeof arg === 'undefined') {
  58. return 'undefined';
  59. } else if (typeof arg !== 'string') {
  60. return toJson(arg);
  61. }
  62. return arg;
  63. }
  64. return match;
  65. });
  66. message = message + '\nhttp://errors.angularjs.org/1.2.21/' +
  67. (module ? module + '/' : '') + code;
  68. for (i = 2; i < arguments.length; i++) {
  69. message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
  70. encodeURIComponent(stringify(arguments[i]));
  71. }
  72. return new Error(message);
  73. };
  74. }
  75. /* We need to tell jshint what variables are being exported */
  76. /* global angular: true,
  77. msie: true,
  78. jqLite: true,
  79. jQuery: true,
  80. slice: true,
  81. push: true,
  82. toString: true,
  83. ngMinErr: true,
  84. angularModule: true,
  85. nodeName_: true,
  86. uid: true,
  87. VALIDITY_STATE_PROPERTY: true,
  88. lowercase: true,
  89. uppercase: true,
  90. manualLowercase: true,
  91. manualUppercase: true,
  92. nodeName_: true,
  93. isArrayLike: true,
  94. forEach: true,
  95. sortedKeys: true,
  96. forEachSorted: true,
  97. reverseParams: true,
  98. nextUid: true,
  99. setHashKey: true,
  100. extend: true,
  101. int: true,
  102. inherit: true,
  103. noop: true,
  104. identity: true,
  105. valueFn: true,
  106. isUndefined: true,
  107. isDefined: true,
  108. isObject: true,
  109. isString: true,
  110. isNumber: true,
  111. isDate: true,
  112. isArray: true,
  113. isFunction: true,
  114. isRegExp: true,
  115. isWindow: true,
  116. isScope: true,
  117. isFile: true,
  118. isBlob: true,
  119. isBoolean: true,
  120. isPromiseLike: true,
  121. trim: true,
  122. isElement: true,
  123. makeMap: true,
  124. map: true,
  125. size: true,
  126. includes: true,
  127. indexOf: true,
  128. arrayRemove: true,
  129. isLeafNode: true,
  130. copy: true,
  131. shallowCopy: true,
  132. equals: true,
  133. csp: true,
  134. concat: true,
  135. sliceArgs: true,
  136. bind: true,
  137. toJsonReplacer: true,
  138. toJson: true,
  139. fromJson: true,
  140. toBoolean: true,
  141. startingTag: true,
  142. tryDecodeURIComponent: true,
  143. parseKeyValue: true,
  144. toKeyValue: true,
  145. encodeUriSegment: true,
  146. encodeUriQuery: true,
  147. angularInit: true,
  148. bootstrap: true,
  149. snake_case: true,
  150. bindJQuery: true,
  151. assertArg: true,
  152. assertArgFn: true,
  153. assertNotHasOwnProperty: true,
  154. getter: true,
  155. getBlockElements: true,
  156. hasOwnProperty: true,
  157. */
  158. ////////////////////////////////////
  159. /**
  160. * @ngdoc module
  161. * @name ng
  162. * @module ng
  163. * @description
  164. *
  165. * # ng (core module)
  166. * The ng module is loaded by default when an AngularJS application is started. The module itself
  167. * contains the essential components for an AngularJS application to function. The table below
  168. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  169. * components available within this core module.
  170. *
  171. * <div doc-module-components="ng"></div>
  172. */
  173. // The name of a form control's ValidityState property.
  174. // This is used so that it's possible for internal tests to create mock ValidityStates.
  175. var VALIDITY_STATE_PROPERTY = 'validity';
  176. /**
  177. * @ngdoc function
  178. * @name angular.lowercase
  179. * @module ng
  180. * @kind function
  181. *
  182. * @description Converts the specified string to lowercase.
  183. * @param {string} string String to be converted to lowercase.
  184. * @returns {string} Lowercased string.
  185. */
  186. var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
  187. var hasOwnProperty = Object.prototype.hasOwnProperty;
  188. /**
  189. * @ngdoc function
  190. * @name angular.uppercase
  191. * @module ng
  192. * @kind function
  193. *
  194. * @description Converts the specified string to uppercase.
  195. * @param {string} string String to be converted to uppercase.
  196. * @returns {string} Uppercased string.
  197. */
  198. var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
  199. var manualLowercase = function(s) {
  200. /* jshint bitwise: false */
  201. return isString(s)
  202. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  203. : s;
  204. };
  205. var manualUppercase = function(s) {
  206. /* jshint bitwise: false */
  207. return isString(s)
  208. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  209. : s;
  210. };
  211. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  212. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  213. // with correct but slower alternatives.
  214. if ('i' !== 'I'.toLowerCase()) {
  215. lowercase = manualLowercase;
  216. uppercase = manualUppercase;
  217. }
  218. var /** holds major version number for IE or NaN for real browsers */
  219. msie,
  220. jqLite, // delay binding since jQuery could be loaded after us.
  221. jQuery, // delay binding
  222. slice = [].slice,
  223. push = [].push,
  224. toString = Object.prototype.toString,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. nodeName_,
  230. uid = ['0', '0', '0'];
  231. /**
  232. * IE 11 changed the format of the UserAgent string.
  233. * See http://msdn.microsoft.com/en-us/library/ms537503.aspx
  234. */
  235. msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  236. if (isNaN(msie)) {
  237. msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
  238. }
  239. /**
  240. * @private
  241. * @param {*} obj
  242. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  243. * String ...)
  244. */
  245. function isArrayLike(obj) {
  246. if (obj == null || isWindow(obj)) {
  247. return false;
  248. }
  249. var length = obj.length;
  250. if (obj.nodeType === 1 && length) {
  251. return true;
  252. }
  253. return isString(obj) || isArray(obj) || length === 0 ||
  254. typeof length === 'number' && length > 0 && (length - 1) in obj;
  255. }
  256. /**
  257. * @ngdoc function
  258. * @name angular.forEach
  259. * @module ng
  260. * @kind function
  261. *
  262. * @description
  263. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  264. * object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
  265. * is the value of an object property or an array element and `key` is the object property key or
  266. * array element index. Specifying a `context` for the function is optional.
  267. *
  268. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  269. * using the `hasOwnProperty` method.
  270. *
  271. ```js
  272. var values = {name: 'misko', gender: 'male'};
  273. var log = [];
  274. angular.forEach(values, function(value, key) {
  275. this.push(key + ': ' + value);
  276. }, log);
  277. expect(log).toEqual(['name: misko', 'gender: male']);
  278. ```
  279. *
  280. * @param {Object|Array} obj Object to iterate over.
  281. * @param {Function} iterator Iterator function.
  282. * @param {Object=} context Object to become context (`this`) for the iterator function.
  283. * @returns {Object|Array} Reference to `obj`.
  284. */
  285. function forEach(obj, iterator, context) {
  286. var key;
  287. if (obj) {
  288. if (isFunction(obj)) {
  289. for (key in obj) {
  290. // Need to check if hasOwnProperty exists,
  291. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  292. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  293. iterator.call(context, obj[key], key);
  294. }
  295. }
  296. } else if (isArray(obj) || isArrayLike(obj)) {
  297. for (key = 0; key < obj.length; key++) {
  298. iterator.call(context, obj[key], key);
  299. }
  300. } else if (obj.forEach && obj.forEach !== forEach) {
  301. obj.forEach(iterator, context);
  302. } else {
  303. for (key in obj) {
  304. if (obj.hasOwnProperty(key)) {
  305. iterator.call(context, obj[key], key);
  306. }
  307. }
  308. }
  309. }
  310. return obj;
  311. }
  312. function sortedKeys(obj) {
  313. var keys = [];
  314. for (var key in obj) {
  315. if (obj.hasOwnProperty(key)) {
  316. keys.push(key);
  317. }
  318. }
  319. return keys.sort();
  320. }
  321. function forEachSorted(obj, iterator, context) {
  322. var keys = sortedKeys(obj);
  323. for ( var i = 0; i < keys.length; i++) {
  324. iterator.call(context, obj[keys[i]], keys[i]);
  325. }
  326. return keys;
  327. }
  328. /**
  329. * when using forEach the params are value, key, but it is often useful to have key, value.
  330. * @param {function(string, *)} iteratorFn
  331. * @returns {function(*, string)}
  332. */
  333. function reverseParams(iteratorFn) {
  334. return function(value, key) { iteratorFn(key, value); };
  335. }
  336. /**
  337. * A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
  338. * characters such as '012ABC'. The reason why we are not using simply a number counter is that
  339. * the number string gets longer over time, and it can also overflow, where as the nextId
  340. * will grow much slower, it is a string, and it will never overflow.
  341. *
  342. * @returns {string} an unique alpha-numeric string
  343. */
  344. function nextUid() {
  345. var index = uid.length;
  346. var digit;
  347. while(index) {
  348. index--;
  349. digit = uid[index].charCodeAt(0);
  350. if (digit == 57 /*'9'*/) {
  351. uid[index] = 'A';
  352. return uid.join('');
  353. }
  354. if (digit == 90 /*'Z'*/) {
  355. uid[index] = '0';
  356. } else {
  357. uid[index] = String.fromCharCode(digit + 1);
  358. return uid.join('');
  359. }
  360. }
  361. uid.unshift('0');
  362. return uid.join('');
  363. }
  364. /**
  365. * Set or clear the hashkey for an object.
  366. * @param obj object
  367. * @param h the hashkey (!truthy to delete the hashkey)
  368. */
  369. function setHashKey(obj, h) {
  370. if (h) {
  371. obj.$$hashKey = h;
  372. }
  373. else {
  374. delete obj.$$hashKey;
  375. }
  376. }
  377. /**
  378. * @ngdoc function
  379. * @name angular.extend
  380. * @module ng
  381. * @kind function
  382. *
  383. * @description
  384. * Extends the destination object `dst` by copying all of the properties from the `src` object(s)
  385. * to `dst`. You can specify multiple `src` objects.
  386. *
  387. * @param {Object} dst Destination object.
  388. * @param {...Object} src Source object(s).
  389. * @returns {Object} Reference to `dst`.
  390. */
  391. function extend(dst) {
  392. var h = dst.$$hashKey;
  393. forEach(arguments, function(obj) {
  394. if (obj !== dst) {
  395. forEach(obj, function(value, key) {
  396. dst[key] = value;
  397. });
  398. }
  399. });
  400. setHashKey(dst,h);
  401. return dst;
  402. }
  403. function int(str) {
  404. return parseInt(str, 10);
  405. }
  406. function inherit(parent, extra) {
  407. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  408. }
  409. /**
  410. * @ngdoc function
  411. * @name angular.noop
  412. * @module ng
  413. * @kind function
  414. *
  415. * @description
  416. * A function that performs no operations. This function can be useful when writing code in the
  417. * functional style.
  418. ```js
  419. function foo(callback) {
  420. var result = calculateResult();
  421. (callback || angular.noop)(result);
  422. }
  423. ```
  424. */
  425. function noop() {}
  426. noop.$inject = [];
  427. /**
  428. * @ngdoc function
  429. * @name angular.identity
  430. * @module ng
  431. * @kind function
  432. *
  433. * @description
  434. * A function that returns its first argument. This function is useful when writing code in the
  435. * functional style.
  436. *
  437. ```js
  438. function transformer(transformationFn, value) {
  439. return (transformationFn || angular.identity)(value);
  440. };
  441. ```
  442. */
  443. function identity($) {return $;}
  444. identity.$inject = [];
  445. function valueFn(value) {return function() {return value;};}
  446. /**
  447. * @ngdoc function
  448. * @name angular.isUndefined
  449. * @module ng
  450. * @kind function
  451. *
  452. * @description
  453. * Determines if a reference is undefined.
  454. *
  455. * @param {*} value Reference to check.
  456. * @returns {boolean} True if `value` is undefined.
  457. */
  458. function isUndefined(value){return typeof value === 'undefined';}
  459. /**
  460. * @ngdoc function
  461. * @name angular.isDefined
  462. * @module ng
  463. * @kind function
  464. *
  465. * @description
  466. * Determines if a reference is defined.
  467. *
  468. * @param {*} value Reference to check.
  469. * @returns {boolean} True if `value` is defined.
  470. */
  471. function isDefined(value){return typeof value !== 'undefined';}
  472. /**
  473. * @ngdoc function
  474. * @name angular.isObject
  475. * @module ng
  476. * @kind function
  477. *
  478. * @description
  479. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  480. * considered to be objects. Note that JavaScript arrays are objects.
  481. *
  482. * @param {*} value Reference to check.
  483. * @returns {boolean} True if `value` is an `Object` but not `null`.
  484. */
  485. function isObject(value){return value != null && typeof value === 'object';}
  486. /**
  487. * @ngdoc function
  488. * @name angular.isString
  489. * @module ng
  490. * @kind function
  491. *
  492. * @description
  493. * Determines if a reference is a `String`.
  494. *
  495. * @param {*} value Reference to check.
  496. * @returns {boolean} True if `value` is a `String`.
  497. */
  498. function isString(value){return typeof value === 'string';}
  499. /**
  500. * @ngdoc function
  501. * @name angular.isNumber
  502. * @module ng
  503. * @kind function
  504. *
  505. * @description
  506. * Determines if a reference is a `Number`.
  507. *
  508. * @param {*} value Reference to check.
  509. * @returns {boolean} True if `value` is a `Number`.
  510. */
  511. function isNumber(value){return typeof value === 'number';}
  512. /**
  513. * @ngdoc function
  514. * @name angular.isDate
  515. * @module ng
  516. * @kind function
  517. *
  518. * @description
  519. * Determines if a value is a date.
  520. *
  521. * @param {*} value Reference to check.
  522. * @returns {boolean} True if `value` is a `Date`.
  523. */
  524. function isDate(value) {
  525. return toString.call(value) === '[object Date]';
  526. }
  527. /**
  528. * @ngdoc function
  529. * @name angular.isArray
  530. * @module ng
  531. * @kind function
  532. *
  533. * @description
  534. * Determines if a reference is an `Array`.
  535. *
  536. * @param {*} value Reference to check.
  537. * @returns {boolean} True if `value` is an `Array`.
  538. */
  539. var isArray = (function() {
  540. if (!isFunction(Array.isArray)) {
  541. return function(value) {
  542. return toString.call(value) === '[object Array]';
  543. };
  544. }
  545. return Array.isArray;
  546. })();
  547. /**
  548. * @ngdoc function
  549. * @name angular.isFunction
  550. * @module ng
  551. * @kind function
  552. *
  553. * @description
  554. * Determines if a reference is a `Function`.
  555. *
  556. * @param {*} value Reference to check.
  557. * @returns {boolean} True if `value` is a `Function`.
  558. */
  559. function isFunction(value){return typeof value === 'function';}
  560. /**
  561. * Determines if a value is a regular expression object.
  562. *
  563. * @private
  564. * @param {*} value Reference to check.
  565. * @returns {boolean} True if `value` is a `RegExp`.
  566. */
  567. function isRegExp(value) {
  568. return toString.call(value) === '[object RegExp]';
  569. }
  570. /**
  571. * Checks if `obj` is a window object.
  572. *
  573. * @private
  574. * @param {*} obj Object to check
  575. * @returns {boolean} True if `obj` is a window obj.
  576. */
  577. function isWindow(obj) {
  578. return obj && obj.document && obj.location && obj.alert && obj.setInterval;
  579. }
  580. function isScope(obj) {
  581. return obj && obj.$evalAsync && obj.$watch;
  582. }
  583. function isFile(obj) {
  584. return toString.call(obj) === '[object File]';
  585. }
  586. function isBlob(obj) {
  587. return toString.call(obj) === '[object Blob]';
  588. }
  589. function isBoolean(value) {
  590. return typeof value === 'boolean';
  591. }
  592. function isPromiseLike(obj) {
  593. return obj && isFunction(obj.then);
  594. }
  595. var trim = (function() {
  596. // native trim is way faster: http://jsperf.com/angular-trim-test
  597. // but IE doesn't have it... :-(
  598. // TODO: we should move this into IE/ES5 polyfill
  599. if (!String.prototype.trim) {
  600. return function(value) {
  601. return isString(value) ? value.replace(/^\s\s*/, '').replace(/\s\s*$/, '') : value;
  602. };
  603. }
  604. return function(value) {
  605. return isString(value) ? value.trim() : value;
  606. };
  607. })();
  608. /**
  609. * @ngdoc function
  610. * @name angular.isElement
  611. * @module ng
  612. * @kind function
  613. *
  614. * @description
  615. * Determines if a reference is a DOM element (or wrapped jQuery element).
  616. *
  617. * @param {*} value Reference to check.
  618. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  619. */
  620. function isElement(node) {
  621. return !!(node &&
  622. (node.nodeName // we are a direct element
  623. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  624. }
  625. /**
  626. * @param str 'key1,key2,...'
  627. * @returns {object} in the form of {key1:true, key2:true, ...}
  628. */
  629. function makeMap(str) {
  630. var obj = {}, items = str.split(","), i;
  631. for ( i = 0; i < items.length; i++ )
  632. obj[ items[i] ] = true;
  633. return obj;
  634. }
  635. if (msie < 9) {
  636. nodeName_ = function(element) {
  637. element = element.nodeName ? element : element[0];
  638. return (element.scopeName && element.scopeName != 'HTML')
  639. ? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
  640. };
  641. } else {
  642. nodeName_ = function(element) {
  643. return element.nodeName ? element.nodeName : element[0].nodeName;
  644. };
  645. }
  646. function map(obj, iterator, context) {
  647. var results = [];
  648. forEach(obj, function(value, index, list) {
  649. results.push(iterator.call(context, value, index, list));
  650. });
  651. return results;
  652. }
  653. /**
  654. * @description
  655. * Determines the number of elements in an array, the number of properties an object has, or
  656. * the length of a string.
  657. *
  658. * Note: This function is used to augment the Object type in Angular expressions. See
  659. * {@link angular.Object} for more information about Angular arrays.
  660. *
  661. * @param {Object|Array|string} obj Object, array, or string to inspect.
  662. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
  663. * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
  664. */
  665. function size(obj, ownPropsOnly) {
  666. var count = 0, key;
  667. if (isArray(obj) || isString(obj)) {
  668. return obj.length;
  669. } else if (isObject(obj)) {
  670. for (key in obj)
  671. if (!ownPropsOnly || obj.hasOwnProperty(key))
  672. count++;
  673. }
  674. return count;
  675. }
  676. function includes(array, obj) {
  677. return indexOf(array, obj) != -1;
  678. }
  679. function indexOf(array, obj) {
  680. if (array.indexOf) return array.indexOf(obj);
  681. for (var i = 0; i < array.length; i++) {
  682. if (obj === array[i]) return i;
  683. }
  684. return -1;
  685. }
  686. function arrayRemove(array, value) {
  687. var index = indexOf(array, value);
  688. if (index >=0)
  689. array.splice(index, 1);
  690. return value;
  691. }
  692. function isLeafNode (node) {
  693. if (node) {
  694. switch (node.nodeName) {
  695. case "OPTION":
  696. case "PRE":
  697. case "TITLE":
  698. return true;
  699. }
  700. }
  701. return false;
  702. }
  703. /**
  704. * @ngdoc function
  705. * @name angular.copy
  706. * @module ng
  707. * @kind function
  708. *
  709. * @description
  710. * Creates a deep copy of `source`, which should be an object or an array.
  711. *
  712. * * If no destination is supplied, a copy of the object or array is created.
  713. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  714. * are deleted and then all elements/properties from the source are copied to it.
  715. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  716. * * If `source` is identical to 'destination' an exception will be thrown.
  717. *
  718. * @param {*} source The source that will be used to make a copy.
  719. * Can be any type, including primitives, `null`, and `undefined`.
  720. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  721. * provided, must be of the same type as `source`.
  722. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  723. *
  724. * @example
  725. <example module="copyExample">
  726. <file name="index.html">
  727. <div ng-controller="ExampleController">
  728. <form novalidate class="simple-form">
  729. Name: <input type="text" ng-model="user.name" /><br />
  730. E-mail: <input type="email" ng-model="user.email" /><br />
  731. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  732. <input type="radio" ng-model="user.gender" value="female" />female<br />
  733. <button ng-click="reset()">RESET</button>
  734. <button ng-click="update(user)">SAVE</button>
  735. </form>
  736. <pre>form = {{user | json}}</pre>
  737. <pre>master = {{master | json}}</pre>
  738. </div>
  739. <script>
  740. angular.module('copyExample', [])
  741. .controller('ExampleController', ['$scope', function($scope) {
  742. $scope.master= {};
  743. $scope.update = function(user) {
  744. // Example with 1 argument
  745. $scope.master= angular.copy(user);
  746. };
  747. $scope.reset = function() {
  748. // Example with 2 arguments
  749. angular.copy($scope.master, $scope.user);
  750. };
  751. $scope.reset();
  752. }]);
  753. </script>
  754. </file>
  755. </example>
  756. */
  757. function copy(source, destination, stackSource, stackDest) {
  758. if (isWindow(source) || isScope(source)) {
  759. throw ngMinErr('cpws',
  760. "Can't copy! Making copies of Window or Scope instances is not supported.");
  761. }
  762. if (!destination) {
  763. destination = source;
  764. if (source) {
  765. if (isArray(source)) {
  766. destination = copy(source, [], stackSource, stackDest);
  767. } else if (isDate(source)) {
  768. destination = new Date(source.getTime());
  769. } else if (isRegExp(source)) {
  770. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  771. destination.lastIndex = source.lastIndex;
  772. } else if (isObject(source)) {
  773. destination = copy(source, {}, stackSource, stackDest);
  774. }
  775. }
  776. } else {
  777. if (source === destination) throw ngMinErr('cpi',
  778. "Can't copy! Source and destination are identical.");
  779. stackSource = stackSource || [];
  780. stackDest = stackDest || [];
  781. if (isObject(source)) {
  782. var index = indexOf(stackSource, source);
  783. if (index !== -1) return stackDest[index];
  784. stackSource.push(source);
  785. stackDest.push(destination);
  786. }
  787. var result;
  788. if (isArray(source)) {
  789. destination.length = 0;
  790. for ( var i = 0; i < source.length; i++) {
  791. result = copy(source[i], null, stackSource, stackDest);
  792. if (isObject(source[i])) {
  793. stackSource.push(source[i]);
  794. stackDest.push(result);
  795. }
  796. destination.push(result);
  797. }
  798. } else {
  799. var h = destination.$$hashKey;
  800. forEach(destination, function(value, key) {
  801. delete destination[key];
  802. });
  803. for ( var key in source) {
  804. result = copy(source[key], null, stackSource, stackDest);
  805. if (isObject(source[key])) {
  806. stackSource.push(source[key]);
  807. stackDest.push(result);
  808. }
  809. destination[key] = result;
  810. }
  811. setHashKey(destination,h);
  812. }
  813. }
  814. return destination;
  815. }
  816. /**
  817. * Creates a shallow copy of an object, an array or a primitive
  818. */
  819. function shallowCopy(src, dst) {
  820. if (isArray(src)) {
  821. dst = dst || [];
  822. for ( var i = 0; i < src.length; i++) {
  823. dst[i] = src[i];
  824. }
  825. } else if (isObject(src)) {
  826. dst = dst || {};
  827. for (var key in src) {
  828. if (hasOwnProperty.call(src, key) && !(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  829. dst[key] = src[key];
  830. }
  831. }
  832. }
  833. return dst || src;
  834. }
  835. /**
  836. * @ngdoc function
  837. * @name angular.equals
  838. * @module ng
  839. * @kind function
  840. *
  841. * @description
  842. * Determines if two objects or two values are equivalent. Supports value types, regular
  843. * expressions, arrays and objects.
  844. *
  845. * Two objects or values are considered equivalent if at least one of the following is true:
  846. *
  847. * * Both objects or values pass `===` comparison.
  848. * * Both objects or values are of the same type and all of their properties are equal by
  849. * comparing them with `angular.equals`.
  850. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  851. * * Both values represent the same regular expression (In JavaScript,
  852. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  853. * representation matches).
  854. *
  855. * During a property comparison, properties of `function` type and properties with names
  856. * that begin with `$` are ignored.
  857. *
  858. * Scope and DOMWindow objects are being compared only by identify (`===`).
  859. *
  860. * @param {*} o1 Object or value to compare.
  861. * @param {*} o2 Object or value to compare.
  862. * @returns {boolean} True if arguments are equal.
  863. */
  864. function equals(o1, o2) {
  865. if (o1 === o2) return true;
  866. if (o1 === null || o2 === null) return false;
  867. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  868. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  869. if (t1 == t2) {
  870. if (t1 == 'object') {
  871. if (isArray(o1)) {
  872. if (!isArray(o2)) return false;
  873. if ((length = o1.length) == o2.length) {
  874. for(key=0; key<length; key++) {
  875. if (!equals(o1[key], o2[key])) return false;
  876. }
  877. return true;
  878. }
  879. } else if (isDate(o1)) {
  880. return isDate(o2) && o1.getTime() == o2.getTime();
  881. } else if (isRegExp(o1) && isRegExp(o2)) {
  882. return o1.toString() == o2.toString();
  883. } else {
  884. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  885. keySet = {};
  886. for(key in o1) {
  887. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  888. if (!equals(o1[key], o2[key])) return false;
  889. keySet[key] = true;
  890. }
  891. for(key in o2) {
  892. if (!keySet.hasOwnProperty(key) &&
  893. key.charAt(0) !== '$' &&
  894. o2[key] !== undefined &&
  895. !isFunction(o2[key])) return false;
  896. }
  897. return true;
  898. }
  899. }
  900. }
  901. return false;
  902. }
  903. var csp = function() {
  904. if (isDefined(csp.isActive_)) return csp.isActive_;
  905. var active = !!(document.querySelector('[ng-csp]') ||
  906. document.querySelector('[data-ng-csp]'));
  907. if (!active) {
  908. try {
  909. /* jshint -W031, -W054 */
  910. new Function('');
  911. /* jshint +W031, +W054 */
  912. } catch (e) {
  913. active = true;
  914. }
  915. }
  916. return (csp.isActive_ = active);
  917. };
  918. function concat(array1, array2, index) {
  919. return array1.concat(slice.call(array2, index));
  920. }
  921. function sliceArgs(args, startIndex) {
  922. return slice.call(args, startIndex || 0);
  923. }
  924. /* jshint -W101 */
  925. /**
  926. * @ngdoc function
  927. * @name angular.bind
  928. * @module ng
  929. * @kind function
  930. *
  931. * @description
  932. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  933. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  934. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  935. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  936. *
  937. * @param {Object} self Context which `fn` should be evaluated in.
  938. * @param {function()} fn Function to be bound.
  939. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  940. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  941. */
  942. /* jshint +W101 */
  943. function bind(self, fn) {
  944. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  945. if (isFunction(fn) && !(fn instanceof RegExp)) {
  946. return curryArgs.length
  947. ? function() {
  948. return arguments.length
  949. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  950. : fn.apply(self, curryArgs);
  951. }
  952. : function() {
  953. return arguments.length
  954. ? fn.apply(self, arguments)
  955. : fn.call(self);
  956. };
  957. } else {
  958. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  959. return fn;
  960. }
  961. }
  962. function toJsonReplacer(key, value) {
  963. var val = value;
  964. if (typeof key === 'string' && key.charAt(0) === '$') {
  965. val = undefined;
  966. } else if (isWindow(value)) {
  967. val = '$WINDOW';
  968. } else if (value && document === value) {
  969. val = '$DOCUMENT';
  970. } else if (isScope(value)) {
  971. val = '$SCOPE';
  972. }
  973. return val;
  974. }
  975. /**
  976. * @ngdoc function
  977. * @name angular.toJson
  978. * @module ng
  979. * @kind function
  980. *
  981. * @description
  982. * Serializes input into a JSON-formatted string. Properties with leading $ characters will be
  983. * stripped since angular uses this notation internally.
  984. *
  985. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  986. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  987. * @returns {string|undefined} JSON-ified string representing `obj`.
  988. */
  989. function toJson(obj, pretty) {
  990. if (typeof obj === 'undefined') return undefined;
  991. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  992. }
  993. /**
  994. * @ngdoc function
  995. * @name angular.fromJson
  996. * @module ng
  997. * @kind function
  998. *
  999. * @description
  1000. * Deserializes a JSON string.
  1001. *
  1002. * @param {string} json JSON string to deserialize.
  1003. * @returns {Object|Array|string|number} Deserialized thingy.
  1004. */
  1005. function fromJson(json) {
  1006. return isString(json)
  1007. ? JSON.parse(json)
  1008. : json;
  1009. }
  1010. function toBoolean(value) {
  1011. if (typeof value === 'function') {
  1012. value = true;
  1013. } else if (value && value.length !== 0) {
  1014. var v = lowercase("" + value);
  1015. value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
  1016. } else {
  1017. value = false;
  1018. }
  1019. return value;
  1020. }
  1021. /**
  1022. * @returns {string} Returns the string representation of the element.
  1023. */
  1024. function startingTag(element) {
  1025. element = jqLite(element).clone();
  1026. try {
  1027. // turns out IE does not let you set .html() on elements which
  1028. // are not allowed to have children. So we just ignore it.
  1029. element.empty();
  1030. } catch(e) {}
  1031. // As Per DOM Standards
  1032. var TEXT_NODE = 3;
  1033. var elemHtml = jqLite('<div>').append(element).html();
  1034. try {
  1035. return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
  1036. elemHtml.
  1037. match(/^(<[^>]+>)/)[1].
  1038. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1039. } catch(e) {
  1040. return lowercase(elemHtml);
  1041. }
  1042. }
  1043. /////////////////////////////////////////////////
  1044. /**
  1045. * Tries to decode the URI component without throwing an exception.
  1046. *
  1047. * @private
  1048. * @param str value potential URI component to check.
  1049. * @returns {boolean} True if `value` can be decoded
  1050. * with the decodeURIComponent function.
  1051. */
  1052. function tryDecodeURIComponent(value) {
  1053. try {
  1054. return decodeURIComponent(value);
  1055. } catch(e) {
  1056. // Ignore any invalid uri component
  1057. }
  1058. }
  1059. /**
  1060. * Parses an escaped url query string into key-value pairs.
  1061. * @returns {Object.<string,boolean|Array>}
  1062. */
  1063. function parseKeyValue(/**string*/keyValue) {
  1064. var obj = {}, key_value, key;
  1065. forEach((keyValue || "").split('&'), function(keyValue) {
  1066. if ( keyValue ) {
  1067. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1068. key = tryDecodeURIComponent(key_value[0]);
  1069. if ( isDefined(key) ) {
  1070. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1071. if (!hasOwnProperty.call(obj, key)) {
  1072. obj[key] = val;
  1073. } else if(isArray(obj[key])) {
  1074. obj[key].push(val);
  1075. } else {
  1076. obj[key] = [obj[key],val];
  1077. }
  1078. }
  1079. }
  1080. });
  1081. return obj;
  1082. }
  1083. function toKeyValue(obj) {
  1084. var parts = [];
  1085. forEach(obj, function(value, key) {
  1086. if (isArray(value)) {
  1087. forEach(value, function(arrayValue) {
  1088. parts.push(encodeUriQuery(key, true) +
  1089. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1090. });
  1091. } else {
  1092. parts.push(encodeUriQuery(key, true) +
  1093. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1094. }
  1095. });
  1096. return parts.length ? parts.join('&') : '';
  1097. }
  1098. /**
  1099. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1100. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1101. * segments:
  1102. * segment = *pchar
  1103. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1104. * pct-encoded = "%" HEXDIG HEXDIG
  1105. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1106. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1107. * / "*" / "+" / "," / ";" / "="
  1108. */
  1109. function encodeUriSegment(val) {
  1110. return encodeUriQuery(val, true).
  1111. replace(/%26/gi, '&').
  1112. replace(/%3D/gi, '=').
  1113. replace(/%2B/gi, '+');
  1114. }
  1115. /**
  1116. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1117. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1118. * encoded per http://tools.ietf.org/html/rfc3986:
  1119. * query = *( pchar / "/" / "?" )
  1120. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1121. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1122. * pct-encoded = "%" HEXDIG HEXDIG
  1123. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1124. * / "*" / "+" / "," / ";" / "="
  1125. */
  1126. function encodeUriQuery(val, pctEncodeSpaces) {
  1127. return encodeURIComponent(val).
  1128. replace(/%40/gi, '@').
  1129. replace(/%3A/gi, ':').
  1130. replace(/%24/g, '$').
  1131. replace(/%2C/gi, ',').
  1132. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1133. }
  1134. /**
  1135. * @ngdoc directive
  1136. * @name ngApp
  1137. * @module ng
  1138. *
  1139. * @element ANY
  1140. * @param {angular.Module} ngApp an optional application
  1141. * {@link angular.module module} name to load.
  1142. *
  1143. * @description
  1144. *
  1145. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1146. * designates the **root element** of the application and is typically placed near the root element
  1147. * of the page - e.g. on the `<body>` or `<html>` tags.
  1148. *
  1149. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1150. * found in the document will be used to define the root element to auto-bootstrap as an
  1151. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1152. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1153. *
  1154. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1155. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
  1156. * should contain the application code needed or have dependencies on other modules that will
  1157. * contain the code. See {@link angular.module} for more information.
  1158. *
  1159. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1160. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1161. * would not be resolved to `3`.
  1162. *
  1163. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1164. *
  1165. <example module="ngAppDemo">
  1166. <file name="index.html">
  1167. <div ng-controller="ngAppDemoController">
  1168. I can add: {{a}} + {{b}} = {{ a+b }}
  1169. </div>
  1170. </file>
  1171. <file name="script.js">
  1172. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1173. $scope.a = 1;
  1174. $scope.b = 2;
  1175. });
  1176. </file>
  1177. </example>
  1178. *
  1179. */
  1180. function angularInit(element, bootstrap) {
  1181. var elements = [element],
  1182. appElement,
  1183. module,
  1184. names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
  1185. NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
  1186. function append(element) {
  1187. element && elements.push(element);
  1188. }
  1189. forEach(names, function(name) {
  1190. names[name] = true;
  1191. append(document.getElementById(name));
  1192. name = name.replace(':', '\\:');
  1193. if (element.querySelectorAll) {
  1194. forEach(element.querySelectorAll('.' + name), append);
  1195. forEach(element.querySelectorAll('.' + name + '\\:'), append);
  1196. forEach(element.querySelectorAll('[' + name + ']'), append);
  1197. }
  1198. });
  1199. forEach(elements, function(element) {
  1200. if (!appElement) {
  1201. var className = ' ' + element.className + ' ';
  1202. var match = NG_APP_CLASS_REGEXP.exec(className);
  1203. if (match) {
  1204. appElement = element;
  1205. module = (match[2] || '').replace(/\s+/g, ',');
  1206. } else {
  1207. forEach(element.attributes, function(attr) {
  1208. if (!appElement && names[attr.name]) {
  1209. appElement = element;
  1210. module = attr.value;
  1211. }
  1212. });
  1213. }
  1214. }
  1215. });
  1216. if (appElement) {
  1217. bootstrap(appElement, module ? [module] : []);
  1218. }
  1219. }
  1220. /**
  1221. * @ngdoc function
  1222. * @name angular.bootstrap
  1223. * @module ng
  1224. * @description
  1225. * Use this function to manually start up angular application.
  1226. *
  1227. * See: {@link guide/bootstrap Bootstrap}
  1228. *
  1229. * Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
  1230. * They must use {@link ng.directive:ngApp ngApp}.
  1231. *
  1232. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1233. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1234. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1235. * multiple instances of Angular try to work on the DOM.
  1236. *
  1237. * <example name="multi-bootstrap" module="multi-bootstrap">
  1238. * <file name="index.html">
  1239. * <script src="../../../angular.js"></script>
  1240. * <div ng-controller="BrokenTable">
  1241. * <table>
  1242. * <tr>
  1243. * <th ng-repeat="heading in headings">{{heading}}</th>
  1244. * </tr>
  1245. * <tr ng-repeat="filling in fillings">
  1246. * <td ng-repeat="fill in filling">{{fill}}</td>
  1247. * </tr>
  1248. * </table>
  1249. * </div>
  1250. * </file>
  1251. * <file name="controller.js">
  1252. * var app = angular.module('multi-bootstrap', [])
  1253. *
  1254. * .controller('BrokenTable', function($scope) {
  1255. * $scope.headings = ['One', 'Two', 'Three'];
  1256. * $scope.fillings = [[1, 2, 3], ['A', 'B', 'C'], [7, 8, 9]];
  1257. * });
  1258. * </file>
  1259. * <file name="protractor.js" type="protractor">
  1260. * it('should only insert one table cell for each item in $scope.fillings', function() {
  1261. * expect(element.all(by.css('td')).count())
  1262. * .toBe(9);
  1263. * });
  1264. * </file>
  1265. * </example>
  1266. *
  1267. * @param {DOMElement} element DOM element which is the root of angular application.
  1268. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1269. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1270. * function that will be invoked by the injector as a run block.
  1271. * See: {@link angular.module modules}
  1272. * @returns {auto.$injector} Returns the newly created injector for this app.
  1273. */
  1274. function bootstrap(element, modules) {
  1275. var doBootstrap = function() {
  1276. element = jqLite(element);
  1277. if (element.injector()) {
  1278. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1279. throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
  1280. }
  1281. modules = modules || [];
  1282. modules.unshift(['$provide', function($provide) {
  1283. $provide.value('$rootElement', element);
  1284. }]);
  1285. modules.unshift('ng');
  1286. var injector = createInjector(modules);
  1287. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
  1288. function(scope, element, compile, injector, animate) {
  1289. scope.$apply(function() {
  1290. element.data('$injector', injector);
  1291. compile(element)(scope);
  1292. });
  1293. }]
  1294. );
  1295. return injector;
  1296. };
  1297. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1298. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1299. return doBootstrap();
  1300. }
  1301. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1302. angular.resumeBootstrap = function(extraModules) {
  1303. forEach(extraModules, function(module) {
  1304. modules.push(module);
  1305. });
  1306. doBootstrap();
  1307. };
  1308. }
  1309. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1310. function snake_case(name, separator) {
  1311. separator = separator || '_';
  1312. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1313. return (pos ? separator : '') + letter.toLowerCase();
  1314. });
  1315. }
  1316. function bindJQuery() {
  1317. // bind to jQuery if present;
  1318. jQuery = window.jQuery;
  1319. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1320. // Angular 1.2+ requires jQuery 1.7.1+ for on()/off() support.
  1321. if (jQuery && jQuery.fn.on) {
  1322. jqLite = jQuery;
  1323. extend(jQuery.fn, {
  1324. scope: JQLitePrototype.scope,
  1325. isolateScope: JQLitePrototype.isolateScope,
  1326. controller: JQLitePrototype.controller,
  1327. injector: JQLitePrototype.injector,
  1328. inheritedData: JQLitePrototype.inheritedData
  1329. });
  1330. // Method signature:
  1331. // jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
  1332. jqLitePatchJQueryRemove('remove', true, true, false);
  1333. jqLitePatchJQueryRemove('empty', false, false, false);
  1334. jqLitePatchJQueryRemove('html', false, false, true);
  1335. } else {
  1336. jqLite = JQLite;
  1337. }
  1338. angular.element = jqLite;
  1339. }
  1340. /**
  1341. * throw error if the argument is falsy.
  1342. */
  1343. function assertArg(arg, name, reason) {
  1344. if (!arg) {
  1345. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1346. }
  1347. return arg;
  1348. }
  1349. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1350. if (acceptArrayAnnotation && isArray(arg)) {
  1351. arg = arg[arg.length - 1];
  1352. }
  1353. assertArg(isFunction(arg), name, 'not a function, got ' +
  1354. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1355. return arg;
  1356. }
  1357. /**
  1358. * throw error if the name given is hasOwnProperty
  1359. * @param {String} name the name to test
  1360. * @param {String} context the context in which the name is used, such as module or directive
  1361. */
  1362. function assertNotHasOwnProperty(name, context) {
  1363. if (name === 'hasOwnProperty') {
  1364. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1365. }
  1366. }
  1367. /**
  1368. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1369. * @param {Object} obj starting object
  1370. * @param {String} path path to traverse
  1371. * @param {boolean} [bindFnToScope=true]
  1372. * @returns {Object} value as accessible by path
  1373. */
  1374. //TODO(misko): this function needs to be removed
  1375. function getter(obj, path, bindFnToScope) {
  1376. if (!path) return obj;
  1377. var keys = path.split('.');
  1378. var key;
  1379. var lastInstance = obj;
  1380. var len = keys.length;
  1381. for (var i = 0; i < len; i++) {
  1382. key = keys[i];
  1383. if (obj) {
  1384. obj = (lastInstance = obj)[key];
  1385. }
  1386. }
  1387. if (!bindFnToScope && isFunction(obj)) {
  1388. return bind(lastInstance, obj);
  1389. }
  1390. return obj;
  1391. }
  1392. /**
  1393. * Return the DOM siblings between the first and last node in the given array.
  1394. * @param {Array} array like object
  1395. * @returns {DOMElement} object containing the elements
  1396. */
  1397. function getBlockElements(nodes) {
  1398. var startNode = nodes[0],
  1399. endNode = nodes[nodes.length - 1];
  1400. if (startNode === endNode) {
  1401. return jqLite(startNode);
  1402. }
  1403. var element = startNode;
  1404. var elements = [element];
  1405. do {
  1406. element = element.nextSibling;
  1407. if (!element) break;
  1408. elements.push(element);
  1409. } while (element !== endNode);
  1410. return jqLite(elements);
  1411. }
  1412. /**
  1413. * @ngdoc type
  1414. * @name angular.Module
  1415. * @module ng
  1416. * @description
  1417. *
  1418. * Interface for configuring angular {@link angular.module modules}.
  1419. */
  1420. function setupModuleLoader(window) {
  1421. var $injectorMinErr = minErr('$injector');
  1422. var ngMinErr = minErr('ng');
  1423. function ensure(obj, name, factory) {
  1424. return obj[name] || (obj[name] = factory());
  1425. }
  1426. var angular = ensure(window, 'angular', Object);
  1427. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1428. angular.$$minErr = angular.$$minErr || minErr;
  1429. return ensure(angular, 'module', function() {
  1430. /** @type {Object.<string, angular.Module>} */
  1431. var modules = {};
  1432. /**
  1433. * @ngdoc function
  1434. * @name angular.module
  1435. * @module ng
  1436. * @description
  1437. *
  1438. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1439. * modules.
  1440. * All modules (angular core or 3rd party) that should be available to an application must be
  1441. * registered using this mechanism.
  1442. *
  1443. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1444. * existing module (the name passed as the first argument to `module`) is retrieved.
  1445. *
  1446. *
  1447. * # Module
  1448. *
  1449. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1450. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1451. *
  1452. * ```js
  1453. * // Create a new module
  1454. * var myModule = angular.module('myModule', []);
  1455. *
  1456. * // register a new service
  1457. * myModule.value('appName', 'MyCoolApp');
  1458. *
  1459. * // configure existing services inside initialization blocks.
  1460. * myModule.config(['$locationProvider', function($locationProvider) {
  1461. * // Configure existing providers
  1462. * $locationProvider.hashPrefix('!');
  1463. * }]);
  1464. * ```
  1465. *
  1466. * Then you can create an injector and load your modules like this:
  1467. *
  1468. * ```js
  1469. * var injector = angular.injector(['ng', 'myModule'])
  1470. * ```
  1471. *
  1472. * However it's more likely that you'll just use
  1473. * {@link ng.directive:ngApp ngApp} or
  1474. * {@link angular.bootstrap} to simplify this process for you.
  1475. *
  1476. * @param {!string} name The name of the module to create or retrieve.
  1477. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1478. * unspecified then the module is being retrieved for further configuration.
  1479. * @param {Function=} configFn Optional configuration function for the module. Same as
  1480. * {@link angular.Module#config Module#config()}.
  1481. * @returns {module} new module with the {@link angular.Module} api.
  1482. */
  1483. return function module(name, requires, configFn) {
  1484. var assertNotHasOwnProperty = function(name, context) {
  1485. if (name === 'hasOwnProperty') {
  1486. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1487. }
  1488. };
  1489. assertNotHasOwnProperty(name, 'module');
  1490. if (requires && modules.hasOwnProperty(name)) {
  1491. modules[name] = null;
  1492. }
  1493. return ensure(modules, name, function() {
  1494. if (!requires) {
  1495. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1496. "the module name or forgot to load it. If registering a module ensure that you " +
  1497. "specify the dependencies as the second argument.", name);
  1498. }
  1499. /** @type {!Array.<Array.<*>>} */
  1500. var invokeQueue = [];
  1501. /** @type {!Array.<Function>} */
  1502. var runBlocks = [];
  1503. var config = invokeLater('$injector', 'invoke');
  1504. /** @type {angular.Module} */
  1505. var moduleInstance = {
  1506. // Private state
  1507. _invokeQueue: invokeQueue,
  1508. _runBlocks: runBlocks,
  1509. /**
  1510. * @ngdoc property
  1511. * @name angular.Module#requires
  1512. * @module ng
  1513. * @returns {Array.<string>} List of module names which must be loaded before this module.
  1514. * @description
  1515. * Holds the list of modules which the injector will load before the current module is
  1516. * loaded.
  1517. */
  1518. requires: requires,
  1519. /**
  1520. * @ngdoc property
  1521. * @name angular.Module#name
  1522. * @module ng
  1523. * @returns {string} Name of the module.
  1524. * @description
  1525. */
  1526. name: name,
  1527. /**
  1528. * @ngdoc method
  1529. * @name angular.Module#provider
  1530. * @module ng
  1531. * @param {string} name service name
  1532. * @param {Function} providerType Construction function for creating new instance of the
  1533. * service.
  1534. * @description
  1535. * See {@link auto.$provide#provider $provide.provider()}.
  1536. */
  1537. provider: invokeLater('$provide', 'provider'),
  1538. /**
  1539. * @ngdoc method
  1540. * @name angular.Module#factory
  1541. * @module ng
  1542. * @param {string} name service name
  1543. * @param {Function} providerFunction Function for creating new instance of the service.
  1544. * @description
  1545. * See {@link auto.$provide#factory $provide.factory()}.
  1546. */
  1547. factory: invokeLater('$provide', 'factory'),
  1548. /**
  1549. * @ngdoc method
  1550. * @name angular.Module#service
  1551. * @module ng
  1552. * @param {string} name service name
  1553. * @param {Function} constructor A constructor function that will be instantiated.
  1554. * @description
  1555. * See {@link auto.$provide#service $provide.service()}.
  1556. */
  1557. service: invokeLater('$provide', 'service'),
  1558. /**
  1559. * @ngdoc method
  1560. * @name angular.Module#value
  1561. * @module ng
  1562. * @param {string} name service name
  1563. * @param {*} object Service instance object.
  1564. * @description
  1565. * See {@link auto.$provide#value $provide.value()}.
  1566. */
  1567. value: invokeLater('$provide', 'value'),
  1568. /**
  1569. * @ngdoc method
  1570. * @name angular.Module#constant
  1571. * @module ng
  1572. * @param {string} name constant name
  1573. * @param {*} object Constant value.
  1574. * @description
  1575. * Because the constant are fixed, they get applied before other provide methods.
  1576. * See {@link auto.$provide#constant $provide.constant()}.
  1577. */
  1578. constant: invokeLater('$provide', 'constant', 'unshift'),
  1579. /**
  1580. * @ngdoc method
  1581. * @name angular.Module#animation
  1582. * @module ng
  1583. * @param {string} name animation name
  1584. * @param {Function} animationFactory Factory function for creating new instance of an
  1585. * animation.
  1586. * @description
  1587. *
  1588. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1589. *
  1590. *
  1591. * Defines an animation hook that can be later used with
  1592. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1593. *
  1594. * ```js
  1595. * module.animation('.animation-name', function($inject1, $inject2) {
  1596. * return {
  1597. * eventName : function(element, done) {
  1598. * //code to run the animation
  1599. * //once complete, then run done()
  1600. * return function cancellationFunction(element) {
  1601. * //code to cancel the animation
  1602. * }
  1603. * }
  1604. * }
  1605. * })
  1606. * ```
  1607. *
  1608. * See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
  1609. * {@link ngAnimate ngAnimate module} for more information.
  1610. */
  1611. animation: invokeLater('$animateProvider', 'register'),
  1612. /**
  1613. * @ngdoc method
  1614. * @name angular.Module#filter
  1615. * @module ng
  1616. * @param {string} name Filter name.
  1617. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1618. * @description
  1619. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1620. */
  1621. filter: invokeLater('$filterProvider', 'register'),
  1622. /**
  1623. * @ngdoc method
  1624. * @name angular.Module#controller
  1625. * @module ng
  1626. * @param {string|Object} name Controller name, or an object map of controllers where the
  1627. * keys are the names and the values are the constructors.
  1628. * @param {Function} constructor Controller constructor function.
  1629. * @description
  1630. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1631. */
  1632. controller: invokeLater('$controllerProvider', 'register'),
  1633. /**
  1634. * @ngdoc method
  1635. * @name angular.Module#directive
  1636. * @module ng
  1637. * @param {string|Object} name Directive name, or an object map of directives where the
  1638. * keys are the names and the values are the factories.
  1639. * @param {Function} directiveFactory Factory function for creating new instance of
  1640. * directives.
  1641. * @description
  1642. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1643. */
  1644. directive: invokeLater('$compileProvider', 'directive'),
  1645. /**
  1646. * @ngdoc method
  1647. * @name angular.Module#config
  1648. * @module ng
  1649. * @param {Function} configFn Execute this function on module load. Useful for service
  1650. * configuration.
  1651. * @description
  1652. * Use this method to register work which needs to be performed on module loading.
  1653. * For more about how to configure services, see
  1654. * {@link providers#providers_provider-recipe Provider Recipe}.
  1655. */
  1656. config: config,
  1657. /**
  1658. * @ngdoc method
  1659. * @name angular.Module#run
  1660. * @module ng
  1661. * @param {Function} initializationFn Execute this function after injector creation.
  1662. * Useful for application initialization.
  1663. * @description
  1664. * Use this method to register work which should be performed when the injector is done
  1665. * loading all modules.
  1666. */
  1667. run: function(block) {
  1668. runBlocks.push(block);
  1669. return this;
  1670. }
  1671. };
  1672. if (configFn) {
  1673. config(configFn);
  1674. }
  1675. return moduleInstance;
  1676. /**
  1677. * @param {string} provider
  1678. * @param {string} method
  1679. * @param {String=} insertMethod
  1680. * @returns {angular.Module}
  1681. */
  1682. function invokeLater(provider, method, insertMethod) {
  1683. return function() {
  1684. invokeQueue[insertMethod || 'push']([provider, method, arguments]);
  1685. return moduleInstance;
  1686. };
  1687. }
  1688. });
  1689. };
  1690. });
  1691. }
  1692. /* global angularModule: true,
  1693. version: true,
  1694. $LocaleProvider,
  1695. $CompileProvider,
  1696. htmlAnchorDirective,
  1697. inputDirective,
  1698. inputDirective,
  1699. formDirective,
  1700. scriptDirective,
  1701. selectDirective,
  1702. styleDirective,
  1703. optionDirective,
  1704. ngBindDirective,
  1705. ngBindHtmlDirective,
  1706. ngBindTemplateDirective,
  1707. ngClassDirective,
  1708. ngClassEvenDirective,
  1709. ngClassOddDirective,
  1710. ngCspDirective,
  1711. ngCloakDirective,
  1712. ngControllerDirective,
  1713. ngFormDirective,
  1714. ngHideDirective,
  1715. ngIfDirective,
  1716. ngIncludeDirective,
  1717. ngIncludeFillContentDirective,
  1718. ngInitDirective,
  1719. ngNonBindableDirective,
  1720. ngPluralizeDirective,
  1721. ngRepeatDirective,
  1722. ngShowDirective,
  1723. ngStyleDirective,
  1724. ngSwitchDirective,
  1725. ngSwitchWhenDirective,
  1726. ngSwitchDefaultDirective,
  1727. ngOptionsDirective,
  1728. ngTranscludeDirective,
  1729. ngModelDirective,
  1730. ngListDirective,
  1731. ngChangeDirective,
  1732. requiredDirective,
  1733. requiredDirective,
  1734. ngValueDirective,
  1735. ngAttributeAliasDirectives,
  1736. ngEventDirectives,
  1737. $AnchorScrollProvider,
  1738. $AnimateProvider,
  1739. $BrowserProvider,
  1740. $CacheFactoryProvider,
  1741. $ControllerProvider,
  1742. $DocumentProvider,
  1743. $ExceptionHandlerProvider,
  1744. $FilterProvider,
  1745. $InterpolateProvider,
  1746. $IntervalProvider,
  1747. $HttpProvider,
  1748. $HttpBackendProvider,
  1749. $LocationProvider,
  1750. $LogProvider,
  1751. $ParseProvider,
  1752. $RootScopeProvider,
  1753. $QProvider,
  1754. $$SanitizeUriProvider,
  1755. $SceProvider,
  1756. $SceDelegateProvider,
  1757. $SnifferProvider,
  1758. $TemplateCacheProvider,
  1759. $TimeoutProvider,
  1760. $$RAFProvider,
  1761. $$AsyncCallbackProvider,
  1762. $WindowProvider
  1763. */
  1764. /**
  1765. * @ngdoc object
  1766. * @name angular.version
  1767. * @module ng
  1768. * @description
  1769. * An object that contains information about the current AngularJS version. This object has the
  1770. * following properties:
  1771. *
  1772. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1773. * - `major` – `{number}` – Major version number, such as "0".
  1774. * - `minor` – `{number}` – Minor version number, such as "9".
  1775. * - `dot` – `{number}` – Dot version number, such as "18".
  1776. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1777. */
  1778. var version = {
  1779. full: '1.2.21', // all of these placeholder strings will be replaced by grunt's
  1780. major: 1, // package task
  1781. minor: 2,
  1782. dot: 21,
  1783. codeName: 'wizard-props'
  1784. };
  1785. function publishExternalAPI(angular){
  1786. extend(angular, {
  1787. 'bootstrap': bootstrap,
  1788. 'copy': copy,
  1789. 'extend': extend,
  1790. 'equals': equals,
  1791. 'element': jqLite,
  1792. 'forEach': forEach,
  1793. 'injector': createInjector,
  1794. 'noop':noop,
  1795. 'bind':bind,
  1796. 'toJson': toJson,
  1797. 'fromJson': fromJson,
  1798. 'identity':identity,
  1799. 'isUndefined': isUndefined,
  1800. 'isDefined': isDefined,
  1801. 'isString': isString,
  1802. 'isFunction': isFunction,
  1803. 'isObject': isObject,
  1804. 'isNumber': isNumber,
  1805. 'isElement': isElement,
  1806. 'isArray': isArray,
  1807. 'version': version,
  1808. 'isDate': isDate,
  1809. 'lowercase': lowercase,
  1810. 'uppercase': uppercase,
  1811. 'callbacks': {counter: 0},
  1812. '$$minErr': minErr,
  1813. '$$csp': csp
  1814. });
  1815. angularModule = setupModuleLoader(window);
  1816. try {
  1817. angularModule('ngLocale');
  1818. } catch (e) {
  1819. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1820. }
  1821. angularModule('ng', ['ngLocale'], ['$provide',
  1822. function ngModule($provide) {
  1823. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1824. $provide.provider({
  1825. $$sanitizeUri: $$SanitizeUriProvider
  1826. });
  1827. $provide.provider('$compile', $CompileProvider).
  1828. directive({
  1829. a: htmlAnchorDirective,
  1830. input: inputDirective,
  1831. textarea: inputDirective,
  1832. form: formDirective,
  1833. script: scriptDirective,
  1834. select: selectDirective,
  1835. style: styleDirective,
  1836. option: optionDirective,
  1837. ngBind: ngBindDirective,
  1838. ngBindHtml: ngBindHtmlDirective,
  1839. ngBindTemplate: ngBindTemplateDirective,
  1840. ngClass: ngClassDirective,
  1841. ngClassEven: ngClassEvenDirective,
  1842. ngClassOdd: ngClassOddDirective,
  1843. ngCloak: ngCloakDirective,
  1844. ngController: ngControllerDirective,
  1845. ngForm: ngFormDirective,
  1846. ngHide: ngHideDirective,
  1847. ngIf: ngIfDirective,
  1848. ngInclude: ngIncludeDirective,
  1849. ngInit: ngInitDirective,
  1850. ngNonBindable: ngNonBindableDirective,
  1851. ngPluralize: ngPluralizeDirective,
  1852. ngRepeat: ngRepeatDirective,
  1853. ngShow: ngShowDirective,
  1854. ngStyle: ngStyleDirective,
  1855. ngSwitch: ngSwitchDirective,
  1856. ngSwitchWhen: ngSwitchWhenDirective,
  1857. ngSwitchDefault: ngSwitchDefaultDirective,
  1858. ngOptions: ngOptionsDirective,
  1859. ngTransclude: ngTranscludeDirective,
  1860. ngModel: ngModelDirective,
  1861. ngList: ngListDirective,
  1862. ngChange: ngChangeDirective,
  1863. required: requiredDirective,
  1864. ngRequired: requiredDirective,
  1865. ngValue: ngValueDirective
  1866. }).
  1867. directive({
  1868. ngInclude: ngIncludeFillContentDirective
  1869. }).
  1870. directive(ngAttributeAliasDirectives).
  1871. directive(ngEventDirectives);
  1872. $provide.provider({
  1873. $anchorScroll: $AnchorScrollProvider,
  1874. $animate: $AnimateProvider,
  1875. $browser: $BrowserProvider,
  1876. $cacheFactory: $CacheFactoryProvider,
  1877. $controller: $ControllerProvider,
  1878. $document: $DocumentProvider,
  1879. $exceptionHandler: $ExceptionHandlerProvider,
  1880. $filter: $FilterProvider,
  1881. $interpolate: $InterpolateProvider,
  1882. $interval: $IntervalProvider,
  1883. $http: $HttpProvider,
  1884. $httpBackend: $HttpBackendProvider,
  1885. $location: $LocationProvider,
  1886. $log: $LogProvider,
  1887. $parse: $ParseProvider,
  1888. $rootScope: $RootScopeProvider,
  1889. $q: $QProvider,
  1890. $sce: $SceProvider,
  1891. $sceDelegate: $SceDelegateProvider,
  1892. $sniffer: $SnifferProvider,
  1893. $templateCache: $TemplateCacheProvider,
  1894. $timeout: $TimeoutProvider,
  1895. $window: $WindowProvider,
  1896. $$rAF: $$RAFProvider,
  1897. $$asyncCallback : $$AsyncCallbackProvider
  1898. });
  1899. }
  1900. ]);
  1901. }
  1902. /* global JQLitePrototype: true,
  1903. addEventListenerFn: true,
  1904. removeEventListenerFn: true,
  1905. BOOLEAN_ATTR: true
  1906. */
  1907. //////////////////////////////////
  1908. //JQLite
  1909. //////////////////////////////////
  1910. /**
  1911. * @ngdoc function
  1912. * @name angular.element
  1913. * @module ng
  1914. * @kind function
  1915. *
  1916. * @description
  1917. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  1918. *
  1919. * If jQuery is available, `angular.element` is an alias for the
  1920. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  1921. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  1922. *
  1923. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  1924. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  1925. * commonly needed functionality with the goal of having a very small footprint.</div>
  1926. *
  1927. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  1928. *
  1929. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  1930. * jqLite; they are never raw DOM references.</div>
  1931. *
  1932. * ## Angular's jqLite
  1933. * jqLite provides only the following jQuery methods:
  1934. *
  1935. * - [`addClass()`](http://api.jquery.com/addClass/)
  1936. * - [`after()`](http://api.jquery.com/after/)
  1937. * - [`append()`](http://api.jquery.com/append/)
  1938. * - [`attr()`](http://api.jquery.com/attr/)
  1939. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  1940. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  1941. * - [`clone()`](http://api.jquery.com/clone/)
  1942. * - [`contents()`](http://api.jquery.com/contents/)
  1943. * - [`css()`](http://api.jquery.com/css/)
  1944. * - [`data()`](http://api.jquery.com/data/)
  1945. * - [`empty()`](http://api.jquery.com/empty/)
  1946. * - [`eq()`](http://api.jquery.com/eq/)
  1947. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  1948. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  1949. * - [`html()`](http://api.jquery.com/html/)
  1950. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  1951. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  1952. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  1953. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  1954. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  1955. * - [`prepend()`](http://api.jquery.com/prepend/)
  1956. * - [`prop()`](http://api.jquery.com/prop/)
  1957. * - [`ready()`](http://api.jquery.com/ready/)
  1958. * - [`remove()`](http://api.jquery.com/remove/)
  1959. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  1960. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  1961. * - [`removeData()`](http://api.jquery.com/removeData/)
  1962. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  1963. * - [`text()`](http://api.jquery.com/text/)
  1964. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  1965. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  1966. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  1967. * - [`val()`](http://api.jquery.com/val/)
  1968. * - [`wrap()`](http://api.jquery.com/wrap/)
  1969. *
  1970. * ## jQuery/jqLite Extras
  1971. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  1972. *
  1973. * ### Events
  1974. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  1975. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  1976. * element before it is removed.
  1977. *
  1978. * ### Methods
  1979. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  1980. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  1981. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  1982. * `'ngModel'`).
  1983. * - `injector()` - retrieves the injector of the current element or its parent.
  1984. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  1985. * element or its parent.
  1986. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  1987. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  1988. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  1989. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  1990. * parent element is reached.
  1991. *
  1992. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  1993. * @returns {Object} jQuery object.
  1994. */
  1995. JQLite.expando = 'ng339';
  1996. var jqCache = JQLite.cache = {},
  1997. jqId = 1,
  1998. addEventListenerFn = (window.document.addEventListener
  1999. ? function(element, type, fn) {element.addEventListener(type, fn, false);}
  2000. : function(element, type, fn) {element.attachEvent('on' + type, fn);}),
  2001. removeEventListenerFn = (window.document.removeEventListener
  2002. ? function(element, type, fn) {element.removeEventListener(type, fn, false); }
  2003. : function(element, type, fn) {element.detachEvent('on' + type, fn); });
  2004. /*
  2005. * !!! This is an undocumented "private" function !!!
  2006. */
  2007. var jqData = JQLite._data = function(node) {
  2008. //jQuery always returns an object on cache miss
  2009. return this.cache[node[this.expando]] || {};
  2010. };
  2011. function jqNextId() { return ++jqId; }
  2012. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2013. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2014. var jqLiteMinErr = minErr('jqLite');
  2015. /**
  2016. * Converts snake_case to camelCase.
  2017. * Also there is special case for Moz prefix starting with upper case letter.
  2018. * @param name Name to normalize
  2019. */
  2020. function camelCase(name) {
  2021. return name.
  2022. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2023. return offset ? letter.toUpperCase() : letter;
  2024. }).
  2025. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2026. }
  2027. /////////////////////////////////////////////
  2028. // jQuery mutation patch
  2029. //
  2030. // In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
  2031. // $destroy event on all DOM nodes being removed.
  2032. //
  2033. /////////////////////////////////////////////
  2034. function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
  2035. var originalJqFn = jQuery.fn[name];
  2036. originalJqFn = originalJqFn.$original || originalJqFn;
  2037. removePatch.$original = originalJqFn;
  2038. jQuery.fn[name] = removePatch;
  2039. function removePatch(param) {
  2040. // jshint -W040
  2041. var list = filterElems && param ? [this.filter(param)] : [this],
  2042. fireEvent = dispatchThis,
  2043. set, setIndex, setLength,
  2044. element, childIndex, childLength, children;
  2045. if (!getterIfNoArguments || param != null) {
  2046. while(list.length) {
  2047. set = list.shift();
  2048. for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
  2049. element = jqLite(set[setIndex]);
  2050. if (fireEvent) {
  2051. element.triggerHandler('$destroy');
  2052. } else {
  2053. fireEvent = !fireEvent;
  2054. }
  2055. for(childIndex = 0, childLength = (children = element.children()).length;
  2056. childIndex < childLength;
  2057. childIndex++) {
  2058. list.push(jQuery(children[childIndex]));
  2059. }
  2060. }
  2061. }
  2062. }
  2063. return originalJqFn.apply(this, arguments);
  2064. }
  2065. }
  2066. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2067. var HTML_REGEXP = /<|&#?\w+;/;
  2068. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2069. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2070. var wrapMap = {
  2071. 'option': [1, '<select multiple="multiple">', '</select>'],
  2072. 'thead': [1, '<table>', '</table>'],
  2073. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2074. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2075. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2076. '_default': [0, "", ""]
  2077. };
  2078. wrapMap.optgroup = wrapMap.option;
  2079. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2080. wrapMap.th = wrapMap.td;
  2081. function jqLiteIsTextNode(html) {
  2082. return !HTML_REGEXP.test(html);
  2083. }
  2084. function jqLiteBuildFragment(html, context) {
  2085. var elem, tmp, tag, wrap,
  2086. fragment = context.createDocumentFragment(),
  2087. nodes = [], i, j, jj;
  2088. if (jqLiteIsTextNode(html)) {
  2089. // Convert non-html into a text node
  2090. nodes.push(context.createTextNode(html));
  2091. } else {
  2092. tmp = fragment.appendChild(context.createElement('div'));
  2093. // Convert html into DOM nodes
  2094. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2095. wrap = wrapMap[tag] || wrapMap._default;
  2096. tmp.innerHTML = '<div>&#160;</div>' +
  2097. wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2098. tmp.removeChild(tmp.firstChild);
  2099. // Descend through wrappers to the right content
  2100. i = wrap[0];
  2101. while (i--) {
  2102. tmp = tmp.lastChild;
  2103. }
  2104. for (j=0, jj=tmp.childNodes.length; j<jj; ++j) nodes.push(tmp.childNodes[j]);
  2105. tmp = fragment.firstChild;
  2106. tmp.textContent = "";
  2107. }
  2108. // Remove wrapper from fragment
  2109. fragment.textContent = "";
  2110. fragment.innerHTML = ""; // Clear inner HTML
  2111. return nodes;
  2112. }
  2113. function jqLiteParseHTML(html, context) {
  2114. context = context || document;
  2115. var parsed;
  2116. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2117. return [context.createElement(parsed[1])];
  2118. }
  2119. return jqLiteBuildFragment(html, context);
  2120. }
  2121. /////////////////////////////////////////////
  2122. function JQLite(element) {
  2123. if (element instanceof JQLite) {
  2124. return element;
  2125. }
  2126. if (isString(element)) {
  2127. element = trim(element);
  2128. }
  2129. if (!(this instanceof JQLite)) {
  2130. if (isString(element) && element.charAt(0) != '<') {
  2131. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2132. }
  2133. return new JQLite(element);
  2134. }
  2135. if (isString(element)) {
  2136. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2137. var fragment = jqLite(document.createDocumentFragment());
  2138. fragment.append(this);
  2139. } else {
  2140. jqLiteAddNodes(this, element);
  2141. }
  2142. }
  2143. function jqLiteClone(element) {
  2144. return element.cloneNode(true);
  2145. }
  2146. function jqLiteDealoc(element){
  2147. jqLiteRemoveData(element);
  2148. for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
  2149. jqLiteDealoc(children[i]);
  2150. }
  2151. }
  2152. function jqLiteOff(element, type, fn, unsupported) {
  2153. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2154. var events = jqLiteExpandoStore(element, 'events'),
  2155. handle = jqLiteExpandoStore(element, 'handle');
  2156. if (!handle) return; //no listeners registered
  2157. if (isUndefined(type)) {
  2158. forEach(events, function(eventHandler, type) {
  2159. removeEventListenerFn(element, type, eventHandler);
  2160. delete events[type];
  2161. });
  2162. } else {
  2163. forEach(type.split(' '), function(type) {
  2164. if (isUndefined(fn)) {
  2165. removeEventListenerFn(element, type, events[type]);
  2166. delete events[type];
  2167. } else {
  2168. arrayRemove(events[type] || [], fn);
  2169. }
  2170. });
  2171. }
  2172. }
  2173. function jqLiteRemoveData(element, name) {
  2174. var expandoId = element.ng339,
  2175. expandoStore = jqCache[expandoId];
  2176. if (expandoStore) {
  2177. if (name) {
  2178. delete jqCache[expandoId].data[name];
  2179. return;
  2180. }
  2181. if (expandoStore.handle) {
  2182. expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
  2183. jqLiteOff(element);
  2184. }
  2185. delete jqCache[expandoId];
  2186. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2187. }
  2188. }
  2189. function jqLiteExpandoStore(element, key, value) {
  2190. var expandoId = element.ng339,
  2191. expandoStore = jqCache[expandoId || -1];
  2192. if (isDefined(value)) {
  2193. if (!expandoStore) {
  2194. element.ng339 = expandoId = jqNextId();
  2195. expandoStore = jqCache[expandoId] = {};
  2196. }
  2197. expandoStore[key] = value;
  2198. } else {
  2199. return expandoStore && expandoStore[key];
  2200. }
  2201. }
  2202. function jqLiteData(element, key, value) {
  2203. var data = jqLiteExpandoStore(element, 'data'),
  2204. isSetter = isDefined(value),
  2205. keyDefined = !isSetter && isDefined(key),
  2206. isSimpleGetter = keyDefined && !isObject(key);
  2207. if (!data && !isSimpleGetter) {
  2208. jqLiteExpandoStore(element, 'data', data = {});
  2209. }
  2210. if (isSetter) {
  2211. data[key] = value;
  2212. } else {
  2213. if (keyDefined) {
  2214. if (isSimpleGetter) {
  2215. // don't create data in this case.
  2216. return data && data[key];
  2217. } else {
  2218. extend(data, key);
  2219. }
  2220. } else {
  2221. return data;
  2222. }
  2223. }
  2224. }
  2225. function jqLiteHasClass(element, selector) {
  2226. if (!element.getAttribute) return false;
  2227. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2228. indexOf( " " + selector + " " ) > -1);
  2229. }
  2230. function jqLiteRemoveClass(element, cssClasses) {
  2231. if (cssClasses && element.setAttribute) {
  2232. forEach(cssClasses.split(' '), function(cssClass) {
  2233. element.setAttribute('class', trim(
  2234. (" " + (element.getAttribute('class') || '') + " ")
  2235. .replace(/[\n\t]/g, " ")
  2236. .replace(" " + trim(cssClass) + " ", " "))
  2237. );
  2238. });
  2239. }
  2240. }
  2241. function jqLiteAddClass(element, cssClasses) {
  2242. if (cssClasses && element.setAttribute) {
  2243. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2244. .replace(/[\n\t]/g, " ");
  2245. forEach(cssClasses.split(' '), function(cssClass) {
  2246. cssClass = trim(cssClass);
  2247. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2248. existingClasses += cssClass + ' ';
  2249. }
  2250. });
  2251. element.setAttribute('class', trim(existingClasses));
  2252. }
  2253. }
  2254. function jqLiteAddNodes(root, elements) {
  2255. if (elements) {
  2256. elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
  2257. ? elements
  2258. : [ elements ];
  2259. for(var i=0; i < elements.length; i++) {
  2260. root.push(elements[i]);
  2261. }
  2262. }
  2263. }
  2264. function jqLiteController(element, name) {
  2265. return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
  2266. }
  2267. function jqLiteInheritedData(element, name, value) {
  2268. // if element is the document object work with the html element instead
  2269. // this makes $(document).scope() possible
  2270. if(element.nodeType == 9) {
  2271. element = element.documentElement;
  2272. }
  2273. var names = isArray(name) ? name : [name];
  2274. while (element) {
  2275. for (var i = 0, ii = names.length; i < ii; i++) {
  2276. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2277. }
  2278. // If dealing with a document fragment node with a host element, and no parent, use the host
  2279. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2280. // to lookup parent controllers.
  2281. element = element.parentNode || (element.nodeType === 11 && element.host);
  2282. }
  2283. }
  2284. function jqLiteEmpty(element) {
  2285. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2286. jqLiteDealoc(childNodes[i]);
  2287. }
  2288. while (element.firstChild) {
  2289. element.removeChild(element.firstChild);
  2290. }
  2291. }
  2292. //////////////////////////////////////////
  2293. // Functions which are declared directly.
  2294. //////////////////////////////////////////
  2295. var JQLitePrototype = JQLite.prototype = {
  2296. ready: function(fn) {
  2297. var fired = false;
  2298. function trigger() {
  2299. if (fired) return;
  2300. fired = true;
  2301. fn();
  2302. }
  2303. // check if document already is loaded
  2304. if (document.readyState === 'complete'){
  2305. setTimeout(trigger);
  2306. } else {
  2307. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2308. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2309. // jshint -W064
  2310. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2311. // jshint +W064
  2312. }
  2313. },
  2314. toString: function() {
  2315. var value = [];
  2316. forEach(this, function(e){ value.push('' + e);});
  2317. return '[' + value.join(', ') + ']';
  2318. },
  2319. eq: function(index) {
  2320. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2321. },
  2322. length: 0,
  2323. push: push,
  2324. sort: [].sort,
  2325. splice: [].splice
  2326. };
  2327. //////////////////////////////////////////
  2328. // Functions iterating getter/setters.
  2329. // these functions return self on setter and
  2330. // value on get.
  2331. //////////////////////////////////////////
  2332. var BOOLEAN_ATTR = {};
  2333. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2334. BOOLEAN_ATTR[lowercase(value)] = value;
  2335. });
  2336. var BOOLEAN_ELEMENTS = {};
  2337. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2338. BOOLEAN_ELEMENTS[uppercase(value)] = true;
  2339. });
  2340. function getBooleanAttrName(element, name) {
  2341. // check dom last since we will most likely fail on name
  2342. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2343. // booleanAttr is here twice to minimize DOM access
  2344. return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
  2345. }
  2346. forEach({
  2347. data: jqLiteData,
  2348. removeData: jqLiteRemoveData
  2349. }, function(fn, name) {
  2350. JQLite[name] = fn;
  2351. });
  2352. forEach({
  2353. data: jqLiteData,
  2354. inheritedData: jqLiteInheritedData,
  2355. scope: function(element) {
  2356. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2357. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2358. },
  2359. isolateScope: function(element) {
  2360. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2361. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2362. },
  2363. controller: jqLiteController,
  2364. injector: function(element) {
  2365. return jqLiteInheritedData(element, '$injector');
  2366. },
  2367. removeAttr: function(element,name) {
  2368. element.removeAttribute(name);
  2369. },
  2370. hasClass: jqLiteHasClass,
  2371. css: function(element, name, value) {
  2372. name = camelCase(name);
  2373. if (isDefined(value)) {
  2374. element.style[name] = value;
  2375. } else {
  2376. var val;
  2377. if (msie <= 8) {
  2378. // this is some IE specific weirdness that jQuery 1.6.4 does not sure why
  2379. val = element.currentStyle && element.currentStyle[name];
  2380. if (val === '') val = 'auto';
  2381. }
  2382. val = val || element.style[name];
  2383. if (msie <= 8) {
  2384. // jquery weirdness :-/
  2385. val = (val === '') ? undefined : val;
  2386. }
  2387. return val;
  2388. }
  2389. },
  2390. attr: function(element, name, value){
  2391. var lowercasedName = lowercase(name);
  2392. if (BOOLEAN_ATTR[lowercasedName]) {
  2393. if (isDefined(value)) {
  2394. if (!!value) {
  2395. element[name] = true;
  2396. element.setAttribute(name, lowercasedName);
  2397. } else {
  2398. element[name] = false;
  2399. element.removeAttribute(lowercasedName);
  2400. }
  2401. } else {
  2402. return (element[name] ||
  2403. (element.attributes.getNamedItem(name)|| noop).specified)
  2404. ? lowercasedName
  2405. : undefined;
  2406. }
  2407. } else if (isDefined(value)) {
  2408. element.setAttribute(name, value);
  2409. } else if (element.getAttribute) {
  2410. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2411. // some elements (e.g. Document) don't have get attribute, so return undefined
  2412. var ret = element.getAttribute(name, 2);
  2413. // normalize non-existing attributes to undefined (as jQuery)
  2414. return ret === null ? undefined : ret;
  2415. }
  2416. },
  2417. prop: function(element, name, value) {
  2418. if (isDefined(value)) {
  2419. element[name] = value;
  2420. } else {
  2421. return element[name];
  2422. }
  2423. },
  2424. text: (function() {
  2425. var NODE_TYPE_TEXT_PROPERTY = [];
  2426. if (msie < 9) {
  2427. NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
  2428. NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
  2429. } else {
  2430. NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
  2431. NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
  2432. }
  2433. getText.$dv = '';
  2434. return getText;
  2435. function getText(element, value) {
  2436. var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
  2437. if (isUndefined(value)) {
  2438. return textProp ? element[textProp] : '';
  2439. }
  2440. element[textProp] = value;
  2441. }
  2442. })(),
  2443. val: function(element, value) {
  2444. if (isUndefined(value)) {
  2445. if (nodeName_(element) === 'SELECT' && element.multiple) {
  2446. var result = [];
  2447. forEach(element.options, function (option) {
  2448. if (option.selected) {
  2449. result.push(option.value || option.text);
  2450. }
  2451. });
  2452. return result.length === 0 ? null : result;
  2453. }
  2454. return element.value;
  2455. }
  2456. element.value = value;
  2457. },
  2458. html: function(element, value) {
  2459. if (isUndefined(value)) {
  2460. return element.innerHTML;
  2461. }
  2462. for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
  2463. jqLiteDealoc(childNodes[i]);
  2464. }
  2465. element.innerHTML = value;
  2466. },
  2467. empty: jqLiteEmpty
  2468. }, function(fn, name){
  2469. /**
  2470. * Properties: writes return selection, reads return first value
  2471. */
  2472. JQLite.prototype[name] = function(arg1, arg2) {
  2473. var i, key;
  2474. var nodeCount = this.length;
  2475. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2476. // in a way that survives minification.
  2477. // jqLiteEmpty takes no arguments but is a setter.
  2478. if (fn !== jqLiteEmpty &&
  2479. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2480. if (isObject(arg1)) {
  2481. // we are a write, but the object properties are the key/values
  2482. for (i = 0; i < nodeCount; i++) {
  2483. if (fn === jqLiteData) {
  2484. // data() takes the whole object in jQuery
  2485. fn(this[i], arg1);
  2486. } else {
  2487. for (key in arg1) {
  2488. fn(this[i], key, arg1[key]);
  2489. }
  2490. }
  2491. }
  2492. // return self for chaining
  2493. return this;
  2494. } else {
  2495. // we are a read, so read the first child.
  2496. // TODO: do we still need this?
  2497. var value = fn.$dv;
  2498. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2499. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2500. for (var j = 0; j < jj; j++) {
  2501. var nodeValue = fn(this[j], arg1, arg2);
  2502. value = value ? value + nodeValue : nodeValue;
  2503. }
  2504. return value;
  2505. }
  2506. } else {
  2507. // we are a write, so apply to all children
  2508. for (i = 0; i < nodeCount; i++) {
  2509. fn(this[i], arg1, arg2);
  2510. }
  2511. // return self for chaining
  2512. return this;
  2513. }
  2514. };
  2515. });
  2516. function createEventHandler(element, events) {
  2517. var eventHandler = function (event, type) {
  2518. if (!event.preventDefault) {
  2519. event.preventDefault = function() {
  2520. event.returnValue = false; //ie
  2521. };
  2522. }
  2523. if (!event.stopPropagation) {
  2524. event.stopPropagation = function() {
  2525. event.cancelBubble = true; //ie
  2526. };
  2527. }
  2528. if (!event.target) {
  2529. event.target = event.srcElement || document;
  2530. }
  2531. if (isUndefined(event.defaultPrevented)) {
  2532. var prevent = event.preventDefault;
  2533. event.preventDefault = function() {
  2534. event.defaultPrevented = true;
  2535. prevent.call(event);
  2536. };
  2537. event.defaultPrevented = false;
  2538. }
  2539. event.isDefaultPrevented = function() {
  2540. return event.defaultPrevented || event.returnValue === false;
  2541. };
  2542. // Copy event handlers in case event handlers array is modified during execution.
  2543. var eventHandlersCopy = shallowCopy(events[type || event.type] || []);
  2544. forEach(eventHandlersCopy, function(fn) {
  2545. fn.call(element, event);
  2546. });
  2547. // Remove monkey-patched methods (IE),
  2548. // as they would cause memory leaks in IE8.
  2549. if (msie <= 8) {
  2550. // IE7/8 does not allow to delete property on native object
  2551. event.preventDefault = null;
  2552. event.stopPropagation = null;
  2553. event.isDefaultPrevented = null;
  2554. } else {
  2555. // It shouldn't affect normal browsers (native methods are defined on prototype).
  2556. delete event.preventDefault;
  2557. delete event.stopPropagation;
  2558. delete event.isDefaultPrevented;
  2559. }
  2560. };
  2561. eventHandler.elem = element;
  2562. return eventHandler;
  2563. }
  2564. //////////////////////////////////////////
  2565. // Functions iterating traversal.
  2566. // These functions chain results into a single
  2567. // selector.
  2568. //////////////////////////////////////////
  2569. forEach({
  2570. removeData: jqLiteRemoveData,
  2571. dealoc: jqLiteDealoc,
  2572. on: function onFn(element, type, fn, unsupported){
  2573. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2574. var events = jqLiteExpandoStore(element, 'events'),
  2575. handle = jqLiteExpandoStore(element, 'handle');
  2576. if (!events) jqLiteExpandoStore(element, 'events', events = {});
  2577. if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
  2578. forEach(type.split(' '), function(type){
  2579. var eventFns = events[type];
  2580. if (!eventFns) {
  2581. if (type == 'mouseenter' || type == 'mouseleave') {
  2582. var contains = document.body.contains || document.body.compareDocumentPosition ?
  2583. function( a, b ) {
  2584. // jshint bitwise: false
  2585. var adown = a.nodeType === 9 ? a.documentElement : a,
  2586. bup = b && b.parentNode;
  2587. return a === bup || !!( bup && bup.nodeType === 1 && (
  2588. adown.contains ?
  2589. adown.contains( bup ) :
  2590. a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
  2591. ));
  2592. } :
  2593. function( a, b ) {
  2594. if ( b ) {
  2595. while ( (b = b.parentNode) ) {
  2596. if ( b === a ) {
  2597. return true;
  2598. }
  2599. }
  2600. }
  2601. return false;
  2602. };
  2603. events[type] = [];
  2604. // Refer to jQuery's implementation of mouseenter & mouseleave
  2605. // Read about mouseenter and mouseleave:
  2606. // http://www.quirksmode.org/js/events_mouse.html#link8
  2607. var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
  2608. onFn(element, eventmap[type], function(event) {
  2609. var target = this, related = event.relatedTarget;
  2610. // For mousenter/leave call the handler if related is outside the target.
  2611. // NB: No relatedTarget if the mouse left/entered the browser window
  2612. if ( !related || (related !== target && !contains(target, related)) ){
  2613. handle(event, type);
  2614. }
  2615. });
  2616. } else {
  2617. addEventListenerFn(element, type, handle);
  2618. events[type] = [];
  2619. }
  2620. eventFns = events[type];
  2621. }
  2622. eventFns.push(fn);
  2623. });
  2624. },
  2625. off: jqLiteOff,
  2626. one: function(element, type, fn) {
  2627. element = jqLite(element);
  2628. //add the listener twice so that when it is called
  2629. //you can remove the original function and still be
  2630. //able to call element.off(ev, fn) normally
  2631. element.on(type, function onFn() {
  2632. element.off(type, fn);
  2633. element.off(type, onFn);
  2634. });
  2635. element.on(type, fn);
  2636. },
  2637. replaceWith: function(element, replaceNode) {
  2638. var index, parent = element.parentNode;
  2639. jqLiteDealoc(element);
  2640. forEach(new JQLite(replaceNode), function(node){
  2641. if (index) {
  2642. parent.insertBefore(node, index.nextSibling);
  2643. } else {
  2644. parent.replaceChild(node, element);
  2645. }
  2646. index = node;
  2647. });
  2648. },
  2649. children: function(element) {
  2650. var children = [];
  2651. forEach(element.childNodes, function(element){
  2652. if (element.nodeType === 1)
  2653. children.push(element);
  2654. });
  2655. return children;
  2656. },
  2657. contents: function(element) {
  2658. return element.contentDocument || element.childNodes || [];
  2659. },
  2660. append: function(element, node) {
  2661. forEach(new JQLite(node), function(child){
  2662. if (element.nodeType === 1 || element.nodeType === 11) {
  2663. element.appendChild(child);
  2664. }
  2665. });
  2666. },
  2667. prepend: function(element, node) {
  2668. if (element.nodeType === 1) {
  2669. var index = element.firstChild;
  2670. forEach(new JQLite(node), function(child){
  2671. element.insertBefore(child, index);
  2672. });
  2673. }
  2674. },
  2675. wrap: function(element, wrapNode) {
  2676. wrapNode = jqLite(wrapNode)[0];
  2677. var parent = element.parentNode;
  2678. if (parent) {
  2679. parent.replaceChild(wrapNode, element);
  2680. }
  2681. wrapNode.appendChild(element);
  2682. },
  2683. remove: function(element) {
  2684. jqLiteDealoc(element);
  2685. var parent = element.parentNode;
  2686. if (parent) parent.removeChild(element);
  2687. },
  2688. after: function(element, newElement) {
  2689. var index = element, parent = element.parentNode;
  2690. forEach(new JQLite(newElement), function(node){
  2691. parent.insertBefore(node, index.nextSibling);
  2692. index = node;
  2693. });
  2694. },
  2695. addClass: jqLiteAddClass,
  2696. removeClass: jqLiteRemoveClass,
  2697. toggleClass: function(element, selector, condition) {
  2698. if (selector) {
  2699. forEach(selector.split(' '), function(className){
  2700. var classCondition = condition;
  2701. if (isUndefined(classCondition)) {
  2702. classCondition = !jqLiteHasClass(element, className);
  2703. }
  2704. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2705. });
  2706. }
  2707. },
  2708. parent: function(element) {
  2709. var parent = element.parentNode;
  2710. return parent && parent.nodeType !== 11 ? parent : null;
  2711. },
  2712. next: function(element) {
  2713. if (element.nextElementSibling) {
  2714. return element.nextElementSibling;
  2715. }
  2716. // IE8 doesn't have nextElementSibling
  2717. var elm = element.nextSibling;
  2718. while (elm != null && elm.nodeType !== 1) {
  2719. elm = elm.nextSibling;
  2720. }
  2721. return elm;
  2722. },
  2723. find: function(element, selector) {
  2724. if (element.getElementsByTagName) {
  2725. return element.getElementsByTagName(selector);
  2726. } else {
  2727. return [];
  2728. }
  2729. },
  2730. clone: jqLiteClone,
  2731. triggerHandler: function(element, eventName, eventData) {
  2732. // Copy event handlers in case event handlers array is modified during execution.
  2733. var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName],
  2734. eventFnsCopy = shallowCopy(eventFns || []);
  2735. eventData = eventData || [];
  2736. var event = [{
  2737. preventDefault: noop,
  2738. stopPropagation: noop
  2739. }];
  2740. forEach(eventFnsCopy, function(fn) {
  2741. fn.apply(element, event.concat(eventData));
  2742. });
  2743. }
  2744. }, function(fn, name){
  2745. /**
  2746. * chaining functions
  2747. */
  2748. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2749. var value;
  2750. for(var i=0; i < this.length; i++) {
  2751. if (isUndefined(value)) {
  2752. value = fn(this[i], arg1, arg2, arg3);
  2753. if (isDefined(value)) {
  2754. // any function which returns a value needs to be wrapped
  2755. value = jqLite(value);
  2756. }
  2757. } else {
  2758. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2759. }
  2760. }
  2761. return isDefined(value) ? value : this;
  2762. };
  2763. // bind legacy bind/unbind to on/off
  2764. JQLite.prototype.bind = JQLite.prototype.on;
  2765. JQLite.prototype.unbind = JQLite.prototype.off;
  2766. });
  2767. /**
  2768. * Computes a hash of an 'obj'.
  2769. * Hash of a:
  2770. * string is string
  2771. * number is number as string
  2772. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2773. * that is also assigned to the $$hashKey property of the object.
  2774. *
  2775. * @param obj
  2776. * @returns {string} hash string such that the same input will have the same hash string.
  2777. * The resulting string key is in 'type:hashKey' format.
  2778. */
  2779. function hashKey(obj, nextUidFn) {
  2780. var objType = typeof obj,
  2781. key;
  2782. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2783. if (typeof (key = obj.$$hashKey) == 'function') {
  2784. // must invoke on object to keep the right this
  2785. key = obj.$$hashKey();
  2786. } else if (key === undefined) {
  2787. key = obj.$$hashKey = (nextUidFn || nextUid)();
  2788. }
  2789. } else {
  2790. key = obj;
  2791. }
  2792. return objType + ':' + key;
  2793. }
  2794. /**
  2795. * HashMap which can use objects as keys
  2796. */
  2797. function HashMap(array, isolatedUid) {
  2798. if (isolatedUid) {
  2799. var uid = 0;
  2800. this.nextUid = function() {
  2801. return ++uid;
  2802. };
  2803. }
  2804. forEach(array, this.put, this);
  2805. }
  2806. HashMap.prototype = {
  2807. /**
  2808. * Store key value pair
  2809. * @param key key to store can be any type
  2810. * @param value value to store can be any type
  2811. */
  2812. put: function(key, value) {
  2813. this[hashKey(key, this.nextUid)] = value;
  2814. },
  2815. /**
  2816. * @param key
  2817. * @returns {Object} the value for the key
  2818. */
  2819. get: function(key) {
  2820. return this[hashKey(key, this.nextUid)];
  2821. },
  2822. /**
  2823. * Remove the key/value pair
  2824. * @param key
  2825. */
  2826. remove: function(key) {
  2827. var value = this[key = hashKey(key, this.nextUid)];
  2828. delete this[key];
  2829. return value;
  2830. }
  2831. };
  2832. /**
  2833. * @ngdoc function
  2834. * @module ng
  2835. * @name angular.injector
  2836. * @kind function
  2837. *
  2838. * @description
  2839. * Creates an injector function that can be used for retrieving services as well as for
  2840. * dependency injection (see {@link guide/di dependency injection}).
  2841. *
  2842. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2843. * {@link angular.module}. The `ng` module must be explicitly added.
  2844. * @returns {function()} Injector function. See {@link auto.$injector $injector}.
  2845. *
  2846. * @example
  2847. * Typical usage
  2848. * ```js
  2849. * // create an injector
  2850. * var $injector = angular.injector(['ng']);
  2851. *
  2852. * // use the injector to kick off your application
  2853. * // use the type inference to auto inject arguments, or use implicit injection
  2854. * $injector.invoke(function($rootScope, $compile, $document){
  2855. * $compile($document)($rootScope);
  2856. * $rootScope.$digest();
  2857. * });
  2858. * ```
  2859. *
  2860. * Sometimes you want to get access to the injector of a currently running Angular app
  2861. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2862. * application has been bootstrapped. You can do this using the extra `injector()` added
  2863. * to JQuery/jqLite elements. See {@link angular.element}.
  2864. *
  2865. * *This is fairly rare but could be the case if a third party library is injecting the
  2866. * markup.*
  2867. *
  2868. * In the following example a new block of HTML containing a `ng-controller`
  2869. * directive is added to the end of the document body by JQuery. We then compile and link
  2870. * it into the current AngularJS scope.
  2871. *
  2872. * ```js
  2873. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  2874. * $(document.body).append($div);
  2875. *
  2876. * angular.element(document).injector().invoke(function($compile) {
  2877. * var scope = angular.element($div).scope();
  2878. * $compile($div)(scope);
  2879. * });
  2880. * ```
  2881. */
  2882. /**
  2883. * @ngdoc module
  2884. * @name auto
  2885. * @description
  2886. *
  2887. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  2888. */
  2889. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  2890. var FN_ARG_SPLIT = /,/;
  2891. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  2892. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  2893. var $injectorMinErr = minErr('$injector');
  2894. function annotate(fn) {
  2895. var $inject,
  2896. fnText,
  2897. argDecl,
  2898. last;
  2899. if (typeof fn === 'function') {
  2900. if (!($inject = fn.$inject)) {
  2901. $inject = [];
  2902. if (fn.length) {
  2903. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  2904. argDecl = fnText.match(FN_ARGS);
  2905. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
  2906. arg.replace(FN_ARG, function(all, underscore, name){
  2907. $inject.push(name);
  2908. });
  2909. });
  2910. }
  2911. fn.$inject = $inject;
  2912. }
  2913. } else if (isArray(fn)) {
  2914. last = fn.length - 1;
  2915. assertArgFn(fn[last], 'fn');
  2916. $inject = fn.slice(0, last);
  2917. } else {
  2918. assertArgFn(fn, 'fn', true);
  2919. }
  2920. return $inject;
  2921. }
  2922. ///////////////////////////////////////
  2923. /**
  2924. * @ngdoc service
  2925. * @name $injector
  2926. * @kind function
  2927. *
  2928. * @description
  2929. *
  2930. * `$injector` is used to retrieve object instances as defined by
  2931. * {@link auto.$provide provider}, instantiate types, invoke methods,
  2932. * and load modules.
  2933. *
  2934. * The following always holds true:
  2935. *
  2936. * ```js
  2937. * var $injector = angular.injector();
  2938. * expect($injector.get('$injector')).toBe($injector);
  2939. * expect($injector.invoke(function($injector){
  2940. * return $injector;
  2941. * }).toBe($injector);
  2942. * ```
  2943. *
  2944. * # Injection Function Annotation
  2945. *
  2946. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  2947. * following are all valid ways of annotating function with injection arguments and are equivalent.
  2948. *
  2949. * ```js
  2950. * // inferred (only works if code not minified/obfuscated)
  2951. * $injector.invoke(function(serviceA){});
  2952. *
  2953. * // annotated
  2954. * function explicit(serviceA) {};
  2955. * explicit.$inject = ['serviceA'];
  2956. * $injector.invoke(explicit);
  2957. *
  2958. * // inline
  2959. * $injector.invoke(['serviceA', function(serviceA){}]);
  2960. * ```
  2961. *
  2962. * ## Inference
  2963. *
  2964. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  2965. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  2966. * minification, and obfuscation tools since these tools change the argument names.
  2967. *
  2968. * ## `$inject` Annotation
  2969. * By adding an `$inject` property onto a function the injection parameters can be specified.
  2970. *
  2971. * ## Inline
  2972. * As an array of injection names, where the last item in the array is the function to call.
  2973. */
  2974. /**
  2975. * @ngdoc method
  2976. * @name $injector#get
  2977. *
  2978. * @description
  2979. * Return an instance of the service.
  2980. *
  2981. * @param {string} name The name of the instance to retrieve.
  2982. * @return {*} The instance.
  2983. */
  2984. /**
  2985. * @ngdoc method
  2986. * @name $injector#invoke
  2987. *
  2988. * @description
  2989. * Invoke the method and supply the method arguments from the `$injector`.
  2990. *
  2991. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  2992. * {@link guide/di $inject Annotation} rules.
  2993. * @param {Object=} self The `this` for the invoked method.
  2994. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  2995. * object first, before the `$injector` is consulted.
  2996. * @returns {*} the value returned by the invoked `fn` function.
  2997. */
  2998. /**
  2999. * @ngdoc method
  3000. * @name $injector#has
  3001. *
  3002. * @description
  3003. * Allows the user to query if the particular service exists.
  3004. *
  3005. * @param {string} Name of the service to query.
  3006. * @returns {boolean} returns true if injector has given service.
  3007. */
  3008. /**
  3009. * @ngdoc method
  3010. * @name $injector#instantiate
  3011. * @description
  3012. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3013. * operator, and supplies all of the arguments to the constructor function as specified by the
  3014. * constructor annotation.
  3015. *
  3016. * @param {Function} Type Annotated constructor function.
  3017. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3018. * object first, before the `$injector` is consulted.
  3019. * @returns {Object} new instance of `Type`.
  3020. */
  3021. /**
  3022. * @ngdoc method
  3023. * @name $injector#annotate
  3024. *
  3025. * @description
  3026. * Returns an array of service names which the function is requesting for injection. This API is
  3027. * used by the injector to determine which services need to be injected into the function when the
  3028. * function is invoked. There are three ways in which the function can be annotated with the needed
  3029. * dependencies.
  3030. *
  3031. * # Argument names
  3032. *
  3033. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3034. * by converting the function into a string using `toString()` method and extracting the argument
  3035. * names.
  3036. * ```js
  3037. * // Given
  3038. * function MyController($scope, $route) {
  3039. * // ...
  3040. * }
  3041. *
  3042. * // Then
  3043. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3044. * ```
  3045. *
  3046. * This method does not work with code minification / obfuscation. For this reason the following
  3047. * annotation strategies are supported.
  3048. *
  3049. * # The `$inject` property
  3050. *
  3051. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3052. * represent names of services to be injected into the function.
  3053. * ```js
  3054. * // Given
  3055. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3056. * // ...
  3057. * }
  3058. * // Define function dependencies
  3059. * MyController['$inject'] = ['$scope', '$route'];
  3060. *
  3061. * // Then
  3062. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3063. * ```
  3064. *
  3065. * # The array notation
  3066. *
  3067. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3068. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3069. * a way that survives minification is a better choice:
  3070. *
  3071. * ```js
  3072. * // We wish to write this (not minification / obfuscation safe)
  3073. * injector.invoke(function($compile, $rootScope) {
  3074. * // ...
  3075. * });
  3076. *
  3077. * // We are forced to write break inlining
  3078. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3079. * // ...
  3080. * };
  3081. * tmpFn.$inject = ['$compile', '$rootScope'];
  3082. * injector.invoke(tmpFn);
  3083. *
  3084. * // To better support inline function the inline annotation is supported
  3085. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3086. * // ...
  3087. * }]);
  3088. *
  3089. * // Therefore
  3090. * expect(injector.annotate(
  3091. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3092. * ).toEqual(['$compile', '$rootScope']);
  3093. * ```
  3094. *
  3095. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3096. * be retrieved as described above.
  3097. *
  3098. * @returns {Array.<string>} The names of the services which the function requires.
  3099. */
  3100. /**
  3101. * @ngdoc service
  3102. * @name $provide
  3103. *
  3104. * @description
  3105. *
  3106. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3107. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3108. * {@link angular.Module}.
  3109. *
  3110. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3111. * factories** are functions which, in turn, are created by a **service provider**.
  3112. * The **service providers** are constructor functions. When instantiated they must contain a
  3113. * property called `$get`, which holds the **service factory** function.
  3114. *
  3115. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3116. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3117. * function to get the instance of the **service**.
  3118. *
  3119. * Often services have no configuration options and there is no need to add methods to the service
  3120. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3121. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3122. * services without specifying a provider.
  3123. *
  3124. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3125. * {@link auto.$injector $injector}
  3126. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3127. * providers and services.
  3128. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3129. * services, not providers.
  3130. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3131. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3132. * given factory function.
  3133. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3134. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3135. * a new object using the given constructor function.
  3136. *
  3137. * See the individual methods for more information and examples.
  3138. */
  3139. /**
  3140. * @ngdoc method
  3141. * @name $provide#provider
  3142. * @description
  3143. *
  3144. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3145. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3146. * service.
  3147. *
  3148. * Service provider names start with the name of the service they provide followed by `Provider`.
  3149. * For example, the {@link ng.$log $log} service has a provider called
  3150. * {@link ng.$logProvider $logProvider}.
  3151. *
  3152. * Service provider objects can have additional methods which allow configuration of the provider
  3153. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3154. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3155. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3156. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3157. * console or not.
  3158. *
  3159. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3160. 'Provider'` key.
  3161. * @param {(Object|function())} provider If the provider is:
  3162. *
  3163. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3164. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3165. * - `Constructor`: a new instance of the provider will be created using
  3166. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3167. *
  3168. * @returns {Object} registered provider instance
  3169. * @example
  3170. *
  3171. * The following example shows how to create a simple event tracking service and register it using
  3172. * {@link auto.$provide#provider $provide.provider()}.
  3173. *
  3174. * ```js
  3175. * // Define the eventTracker provider
  3176. * function EventTrackerProvider() {
  3177. * var trackingUrl = '/track';
  3178. *
  3179. * // A provider method for configuring where the tracked events should been saved
  3180. * this.setTrackingUrl = function(url) {
  3181. * trackingUrl = url;
  3182. * };
  3183. *
  3184. * // The service factory function
  3185. * this.$get = ['$http', function($http) {
  3186. * var trackedEvents = {};
  3187. * return {
  3188. * // Call this to track an event
  3189. * event: function(event) {
  3190. * var count = trackedEvents[event] || 0;
  3191. * count += 1;
  3192. * trackedEvents[event] = count;
  3193. * return count;
  3194. * },
  3195. * // Call this to save the tracked events to the trackingUrl
  3196. * save: function() {
  3197. * $http.post(trackingUrl, trackedEvents);
  3198. * }
  3199. * };
  3200. * }];
  3201. * }
  3202. *
  3203. * describe('eventTracker', function() {
  3204. * var postSpy;
  3205. *
  3206. * beforeEach(module(function($provide) {
  3207. * // Register the eventTracker provider
  3208. * $provide.provider('eventTracker', EventTrackerProvider);
  3209. * }));
  3210. *
  3211. * beforeEach(module(function(eventTrackerProvider) {
  3212. * // Configure eventTracker provider
  3213. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3214. * }));
  3215. *
  3216. * it('tracks events', inject(function(eventTracker) {
  3217. * expect(eventTracker.event('login')).toEqual(1);
  3218. * expect(eventTracker.event('login')).toEqual(2);
  3219. * }));
  3220. *
  3221. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3222. * postSpy = spyOn($http, 'post');
  3223. * eventTracker.event('login');
  3224. * eventTracker.save();
  3225. * expect(postSpy).toHaveBeenCalled();
  3226. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3227. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3228. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3229. * }));
  3230. * });
  3231. * ```
  3232. */
  3233. /**
  3234. * @ngdoc method
  3235. * @name $provide#factory
  3236. * @description
  3237. *
  3238. * Register a **service factory**, which will be called to return the service instance.
  3239. * This is short for registering a service where its provider consists of only a `$get` property,
  3240. * which is the given service factory function.
  3241. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3242. * configure your service in a provider.
  3243. *
  3244. * @param {string} name The name of the instance.
  3245. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3246. * for `$provide.provider(name, {$get: $getFn})`.
  3247. * @returns {Object} registered provider instance
  3248. *
  3249. * @example
  3250. * Here is an example of registering a service
  3251. * ```js
  3252. * $provide.factory('ping', ['$http', function($http) {
  3253. * return function ping() {
  3254. * return $http.send('/ping');
  3255. * };
  3256. * }]);
  3257. * ```
  3258. * You would then inject and use this service like this:
  3259. * ```js
  3260. * someModule.controller('Ctrl', ['ping', function(ping) {
  3261. * ping();
  3262. * }]);
  3263. * ```
  3264. */
  3265. /**
  3266. * @ngdoc method
  3267. * @name $provide#service
  3268. * @description
  3269. *
  3270. * Register a **service constructor**, which will be invoked with `new` to create the service
  3271. * instance.
  3272. * This is short for registering a service where its provider's `$get` property is the service
  3273. * constructor function that will be used to instantiate the service instance.
  3274. *
  3275. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3276. * as a type/class.
  3277. *
  3278. * @param {string} name The name of the instance.
  3279. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3280. * @returns {Object} registered provider instance
  3281. *
  3282. * @example
  3283. * Here is an example of registering a service using
  3284. * {@link auto.$provide#service $provide.service(class)}.
  3285. * ```js
  3286. * var Ping = function($http) {
  3287. * this.$http = $http;
  3288. * };
  3289. *
  3290. * Ping.$inject = ['$http'];
  3291. *
  3292. * Ping.prototype.send = function() {
  3293. * return this.$http.get('/ping');
  3294. * };
  3295. * $provide.service('ping', Ping);
  3296. * ```
  3297. * You would then inject and use this service like this:
  3298. * ```js
  3299. * someModule.controller('Ctrl', ['ping', function(ping) {
  3300. * ping.send();
  3301. * }]);
  3302. * ```
  3303. */
  3304. /**
  3305. * @ngdoc method
  3306. * @name $provide#value
  3307. * @description
  3308. *
  3309. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3310. * number, an array, an object or a function. This is short for registering a service where its
  3311. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3312. * service**.
  3313. *
  3314. * Value services are similar to constant services, except that they cannot be injected into a
  3315. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3316. * an Angular
  3317. * {@link auto.$provide#decorator decorator}.
  3318. *
  3319. * @param {string} name The name of the instance.
  3320. * @param {*} value The value.
  3321. * @returns {Object} registered provider instance
  3322. *
  3323. * @example
  3324. * Here are some examples of creating value services.
  3325. * ```js
  3326. * $provide.value('ADMIN_USER', 'admin');
  3327. *
  3328. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3329. *
  3330. * $provide.value('halfOf', function(value) {
  3331. * return value / 2;
  3332. * });
  3333. * ```
  3334. */
  3335. /**
  3336. * @ngdoc method
  3337. * @name $provide#constant
  3338. * @description
  3339. *
  3340. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3341. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3342. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3343. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3344. *
  3345. * @param {string} name The name of the constant.
  3346. * @param {*} value The constant value.
  3347. * @returns {Object} registered instance
  3348. *
  3349. * @example
  3350. * Here a some examples of creating constants:
  3351. * ```js
  3352. * $provide.constant('SHARD_HEIGHT', 306);
  3353. *
  3354. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3355. *
  3356. * $provide.constant('double', function(value) {
  3357. * return value * 2;
  3358. * });
  3359. * ```
  3360. */
  3361. /**
  3362. * @ngdoc method
  3363. * @name $provide#decorator
  3364. * @description
  3365. *
  3366. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3367. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3368. * service. The object returned by the decorator may be the original service, or a new service
  3369. * object which replaces or wraps and delegates to the original service.
  3370. *
  3371. * @param {string} name The name of the service to decorate.
  3372. * @param {function()} decorator This function will be invoked when the service needs to be
  3373. * instantiated and should return the decorated service instance. The function is called using
  3374. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3375. * Local injection arguments:
  3376. *
  3377. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3378. * decorated or delegated to.
  3379. *
  3380. * @example
  3381. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3382. * calls to {@link ng.$log#error $log.warn()}.
  3383. * ```js
  3384. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3385. * $delegate.warn = $delegate.error;
  3386. * return $delegate;
  3387. * }]);
  3388. * ```
  3389. */
  3390. function createInjector(modulesToLoad) {
  3391. var INSTANTIATING = {},
  3392. providerSuffix = 'Provider',
  3393. path = [],
  3394. loadedModules = new HashMap([], true),
  3395. providerCache = {
  3396. $provide: {
  3397. provider: supportObject(provider),
  3398. factory: supportObject(factory),
  3399. service: supportObject(service),
  3400. value: supportObject(value),
  3401. constant: supportObject(constant),
  3402. decorator: decorator
  3403. }
  3404. },
  3405. providerInjector = (providerCache.$injector =
  3406. createInternalInjector(providerCache, function() {
  3407. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3408. })),
  3409. instanceCache = {},
  3410. instanceInjector = (instanceCache.$injector =
  3411. createInternalInjector(instanceCache, function(servicename) {
  3412. var provider = providerInjector.get(servicename + providerSuffix);
  3413. return instanceInjector.invoke(provider.$get, provider);
  3414. }));
  3415. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3416. return instanceInjector;
  3417. ////////////////////////////////////
  3418. // $provider
  3419. ////////////////////////////////////
  3420. function supportObject(delegate) {
  3421. return function(key, value) {
  3422. if (isObject(key)) {
  3423. forEach(key, reverseParams(delegate));
  3424. } else {
  3425. return delegate(key, value);
  3426. }
  3427. };
  3428. }
  3429. function provider(name, provider_) {
  3430. assertNotHasOwnProperty(name, 'service');
  3431. if (isFunction(provider_) || isArray(provider_)) {
  3432. provider_ = providerInjector.instantiate(provider_);
  3433. }
  3434. if (!provider_.$get) {
  3435. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3436. }
  3437. return providerCache[name + providerSuffix] = provider_;
  3438. }
  3439. function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
  3440. function service(name, constructor) {
  3441. return factory(name, ['$injector', function($injector) {
  3442. return $injector.instantiate(constructor);
  3443. }]);
  3444. }
  3445. function value(name, val) { return factory(name, valueFn(val)); }
  3446. function constant(name, value) {
  3447. assertNotHasOwnProperty(name, 'constant');
  3448. providerCache[name] = value;
  3449. instanceCache[name] = value;
  3450. }
  3451. function decorator(serviceName, decorFn) {
  3452. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3453. orig$get = origProvider.$get;
  3454. origProvider.$get = function() {
  3455. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3456. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3457. };
  3458. }
  3459. ////////////////////////////////////
  3460. // Module Loading
  3461. ////////////////////////////////////
  3462. function loadModules(modulesToLoad){
  3463. var runBlocks = [], moduleFn, invokeQueue, i, ii;
  3464. forEach(modulesToLoad, function(module) {
  3465. if (loadedModules.get(module)) return;
  3466. loadedModules.put(module, true);
  3467. try {
  3468. if (isString(module)) {
  3469. moduleFn = angularModule(module);
  3470. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3471. for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
  3472. var invokeArgs = invokeQueue[i],
  3473. provider = providerInjector.get(invokeArgs[0]);
  3474. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3475. }
  3476. } else if (isFunction(module)) {
  3477. runBlocks.push(providerInjector.invoke(module));
  3478. } else if (isArray(module)) {
  3479. runBlocks.push(providerInjector.invoke(module));
  3480. } else {
  3481. assertArgFn(module, 'module');
  3482. }
  3483. } catch (e) {
  3484. if (isArray(module)) {
  3485. module = module[module.length - 1];
  3486. }
  3487. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3488. // Safari & FF's stack traces don't contain error.message content
  3489. // unlike those of Chrome and IE
  3490. // So if stack doesn't contain message, we create a new string that contains both.
  3491. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3492. /* jshint -W022 */
  3493. e = e.message + '\n' + e.stack;
  3494. }
  3495. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3496. module, e.stack || e.message || e);
  3497. }
  3498. });
  3499. return runBlocks;
  3500. }
  3501. ////////////////////////////////////
  3502. // internal Injector
  3503. ////////////////////////////////////
  3504. function createInternalInjector(cache, factory) {
  3505. function getService(serviceName) {
  3506. if (cache.hasOwnProperty(serviceName)) {
  3507. if (cache[serviceName] === INSTANTIATING) {
  3508. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3509. serviceName + ' <- ' + path.join(' <- '));
  3510. }
  3511. return cache[serviceName];
  3512. } else {
  3513. try {
  3514. path.unshift(serviceName);
  3515. cache[serviceName] = INSTANTIATING;
  3516. return cache[serviceName] = factory(serviceName);
  3517. } catch (err) {
  3518. if (cache[serviceName] === INSTANTIATING) {
  3519. delete cache[serviceName];
  3520. }
  3521. throw err;
  3522. } finally {
  3523. path.shift();
  3524. }
  3525. }
  3526. }
  3527. function invoke(fn, self, locals){
  3528. var args = [],
  3529. $inject = annotate(fn),
  3530. length, i,
  3531. key;
  3532. for(i = 0, length = $inject.length; i < length; i++) {
  3533. key = $inject[i];
  3534. if (typeof key !== 'string') {
  3535. throw $injectorMinErr('itkn',
  3536. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3537. }
  3538. args.push(
  3539. locals && locals.hasOwnProperty(key)
  3540. ? locals[key]
  3541. : getService(key)
  3542. );
  3543. }
  3544. if (isArray(fn)) {
  3545. fn = fn[length];
  3546. }
  3547. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3548. // #5388
  3549. return fn.apply(self, args);
  3550. }
  3551. function instantiate(Type, locals) {
  3552. var Constructor = function() {},
  3553. instance, returnedValue;
  3554. // Check if Type is annotated and use just the given function at n-1 as parameter
  3555. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3556. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3557. instance = new Constructor();
  3558. returnedValue = invoke(Type, instance, locals);
  3559. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3560. }
  3561. return {
  3562. invoke: invoke,
  3563. instantiate: instantiate,
  3564. get: getService,
  3565. annotate: annotate,
  3566. has: function(name) {
  3567. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3568. }
  3569. };
  3570. }
  3571. }
  3572. /**
  3573. * @ngdoc service
  3574. * @name $anchorScroll
  3575. * @kind function
  3576. * @requires $window
  3577. * @requires $location
  3578. * @requires $rootScope
  3579. *
  3580. * @description
  3581. * When called, it checks current value of `$location.hash()` and scrolls to the related element,
  3582. * according to rules specified in
  3583. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3584. *
  3585. * It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
  3586. * This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
  3587. *
  3588. * @example
  3589. <example>
  3590. <file name="index.html">
  3591. <div id="scrollArea" ng-controller="ScrollCtrl">
  3592. <a ng-click="gotoBottom()">Go to bottom</a>
  3593. <a id="bottom"></a> You're at the bottom!
  3594. </div>
  3595. </file>
  3596. <file name="script.js">
  3597. function ScrollCtrl($scope, $location, $anchorScroll) {
  3598. $scope.gotoBottom = function (){
  3599. // set the location.hash to the id of
  3600. // the element you wish to scroll to.
  3601. $location.hash('bottom');
  3602. // call $anchorScroll()
  3603. $anchorScroll();
  3604. };
  3605. }
  3606. </file>
  3607. <file name="style.css">
  3608. #scrollArea {
  3609. height: 350px;
  3610. overflow: auto;
  3611. }
  3612. #bottom {
  3613. display: block;
  3614. margin-top: 2000px;
  3615. }
  3616. </file>
  3617. </example>
  3618. */
  3619. function $AnchorScrollProvider() {
  3620. var autoScrollingEnabled = true;
  3621. this.disableAutoScrolling = function() {
  3622. autoScrollingEnabled = false;
  3623. };
  3624. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3625. var document = $window.document;
  3626. // helper function to get first anchor from a NodeList
  3627. // can't use filter.filter, as it accepts only instances of Array
  3628. // and IE can't convert NodeList to an array using [].slice
  3629. // TODO(vojta): use filter if we change it to accept lists as well
  3630. function getFirstAnchor(list) {
  3631. var result = null;
  3632. forEach(list, function(element) {
  3633. if (!result && lowercase(element.nodeName) === 'a') result = element;
  3634. });
  3635. return result;
  3636. }
  3637. function scroll() {
  3638. var hash = $location.hash(), elm;
  3639. // empty hash, scroll to the top of the page
  3640. if (!hash) $window.scrollTo(0, 0);
  3641. // element with given id
  3642. else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
  3643. // first anchor with given name :-D
  3644. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
  3645. // no element and hash == 'top', scroll to the top of the page
  3646. else if (hash === 'top') $window.scrollTo(0, 0);
  3647. }
  3648. // does not scroll when user clicks on anchor link that is currently on
  3649. // (no url change, no $location.hash() change), browser native does scroll
  3650. if (autoScrollingEnabled) {
  3651. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3652. function autoScrollWatchAction() {
  3653. $rootScope.$evalAsync(scroll);
  3654. });
  3655. }
  3656. return scroll;
  3657. }];
  3658. }
  3659. var $animateMinErr = minErr('$animate');
  3660. /**
  3661. * @ngdoc provider
  3662. * @name $animateProvider
  3663. *
  3664. * @description
  3665. * Default implementation of $animate that doesn't perform any animations, instead just
  3666. * synchronously performs DOM
  3667. * updates and calls done() callbacks.
  3668. *
  3669. * In order to enable animations the ngAnimate module has to be loaded.
  3670. *
  3671. * To see the functional implementation check out src/ngAnimate/animate.js
  3672. */
  3673. var $AnimateProvider = ['$provide', function($provide) {
  3674. this.$$selectors = {};
  3675. /**
  3676. * @ngdoc method
  3677. * @name $animateProvider#register
  3678. *
  3679. * @description
  3680. * Registers a new injectable animation factory function. The factory function produces the
  3681. * animation object which contains callback functions for each event that is expected to be
  3682. * animated.
  3683. *
  3684. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  3685. * must be called once the element animation is complete. If a function is returned then the
  3686. * animation service will use this function to cancel the animation whenever a cancel event is
  3687. * triggered.
  3688. *
  3689. *
  3690. * ```js
  3691. * return {
  3692. * eventFn : function(element, done) {
  3693. * //code to run the animation
  3694. * //once complete, then run done()
  3695. * return function cancellationFunction() {
  3696. * //code to cancel the animation
  3697. * }
  3698. * }
  3699. * }
  3700. * ```
  3701. *
  3702. * @param {string} name The name of the animation.
  3703. * @param {Function} factory The factory function that will be executed to return the animation
  3704. * object.
  3705. */
  3706. this.register = function(name, factory) {
  3707. var key = name + '-animation';
  3708. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  3709. "Expecting class selector starting with '.' got '{0}'.", name);
  3710. this.$$selectors[name.substr(1)] = key;
  3711. $provide.factory(key, factory);
  3712. };
  3713. /**
  3714. * @ngdoc method
  3715. * @name $animateProvider#classNameFilter
  3716. *
  3717. * @description
  3718. * Sets and/or returns the CSS class regular expression that is checked when performing
  3719. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  3720. * therefore enable $animate to attempt to perform an animation on any element.
  3721. * When setting the classNameFilter value, animations will only be performed on elements
  3722. * that successfully match the filter expression. This in turn can boost performance
  3723. * for low-powered devices as well as applications containing a lot of structural operations.
  3724. * @param {RegExp=} expression The className expression which will be checked against all animations
  3725. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  3726. */
  3727. this.classNameFilter = function(expression) {
  3728. if(arguments.length === 1) {
  3729. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  3730. }
  3731. return this.$$classNameFilter;
  3732. };
  3733. this.$get = ['$timeout', '$$asyncCallback', function($timeout, $$asyncCallback) {
  3734. function async(fn) {
  3735. fn && $$asyncCallback(fn);
  3736. }
  3737. /**
  3738. *
  3739. * @ngdoc service
  3740. * @name $animate
  3741. * @description The $animate service provides rudimentary DOM manipulation functions to
  3742. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  3743. * This service is the core service used by the ngAnimate $animator service which provides
  3744. * high-level animation hooks for CSS and JavaScript.
  3745. *
  3746. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  3747. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  3748. * manipulation operations.
  3749. *
  3750. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  3751. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  3752. * page}.
  3753. */
  3754. return {
  3755. /**
  3756. *
  3757. * @ngdoc method
  3758. * @name $animate#enter
  3759. * @kind function
  3760. * @description Inserts the element into the DOM either after the `after` element or within
  3761. * the `parent` element. Once complete, the done() callback will be fired (if provided).
  3762. * @param {DOMElement} element the element which will be inserted into the DOM
  3763. * @param {DOMElement} parent the parent element which will append the element as
  3764. * a child (if the after element is not present)
  3765. * @param {DOMElement} after the sibling element which will append the element
  3766. * after itself
  3767. * @param {Function=} done callback function that will be called after the element has been
  3768. * inserted into the DOM
  3769. */
  3770. enter : function(element, parent, after, done) {
  3771. if (after) {
  3772. after.after(element);
  3773. } else {
  3774. if (!parent || !parent[0]) {
  3775. parent = after.parent();
  3776. }
  3777. parent.append(element);
  3778. }
  3779. async(done);
  3780. },
  3781. /**
  3782. *
  3783. * @ngdoc method
  3784. * @name $animate#leave
  3785. * @kind function
  3786. * @description Removes the element from the DOM. Once complete, the done() callback will be
  3787. * fired (if provided).
  3788. * @param {DOMElement} element the element which will be removed from the DOM
  3789. * @param {Function=} done callback function that will be called after the element has been
  3790. * removed from the DOM
  3791. */
  3792. leave : function(element, done) {
  3793. element.remove();
  3794. async(done);
  3795. },
  3796. /**
  3797. *
  3798. * @ngdoc method
  3799. * @name $animate#move
  3800. * @kind function
  3801. * @description Moves the position of the provided element within the DOM to be placed
  3802. * either after the `after` element or inside of the `parent` element. Once complete, the
  3803. * done() callback will be fired (if provided).
  3804. *
  3805. * @param {DOMElement} element the element which will be moved around within the
  3806. * DOM
  3807. * @param {DOMElement} parent the parent element where the element will be
  3808. * inserted into (if the after element is not present)
  3809. * @param {DOMElement} after the sibling element where the element will be
  3810. * positioned next to
  3811. * @param {Function=} done the callback function (if provided) that will be fired after the
  3812. * element has been moved to its new position
  3813. */
  3814. move : function(element, parent, after, done) {
  3815. // Do not remove element before insert. Removing will cause data associated with the
  3816. // element to be dropped. Insert will implicitly do the remove.
  3817. this.enter(element, parent, after, done);
  3818. },
  3819. /**
  3820. *
  3821. * @ngdoc method
  3822. * @name $animate#addClass
  3823. * @kind function
  3824. * @description Adds the provided className CSS class value to the provided element. Once
  3825. * complete, the done() callback will be fired (if provided).
  3826. * @param {DOMElement} element the element which will have the className value
  3827. * added to it
  3828. * @param {string} className the CSS class which will be added to the element
  3829. * @param {Function=} done the callback function (if provided) that will be fired after the
  3830. * className value has been added to the element
  3831. */
  3832. addClass : function(element, className, done) {
  3833. className = isString(className) ?
  3834. className :
  3835. isArray(className) ? className.join(' ') : '';
  3836. forEach(element, function (element) {
  3837. jqLiteAddClass(element, className);
  3838. });
  3839. async(done);
  3840. },
  3841. /**
  3842. *
  3843. * @ngdoc method
  3844. * @name $animate#removeClass
  3845. * @kind function
  3846. * @description Removes the provided className CSS class value from the provided element.
  3847. * Once complete, the done() callback will be fired (if provided).
  3848. * @param {DOMElement} element the element which will have the className value
  3849. * removed from it
  3850. * @param {string} className the CSS class which will be removed from the element
  3851. * @param {Function=} done the callback function (if provided) that will be fired after the
  3852. * className value has been removed from the element
  3853. */
  3854. removeClass : function(element, className, done) {
  3855. className = isString(className) ?
  3856. className :
  3857. isArray(className) ? className.join(' ') : '';
  3858. forEach(element, function (element) {
  3859. jqLiteRemoveClass(element, className);
  3860. });
  3861. async(done);
  3862. },
  3863. /**
  3864. *
  3865. * @ngdoc method
  3866. * @name $animate#setClass
  3867. * @kind function
  3868. * @description Adds and/or removes the given CSS classes to and from the element.
  3869. * Once complete, the done() callback will be fired (if provided).
  3870. * @param {DOMElement} element the element which will have its CSS classes changed
  3871. * removed from it
  3872. * @param {string} add the CSS classes which will be added to the element
  3873. * @param {string} remove the CSS class which will be removed from the element
  3874. * @param {Function=} done the callback function (if provided) that will be fired after the
  3875. * CSS classes have been set on the element
  3876. */
  3877. setClass : function(element, add, remove, done) {
  3878. forEach(element, function (element) {
  3879. jqLiteAddClass(element, add);
  3880. jqLiteRemoveClass(element, remove);
  3881. });
  3882. async(done);
  3883. },
  3884. enabled : noop
  3885. };
  3886. }];
  3887. }];
  3888. function $$AsyncCallbackProvider(){
  3889. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  3890. return $$rAF.supported
  3891. ? function(fn) { return $$rAF(fn); }
  3892. : function(fn) {
  3893. return $timeout(fn, 0, false);
  3894. };
  3895. }];
  3896. }
  3897. /**
  3898. * ! This is a private undocumented service !
  3899. *
  3900. * @name $browser
  3901. * @requires $log
  3902. * @description
  3903. * This object has two goals:
  3904. *
  3905. * - hide all the global state in the browser caused by the window object
  3906. * - abstract away all the browser specific features and inconsistencies
  3907. *
  3908. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  3909. * service, which can be used for convenient testing of the application without the interaction with
  3910. * the real browser apis.
  3911. */
  3912. /**
  3913. * @param {object} window The global window object.
  3914. * @param {object} document jQuery wrapped document.
  3915. * @param {function()} XHR XMLHttpRequest constructor.
  3916. * @param {object} $log console.log or an object with the same interface.
  3917. * @param {object} $sniffer $sniffer service
  3918. */
  3919. function Browser(window, document, $log, $sniffer) {
  3920. var self = this,
  3921. rawDocument = document[0],
  3922. location = window.location,
  3923. history = window.history,
  3924. setTimeout = window.setTimeout,
  3925. clearTimeout = window.clearTimeout,
  3926. pendingDeferIds = {};
  3927. self.isMock = false;
  3928. var outstandingRequestCount = 0;
  3929. var outstandingRequestCallbacks = [];
  3930. // TODO(vojta): remove this temporary api
  3931. self.$$completeOutstandingRequest = completeOutstandingRequest;
  3932. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  3933. /**
  3934. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  3935. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  3936. */
  3937. function completeOutstandingRequest(fn) {
  3938. try {
  3939. fn.apply(null, sliceArgs(arguments, 1));
  3940. } finally {
  3941. outstandingRequestCount--;
  3942. if (outstandingRequestCount === 0) {
  3943. while(outstandingRequestCallbacks.length) {
  3944. try {
  3945. outstandingRequestCallbacks.pop()();
  3946. } catch (e) {
  3947. $log.error(e);
  3948. }
  3949. }
  3950. }
  3951. }
  3952. }
  3953. /**
  3954. * @private
  3955. * Note: this method is used only by scenario runner
  3956. * TODO(vojta): prefix this method with $$ ?
  3957. * @param {function()} callback Function that will be called when no outstanding request
  3958. */
  3959. self.notifyWhenNoOutstandingRequests = function(callback) {
  3960. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  3961. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  3962. // regular poller would result in flaky tests.
  3963. forEach(pollFns, function(pollFn){ pollFn(); });
  3964. if (outstandingRequestCount === 0) {
  3965. callback();
  3966. } else {
  3967. outstandingRequestCallbacks.push(callback);
  3968. }
  3969. };
  3970. //////////////////////////////////////////////////////////////
  3971. // Poll Watcher API
  3972. //////////////////////////////////////////////////////////////
  3973. var pollFns = [],
  3974. pollTimeout;
  3975. /**
  3976. * @name $browser#addPollFn
  3977. *
  3978. * @param {function()} fn Poll function to add
  3979. *
  3980. * @description
  3981. * Adds a function to the list of functions that poller periodically executes,
  3982. * and starts polling if not started yet.
  3983. *
  3984. * @returns {function()} the added function
  3985. */
  3986. self.addPollFn = function(fn) {
  3987. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  3988. pollFns.push(fn);
  3989. return fn;
  3990. };
  3991. /**
  3992. * @param {number} interval How often should browser call poll functions (ms)
  3993. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  3994. *
  3995. * @description
  3996. * Configures the poller to run in the specified intervals, using the specified
  3997. * setTimeout fn and kicks it off.
  3998. */
  3999. function startPoller(interval, setTimeout) {
  4000. (function check() {
  4001. forEach(pollFns, function(pollFn){ pollFn(); });
  4002. pollTimeout = setTimeout(check, interval);
  4003. })();
  4004. }
  4005. //////////////////////////////////////////////////////////////
  4006. // URL API
  4007. //////////////////////////////////////////////////////////////
  4008. var lastBrowserUrl = location.href,
  4009. baseElement = document.find('base'),
  4010. newLocation = null;
  4011. /**
  4012. * @name $browser#url
  4013. *
  4014. * @description
  4015. * GETTER:
  4016. * Without any argument, this method just returns current value of location.href.
  4017. *
  4018. * SETTER:
  4019. * With at least one argument, this method sets url to new value.
  4020. * If html5 history api supported, pushState/replaceState is used, otherwise
  4021. * location.href/location.replace is used.
  4022. * Returns its own instance to allow chaining
  4023. *
  4024. * NOTE: this api is intended for use only by the $location service. Please use the
  4025. * {@link ng.$location $location service} to change url.
  4026. *
  4027. * @param {string} url New url (when used as setter)
  4028. * @param {boolean=} replace Should new url replace current history record ?
  4029. */
  4030. self.url = function(url, replace) {
  4031. // Android Browser BFCache causes location, history reference to become stale.
  4032. if (location !== window.location) location = window.location;
  4033. if (history !== window.history) history = window.history;
  4034. // setter
  4035. if (url) {
  4036. if (lastBrowserUrl == url) return;
  4037. lastBrowserUrl = url;
  4038. if ($sniffer.history) {
  4039. if (replace) history.replaceState(null, '', url);
  4040. else {
  4041. history.pushState(null, '', url);
  4042. // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
  4043. baseElement.attr('href', baseElement.attr('href'));
  4044. }
  4045. } else {
  4046. newLocation = url;
  4047. if (replace) {
  4048. location.replace(url);
  4049. } else {
  4050. location.href = url;
  4051. }
  4052. }
  4053. return self;
  4054. // getter
  4055. } else {
  4056. // - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
  4057. // methods not updating location.href synchronously.
  4058. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4059. return newLocation || location.href.replace(/%27/g,"'");
  4060. }
  4061. };
  4062. var urlChangeListeners = [],
  4063. urlChangeInit = false;
  4064. function fireUrlChange() {
  4065. newLocation = null;
  4066. if (lastBrowserUrl == self.url()) return;
  4067. lastBrowserUrl = self.url();
  4068. forEach(urlChangeListeners, function(listener) {
  4069. listener(self.url());
  4070. });
  4071. }
  4072. /**
  4073. * @name $browser#onUrlChange
  4074. *
  4075. * @description
  4076. * Register callback function that will be called, when url changes.
  4077. *
  4078. * It's only called when the url is changed from outside of angular:
  4079. * - user types different url into address bar
  4080. * - user clicks on history (forward/back) button
  4081. * - user clicks on a link
  4082. *
  4083. * It's not called when url is changed by $browser.url() method
  4084. *
  4085. * The listener gets called with new url as parameter.
  4086. *
  4087. * NOTE: this api is intended for use only by the $location service. Please use the
  4088. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4089. *
  4090. * @param {function(string)} listener Listener function to be called when url changes.
  4091. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4092. */
  4093. self.onUrlChange = function(callback) {
  4094. // TODO(vojta): refactor to use node's syntax for events
  4095. if (!urlChangeInit) {
  4096. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4097. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4098. // changed by push/replaceState
  4099. // html5 history api - popstate event
  4100. if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
  4101. // hashchange event
  4102. if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
  4103. // polling
  4104. else self.addPollFn(fireUrlChange);
  4105. urlChangeInit = true;
  4106. }
  4107. urlChangeListeners.push(callback);
  4108. return callback;
  4109. };
  4110. //////////////////////////////////////////////////////////////
  4111. // Misc API
  4112. //////////////////////////////////////////////////////////////
  4113. /**
  4114. * @name $browser#baseHref
  4115. *
  4116. * @description
  4117. * Returns current <base href>
  4118. * (always relative - without domain)
  4119. *
  4120. * @returns {string} The current base href
  4121. */
  4122. self.baseHref = function() {
  4123. var href = baseElement.attr('href');
  4124. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4125. };
  4126. //////////////////////////////////////////////////////////////
  4127. // Cookies API
  4128. //////////////////////////////////////////////////////////////
  4129. var lastCookies = {};
  4130. var lastCookieString = '';
  4131. var cookiePath = self.baseHref();
  4132. /**
  4133. * @name $browser#cookies
  4134. *
  4135. * @param {string=} name Cookie name
  4136. * @param {string=} value Cookie value
  4137. *
  4138. * @description
  4139. * The cookies method provides a 'private' low level access to browser cookies.
  4140. * It is not meant to be used directly, use the $cookie service instead.
  4141. *
  4142. * The return values vary depending on the arguments that the method was called with as follows:
  4143. *
  4144. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4145. * it
  4146. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4147. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4148. * way)
  4149. *
  4150. * @returns {Object} Hash of all cookies (if called without any parameter)
  4151. */
  4152. self.cookies = function(name, value) {
  4153. /* global escape: false, unescape: false */
  4154. var cookieLength, cookieArray, cookie, i, index;
  4155. if (name) {
  4156. if (value === undefined) {
  4157. rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
  4158. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4159. } else {
  4160. if (isString(value)) {
  4161. cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
  4162. ';path=' + cookiePath).length + 1;
  4163. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4164. // - 300 cookies
  4165. // - 20 cookies per unique domain
  4166. // - 4096 bytes per cookie
  4167. if (cookieLength > 4096) {
  4168. $log.warn("Cookie '"+ name +
  4169. "' possibly not set or overflowed because it was too large ("+
  4170. cookieLength + " > 4096 bytes)!");
  4171. }
  4172. }
  4173. }
  4174. } else {
  4175. if (rawDocument.cookie !== lastCookieString) {
  4176. lastCookieString = rawDocument.cookie;
  4177. cookieArray = lastCookieString.split("; ");
  4178. lastCookies = {};
  4179. for (i = 0; i < cookieArray.length; i++) {
  4180. cookie = cookieArray[i];
  4181. index = cookie.indexOf('=');
  4182. if (index > 0) { //ignore nameless cookies
  4183. name = unescape(cookie.substring(0, index));
  4184. // the first value that is seen for a cookie is the most
  4185. // specific one. values for the same cookie name that
  4186. // follow are for less specific paths.
  4187. if (lastCookies[name] === undefined) {
  4188. lastCookies[name] = unescape(cookie.substring(index + 1));
  4189. }
  4190. }
  4191. }
  4192. }
  4193. return lastCookies;
  4194. }
  4195. };
  4196. /**
  4197. * @name $browser#defer
  4198. * @param {function()} fn A function, who's execution should be deferred.
  4199. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4200. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4201. *
  4202. * @description
  4203. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4204. *
  4205. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4206. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4207. * via `$browser.defer.flush()`.
  4208. *
  4209. */
  4210. self.defer = function(fn, delay) {
  4211. var timeoutId;
  4212. outstandingRequestCount++;
  4213. timeoutId = setTimeout(function() {
  4214. delete pendingDeferIds[timeoutId];
  4215. completeOutstandingRequest(fn);
  4216. }, delay || 0);
  4217. pendingDeferIds[timeoutId] = true;
  4218. return timeoutId;
  4219. };
  4220. /**
  4221. * @name $browser#defer.cancel
  4222. *
  4223. * @description
  4224. * Cancels a deferred task identified with `deferId`.
  4225. *
  4226. * @param {*} deferId Token returned by the `$browser.defer` function.
  4227. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4228. * canceled.
  4229. */
  4230. self.defer.cancel = function(deferId) {
  4231. if (pendingDeferIds[deferId]) {
  4232. delete pendingDeferIds[deferId];
  4233. clearTimeout(deferId);
  4234. completeOutstandingRequest(noop);
  4235. return true;
  4236. }
  4237. return false;
  4238. };
  4239. }
  4240. function $BrowserProvider(){
  4241. this.$get = ['$window', '$log', '$sniffer', '$document',
  4242. function( $window, $log, $sniffer, $document){
  4243. return new Browser($window, $document, $log, $sniffer);
  4244. }];
  4245. }
  4246. /**
  4247. * @ngdoc service
  4248. * @name $cacheFactory
  4249. *
  4250. * @description
  4251. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4252. * them.
  4253. *
  4254. * ```js
  4255. *
  4256. * var cache = $cacheFactory('cacheId');
  4257. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4258. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4259. *
  4260. * cache.put("key", "value");
  4261. * cache.put("another key", "another value");
  4262. *
  4263. * // We've specified no options on creation
  4264. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4265. *
  4266. * ```
  4267. *
  4268. *
  4269. * @param {string} cacheId Name or id of the newly created cache.
  4270. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4271. *
  4272. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4273. *
  4274. * @returns {object} Newly created cache object with the following set of methods:
  4275. *
  4276. * - `{object}` `info()` — Returns id, size, and options of cache.
  4277. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4278. * it.
  4279. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4280. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4281. * - `{void}` `removeAll()` — Removes all cached values.
  4282. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4283. *
  4284. * @example
  4285. <example module="cacheExampleApp">
  4286. <file name="index.html">
  4287. <div ng-controller="CacheController">
  4288. <input ng-model="newCacheKey" placeholder="Key">
  4289. <input ng-model="newCacheValue" placeholder="Value">
  4290. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4291. <p ng-if="keys.length">Cached Values</p>
  4292. <div ng-repeat="key in keys">
  4293. <span ng-bind="key"></span>
  4294. <span>: </span>
  4295. <b ng-bind="cache.get(key)"></b>
  4296. </div>
  4297. <p>Cache Info</p>
  4298. <div ng-repeat="(key, value) in cache.info()">
  4299. <span ng-bind="key"></span>
  4300. <span>: </span>
  4301. <b ng-bind="value"></b>
  4302. </div>
  4303. </div>
  4304. </file>
  4305. <file name="script.js">
  4306. angular.module('cacheExampleApp', []).
  4307. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4308. $scope.keys = [];
  4309. $scope.cache = $cacheFactory('cacheId');
  4310. $scope.put = function(key, value) {
  4311. $scope.cache.put(key, value);
  4312. $scope.keys.push(key);
  4313. };
  4314. }]);
  4315. </file>
  4316. <file name="style.css">
  4317. p {
  4318. margin: 10px 0 3px;
  4319. }
  4320. </file>
  4321. </example>
  4322. */
  4323. function $CacheFactoryProvider() {
  4324. this.$get = function() {
  4325. var caches = {};
  4326. function cacheFactory(cacheId, options) {
  4327. if (cacheId in caches) {
  4328. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4329. }
  4330. var size = 0,
  4331. stats = extend({}, options, {id: cacheId}),
  4332. data = {},
  4333. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4334. lruHash = {},
  4335. freshEnd = null,
  4336. staleEnd = null;
  4337. /**
  4338. * @ngdoc type
  4339. * @name $cacheFactory.Cache
  4340. *
  4341. * @description
  4342. * A cache object used to store and retrieve data, primarily used by
  4343. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4344. * templates and other data.
  4345. *
  4346. * ```js
  4347. * angular.module('superCache')
  4348. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4349. * return $cacheFactory('super-cache');
  4350. * }]);
  4351. * ```
  4352. *
  4353. * Example test:
  4354. *
  4355. * ```js
  4356. * it('should behave like a cache', inject(function(superCache) {
  4357. * superCache.put('key', 'value');
  4358. * superCache.put('another key', 'another value');
  4359. *
  4360. * expect(superCache.info()).toEqual({
  4361. * id: 'super-cache',
  4362. * size: 2
  4363. * });
  4364. *
  4365. * superCache.remove('another key');
  4366. * expect(superCache.get('another key')).toBeUndefined();
  4367. *
  4368. * superCache.removeAll();
  4369. * expect(superCache.info()).toEqual({
  4370. * id: 'super-cache',
  4371. * size: 0
  4372. * });
  4373. * }));
  4374. * ```
  4375. */
  4376. return caches[cacheId] = {
  4377. /**
  4378. * @ngdoc method
  4379. * @name $cacheFactory.Cache#put
  4380. * @kind function
  4381. *
  4382. * @description
  4383. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4384. * retrieved later, and incrementing the size of the cache if the key was not already
  4385. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4386. * entries from the set.
  4387. *
  4388. * It will not insert undefined values into the cache.
  4389. *
  4390. * @param {string} key the key under which the cached data is stored.
  4391. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4392. * will not be stored.
  4393. * @returns {*} the value stored.
  4394. */
  4395. put: function(key, value) {
  4396. if (capacity < Number.MAX_VALUE) {
  4397. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4398. refresh(lruEntry);
  4399. }
  4400. if (isUndefined(value)) return;
  4401. if (!(key in data)) size++;
  4402. data[key] = value;
  4403. if (size > capacity) {
  4404. this.remove(staleEnd.key);
  4405. }
  4406. return value;
  4407. },
  4408. /**
  4409. * @ngdoc method
  4410. * @name $cacheFactory.Cache#get
  4411. * @kind function
  4412. *
  4413. * @description
  4414. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4415. *
  4416. * @param {string} key the key of the data to be retrieved
  4417. * @returns {*} the value stored.
  4418. */
  4419. get: function(key) {
  4420. if (capacity < Number.MAX_VALUE) {
  4421. var lruEntry = lruHash[key];
  4422. if (!lruEntry) return;
  4423. refresh(lruEntry);
  4424. }
  4425. return data[key];
  4426. },
  4427. /**
  4428. * @ngdoc method
  4429. * @name $cacheFactory.Cache#remove
  4430. * @kind function
  4431. *
  4432. * @description
  4433. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4434. *
  4435. * @param {string} key the key of the entry to be removed
  4436. */
  4437. remove: function(key) {
  4438. if (capacity < Number.MAX_VALUE) {
  4439. var lruEntry = lruHash[key];
  4440. if (!lruEntry) return;
  4441. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4442. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4443. link(lruEntry.n,lruEntry.p);
  4444. delete lruHash[key];
  4445. }
  4446. delete data[key];
  4447. size--;
  4448. },
  4449. /**
  4450. * @ngdoc method
  4451. * @name $cacheFactory.Cache#removeAll
  4452. * @kind function
  4453. *
  4454. * @description
  4455. * Clears the cache object of any entries.
  4456. */
  4457. removeAll: function() {
  4458. data = {};
  4459. size = 0;
  4460. lruHash = {};
  4461. freshEnd = staleEnd = null;
  4462. },
  4463. /**
  4464. * @ngdoc method
  4465. * @name $cacheFactory.Cache#destroy
  4466. * @kind function
  4467. *
  4468. * @description
  4469. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4470. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4471. */
  4472. destroy: function() {
  4473. data = null;
  4474. stats = null;
  4475. lruHash = null;
  4476. delete caches[cacheId];
  4477. },
  4478. /**
  4479. * @ngdoc method
  4480. * @name $cacheFactory.Cache#info
  4481. * @kind function
  4482. *
  4483. * @description
  4484. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  4485. *
  4486. * @returns {object} an object with the following properties:
  4487. * <ul>
  4488. * <li>**id**: the id of the cache instance</li>
  4489. * <li>**size**: the number of entries kept in the cache instance</li>
  4490. * <li>**...**: any additional properties from the options object when creating the
  4491. * cache.</li>
  4492. * </ul>
  4493. */
  4494. info: function() {
  4495. return extend({}, stats, {size: size});
  4496. }
  4497. };
  4498. /**
  4499. * makes the `entry` the freshEnd of the LRU linked list
  4500. */
  4501. function refresh(entry) {
  4502. if (entry != freshEnd) {
  4503. if (!staleEnd) {
  4504. staleEnd = entry;
  4505. } else if (staleEnd == entry) {
  4506. staleEnd = entry.n;
  4507. }
  4508. link(entry.n, entry.p);
  4509. link(entry, freshEnd);
  4510. freshEnd = entry;
  4511. freshEnd.n = null;
  4512. }
  4513. }
  4514. /**
  4515. * bidirectionally links two entries of the LRU linked list
  4516. */
  4517. function link(nextEntry, prevEntry) {
  4518. if (nextEntry != prevEntry) {
  4519. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  4520. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  4521. }
  4522. }
  4523. }
  4524. /**
  4525. * @ngdoc method
  4526. * @name $cacheFactory#info
  4527. *
  4528. * @description
  4529. * Get information about all the caches that have been created
  4530. *
  4531. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  4532. */
  4533. cacheFactory.info = function() {
  4534. var info = {};
  4535. forEach(caches, function(cache, cacheId) {
  4536. info[cacheId] = cache.info();
  4537. });
  4538. return info;
  4539. };
  4540. /**
  4541. * @ngdoc method
  4542. * @name $cacheFactory#get
  4543. *
  4544. * @description
  4545. * Get access to a cache object by the `cacheId` used when it was created.
  4546. *
  4547. * @param {string} cacheId Name or id of a cache to access.
  4548. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  4549. */
  4550. cacheFactory.get = function(cacheId) {
  4551. return caches[cacheId];
  4552. };
  4553. return cacheFactory;
  4554. };
  4555. }
  4556. /**
  4557. * @ngdoc service
  4558. * @name $templateCache
  4559. *
  4560. * @description
  4561. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  4562. * can load templates directly into the cache in a `script` tag, or by consuming the
  4563. * `$templateCache` service directly.
  4564. *
  4565. * Adding via the `script` tag:
  4566. *
  4567. * ```html
  4568. * <script type="text/ng-template" id="templateId.html">
  4569. * <p>This is the content of the template</p>
  4570. * </script>
  4571. * ```
  4572. *
  4573. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  4574. * the document, but it must be below the `ng-app` definition.
  4575. *
  4576. * Adding via the $templateCache service:
  4577. *
  4578. * ```js
  4579. * var myApp = angular.module('myApp', []);
  4580. * myApp.run(function($templateCache) {
  4581. * $templateCache.put('templateId.html', 'This is the content of the template');
  4582. * });
  4583. * ```
  4584. *
  4585. * To retrieve the template later, simply use it in your HTML:
  4586. * ```html
  4587. * <div ng-include=" 'templateId.html' "></div>
  4588. * ```
  4589. *
  4590. * or get it via Javascript:
  4591. * ```js
  4592. * $templateCache.get('templateId.html')
  4593. * ```
  4594. *
  4595. * See {@link ng.$cacheFactory $cacheFactory}.
  4596. *
  4597. */
  4598. function $TemplateCacheProvider() {
  4599. this.$get = ['$cacheFactory', function($cacheFactory) {
  4600. return $cacheFactory('templates');
  4601. }];
  4602. }
  4603. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  4604. *
  4605. * DOM-related variables:
  4606. *
  4607. * - "node" - DOM Node
  4608. * - "element" - DOM Element or Node
  4609. * - "$node" or "$element" - jqLite-wrapped node or element
  4610. *
  4611. *
  4612. * Compiler related stuff:
  4613. *
  4614. * - "linkFn" - linking fn of a single directive
  4615. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  4616. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  4617. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  4618. */
  4619. /**
  4620. * @ngdoc service
  4621. * @name $compile
  4622. * @kind function
  4623. *
  4624. * @description
  4625. * Compiles an HTML string or DOM into a template and produces a template function, which
  4626. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  4627. *
  4628. * The compilation is a process of walking the DOM tree and matching DOM elements to
  4629. * {@link ng.$compileProvider#directive directives}.
  4630. *
  4631. * <div class="alert alert-warning">
  4632. * **Note:** This document is an in-depth reference of all directive options.
  4633. * For a gentle introduction to directives with examples of common use cases,
  4634. * see the {@link guide/directive directive guide}.
  4635. * </div>
  4636. *
  4637. * ## Comprehensive Directive API
  4638. *
  4639. * There are many different options for a directive.
  4640. *
  4641. * The difference resides in the return value of the factory function.
  4642. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  4643. * or just the `postLink` function (all other properties will have the default values).
  4644. *
  4645. * <div class="alert alert-success">
  4646. * **Best Practice:** It's recommended to use the "directive definition object" form.
  4647. * </div>
  4648. *
  4649. * Here's an example directive declared with a Directive Definition Object:
  4650. *
  4651. * ```js
  4652. * var myModule = angular.module(...);
  4653. *
  4654. * myModule.directive('directiveName', function factory(injectables) {
  4655. * var directiveDefinitionObject = {
  4656. * priority: 0,
  4657. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  4658. * // or
  4659. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  4660. * transclude: false,
  4661. * restrict: 'A',
  4662. * scope: false,
  4663. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  4664. * controllerAs: 'stringAlias',
  4665. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  4666. * compile: function compile(tElement, tAttrs, transclude) {
  4667. * return {
  4668. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4669. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4670. * }
  4671. * // or
  4672. * // return function postLink( ... ) { ... }
  4673. * },
  4674. * // or
  4675. * // link: {
  4676. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  4677. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  4678. * // }
  4679. * // or
  4680. * // link: function postLink( ... ) { ... }
  4681. * };
  4682. * return directiveDefinitionObject;
  4683. * });
  4684. * ```
  4685. *
  4686. * <div class="alert alert-warning">
  4687. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  4688. * </div>
  4689. *
  4690. * Therefore the above can be simplified as:
  4691. *
  4692. * ```js
  4693. * var myModule = angular.module(...);
  4694. *
  4695. * myModule.directive('directiveName', function factory(injectables) {
  4696. * var directiveDefinitionObject = {
  4697. * link: function postLink(scope, iElement, iAttrs) { ... }
  4698. * };
  4699. * return directiveDefinitionObject;
  4700. * // or
  4701. * // return function postLink(scope, iElement, iAttrs) { ... }
  4702. * });
  4703. * ```
  4704. *
  4705. *
  4706. *
  4707. * ### Directive Definition Object
  4708. *
  4709. * The directive definition object provides instructions to the {@link ng.$compile
  4710. * compiler}. The attributes are:
  4711. *
  4712. * #### `priority`
  4713. * When there are multiple directives defined on a single DOM element, sometimes it
  4714. * is necessary to specify the order in which the directives are applied. The `priority` is used
  4715. * to sort the directives before their `compile` functions get called. Priority is defined as a
  4716. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  4717. * are also run in priority order, but post-link functions are run in reverse order. The order
  4718. * of directives with the same priority is undefined. The default priority is `0`.
  4719. *
  4720. * #### `terminal`
  4721. * If set to true then the current `priority` will be the last set of directives
  4722. * which will execute (any directives at the current priority will still execute
  4723. * as the order of execution on same `priority` is undefined).
  4724. *
  4725. * #### `scope`
  4726. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  4727. * same element request a new scope, only one new scope is created. The new scope rule does not
  4728. * apply for the root of the template since the root of the template always gets a new scope.
  4729. *
  4730. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  4731. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  4732. * when creating reusable components, which should not accidentally read or modify data in the
  4733. * parent scope.
  4734. *
  4735. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  4736. * derived from the parent scope. These local properties are useful for aliasing values for
  4737. * templates. Locals definition is a hash of local scope property to its source:
  4738. *
  4739. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  4740. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  4741. * attribute name is assumed to be the same as the local name.
  4742. * Given `<widget my-attr="hello {{name}}">` and widget definition
  4743. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  4744. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  4745. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  4746. * component scope).
  4747. *
  4748. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  4749. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  4750. * name is specified then the attribute name is assumed to be the same as the local name.
  4751. * Given `<widget my-attr="parentModel">` and widget definition of
  4752. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  4753. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  4754. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  4755. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  4756. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  4757. *
  4758. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  4759. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  4760. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  4761. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  4762. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  4763. * pass data from the isolated scope via an expression to the parent scope, this can be
  4764. * done by passing a map of local variable names and values into the expression wrapper fn.
  4765. * For example, if the expression is `increment(amount)` then we can specify the amount value
  4766. * by calling the `localFn` as `localFn({amount: 22})`.
  4767. *
  4768. *
  4769. *
  4770. * #### `controller`
  4771. * Controller constructor function. The controller is instantiated before the
  4772. * pre-linking phase and it is shared with other directives (see
  4773. * `require` attribute). This allows the directives to communicate with each other and augment
  4774. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  4775. *
  4776. * * `$scope` - Current scope associated with the element
  4777. * * `$element` - Current element
  4778. * * `$attrs` - Current attributes object for the element
  4779. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope.
  4780. * The scope can be overridden by an optional first argument.
  4781. * `function([scope], cloneLinkingFn)`.
  4782. *
  4783. *
  4784. * #### `require`
  4785. * Require another directive and inject its controller as the fourth argument to the linking function. The
  4786. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  4787. * injected argument will be an array in corresponding order. If no such directive can be
  4788. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  4789. *
  4790. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  4791. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  4792. * * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  4793. * * `?^` - Attempt to locate the required controller by searching the element's parents or pass `null` to the
  4794. * `link` fn if not found.
  4795. *
  4796. *
  4797. * #### `controllerAs`
  4798. * Controller alias at the directive scope. An alias for the controller so it
  4799. * can be referenced at the directive template. The directive needs to define a scope for this
  4800. * configuration to be used. Useful in the case when directive is used as component.
  4801. *
  4802. *
  4803. * #### `restrict`
  4804. * String of subset of `EACM` which restricts the directive to a specific directive
  4805. * declaration style. If omitted, the default (attributes only) is used.
  4806. *
  4807. * * `E` - Element name: `<my-directive></my-directive>`
  4808. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  4809. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  4810. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  4811. *
  4812. *
  4813. * #### `template`
  4814. * HTML markup that may:
  4815. * * Replace the contents of the directive's element (defualt).
  4816. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  4817. * * Wrap the contents of the directive's element (if `transclude` is true).
  4818. *
  4819. * Value may be:
  4820. *
  4821. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  4822. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  4823. * function api below) and returns a string value.
  4824. *
  4825. *
  4826. * #### `templateUrl`
  4827. * Same as `template` but the template is loaded from the specified URL. Because
  4828. * the template loading is asynchronous the compilation/linking is suspended until the template
  4829. * is loaded.
  4830. *
  4831. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  4832. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  4833. * a string value representing the url. In either case, the template URL is passed through {@link
  4834. * api/ng.$sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  4835. *
  4836. *
  4837. * #### `replace` ([*DEPRECATED*!], will be removed in next major release)
  4838. * specify what the template should replace. Defaults to `false`.
  4839. *
  4840. * * `true` - the template will replace the directive's element.
  4841. * * `false` - the template will replace the contents of the directive's element.
  4842. *
  4843. * The replacement process migrates all of the attributes / classes from the old element to the new
  4844. * one. See the {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
  4845. * Directives Guide} for an example.
  4846. *
  4847. * #### `transclude`
  4848. * compile the content of the element and make it available to the directive.
  4849. * Typically used with {@link ng.directive:ngTransclude
  4850. * ngTransclude}. The advantage of transclusion is that the linking function receives a
  4851. * transclusion function which is pre-bound to the correct scope. In a typical setup the widget
  4852. * creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
  4853. * scope. This makes it possible for the widget to have private state, and the transclusion to
  4854. * be bound to the parent (pre-`isolate`) scope.
  4855. *
  4856. * * `true` - transclude the content of the directive.
  4857. * * `'element'` - transclude the whole element including any directives defined at lower priority.
  4858. *
  4859. * <div class="alert alert-warning">
  4860. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  4861. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  4862. * Testing Transclusion Directives}.
  4863. * </div>
  4864. *
  4865. * #### `compile`
  4866. *
  4867. * ```js
  4868. * function compile(tElement, tAttrs, transclude) { ... }
  4869. * ```
  4870. *
  4871. * The compile function deals with transforming the template DOM. Since most directives do not do
  4872. * template transformation, it is not used often. The compile function takes the following arguments:
  4873. *
  4874. * * `tElement` - template element - The element where the directive has been declared. It is
  4875. * safe to do template transformation on the element and child elements only.
  4876. *
  4877. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  4878. * between all directive compile functions.
  4879. *
  4880. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  4881. *
  4882. * <div class="alert alert-warning">
  4883. * **Note:** The template instance and the link instance may be different objects if the template has
  4884. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  4885. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  4886. * should be done in a linking function rather than in a compile function.
  4887. * </div>
  4888. * <div class="alert alert-warning">
  4889. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  4890. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  4891. * stack overflow errors.
  4892. *
  4893. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  4894. * a directive's template instead of relying on automatic template compilation via `template` or
  4895. * `templateUrl` declaration or manual compilation inside the compile function.
  4896. * </div>
  4897. *
  4898. * <div class="alert alert-error">
  4899. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  4900. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  4901. * to the link function instead.
  4902. * </div>
  4903. * A compile function can have a return value which can be either a function or an object.
  4904. *
  4905. * * returning a (post-link) function - is equivalent to registering the linking function via the
  4906. * `link` property of the config object when the compile function is empty.
  4907. *
  4908. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  4909. * control when a linking function should be called during the linking phase. See info about
  4910. * pre-linking and post-linking functions below.
  4911. *
  4912. *
  4913. * #### `link`
  4914. * This property is used only if the `compile` property is not defined.
  4915. *
  4916. * ```js
  4917. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  4918. * ```
  4919. *
  4920. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  4921. * executed after the template has been cloned. This is where most of the directive logic will be
  4922. * put.
  4923. *
  4924. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  4925. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  4926. *
  4927. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  4928. * manipulate the children of the element only in `postLink` function since the children have
  4929. * already been linked.
  4930. *
  4931. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  4932. * between all directive linking functions.
  4933. *
  4934. * * `controller` - a controller instance - A controller instance if at least one directive on the
  4935. * element defines a controller. The controller is shared among all the directives, which allows
  4936. * the directives to use the controllers as a communication channel.
  4937. *
  4938. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  4939. * The scope can be overridden by an optional first argument. This is the same as the `$transclude`
  4940. * parameter of directive controllers.
  4941. * `function([scope], cloneLinkingFn)`.
  4942. *
  4943. *
  4944. * #### Pre-linking function
  4945. *
  4946. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  4947. * compiler linking function will fail to locate the correct elements for linking.
  4948. *
  4949. * #### Post-linking function
  4950. *
  4951. * Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
  4952. *
  4953. * <a name="Attributes"></a>
  4954. * ### Attributes
  4955. *
  4956. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  4957. * `link()` or `compile()` functions. It has a variety of uses.
  4958. *
  4959. * accessing *Normalized attribute names:*
  4960. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  4961. * the attributes object allows for normalized access to
  4962. * the attributes.
  4963. *
  4964. * * *Directive inter-communication:* All directives share the same instance of the attributes
  4965. * object which allows the directives to use the attributes object as inter directive
  4966. * communication.
  4967. *
  4968. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  4969. * allowing other directives to read the interpolated value.
  4970. *
  4971. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  4972. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  4973. * the only way to easily get the actual value because during the linking phase the interpolation
  4974. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  4975. *
  4976. * ```js
  4977. * function linkingFn(scope, elm, attrs, ctrl) {
  4978. * // get the attribute value
  4979. * console.log(attrs.ngModel);
  4980. *
  4981. * // change the attribute
  4982. * attrs.$set('ngModel', 'new value');
  4983. *
  4984. * // observe changes to interpolated attribute
  4985. * attrs.$observe('ngModel', function(value) {
  4986. * console.log('ngModel has changed value to ' + value);
  4987. * });
  4988. * }
  4989. * ```
  4990. *
  4991. * Below is an example using `$compileProvider`.
  4992. *
  4993. * <div class="alert alert-warning">
  4994. * **Note**: Typically directives are registered with `module.directive`. The example below is
  4995. * to illustrate how `$compile` works.
  4996. * </div>
  4997. *
  4998. <example module="compileExample">
  4999. <file name="index.html">
  5000. <script>
  5001. angular.module('compileExample', [], function($compileProvider) {
  5002. // configure new 'compile' directive by passing a directive
  5003. // factory function. The factory function injects the '$compile'
  5004. $compileProvider.directive('compile', function($compile) {
  5005. // directive factory creates a link function
  5006. return function(scope, element, attrs) {
  5007. scope.$watch(
  5008. function(scope) {
  5009. // watch the 'compile' expression for changes
  5010. return scope.$eval(attrs.compile);
  5011. },
  5012. function(value) {
  5013. // when the 'compile' expression changes
  5014. // assign it into the current DOM
  5015. element.html(value);
  5016. // compile the new DOM and link it to the current
  5017. // scope.
  5018. // NOTE: we only compile .childNodes so that
  5019. // we don't get into infinite loop compiling ourselves
  5020. $compile(element.contents())(scope);
  5021. }
  5022. );
  5023. };
  5024. });
  5025. })
  5026. .controller('GreeterController', ['$scope', function($scope) {
  5027. $scope.name = 'Angular';
  5028. $scope.html = 'Hello {{name}}';
  5029. }]);
  5030. </script>
  5031. <div ng-controller="GreeterController">
  5032. <input ng-model="name"> <br>
  5033. <textarea ng-model="html"></textarea> <br>
  5034. <div compile="html"></div>
  5035. </div>
  5036. </file>
  5037. <file name="protractor.js" type="protractor">
  5038. it('should auto compile', function() {
  5039. var textarea = $('textarea');
  5040. var output = $('div[compile]');
  5041. // The initial state reads 'Hello Angular'.
  5042. expect(output.getText()).toBe('Hello Angular');
  5043. textarea.clear();
  5044. textarea.sendKeys('{{name}}!');
  5045. expect(output.getText()).toBe('Angular!');
  5046. });
  5047. </file>
  5048. </example>
  5049. *
  5050. *
  5051. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5052. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
  5053. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5054. * root element(s), not their children)
  5055. * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
  5056. * (a DOM element/tree) to a scope. Where:
  5057. *
  5058. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5059. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5060. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5061. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5062. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5063. *
  5064. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5065. * * `scope` - is the current scope with which the linking function is working with.
  5066. *
  5067. * Calling the linking function returns the element of the template. It is either the original
  5068. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5069. *
  5070. * After linking the view is not updated until after a call to $digest which typically is done by
  5071. * Angular automatically.
  5072. *
  5073. * If you need access to the bound view, there are two ways to do it:
  5074. *
  5075. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5076. * before you send them to the compiler and keep this reference around.
  5077. * ```js
  5078. * var element = $compile('<p>{{total}}</p>')(scope);
  5079. * ```
  5080. *
  5081. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5082. * example would not point to the clone, but rather to the original template that was cloned. In
  5083. * this case, you can access the clone via the cloneAttachFn:
  5084. * ```js
  5085. * var templateElement = angular.element('<p>{{total}}</p>'),
  5086. * scope = ....;
  5087. *
  5088. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5089. * //attach the clone to DOM document at the right place
  5090. * });
  5091. *
  5092. * //now we have reference to the cloned DOM via `clonedElement`
  5093. * ```
  5094. *
  5095. *
  5096. * For information on how the compiler works, see the
  5097. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5098. */
  5099. var $compileMinErr = minErr('$compile');
  5100. /**
  5101. * @ngdoc provider
  5102. * @name $compileProvider
  5103. * @kind function
  5104. *
  5105. * @description
  5106. */
  5107. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5108. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5109. var hasDirectives = {},
  5110. Suffix = 'Directive',
  5111. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/,
  5112. CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/;
  5113. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5114. // The assumption is that future DOM event attribute names will begin with
  5115. // 'on' and be composed of only English letters.
  5116. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5117. /**
  5118. * @ngdoc method
  5119. * @name $compileProvider#directive
  5120. * @kind function
  5121. *
  5122. * @description
  5123. * Register a new directive with the compiler.
  5124. *
  5125. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5126. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5127. * names and the values are the factories.
  5128. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5129. * {@link guide/directive} for more info.
  5130. * @returns {ng.$compileProvider} Self for chaining.
  5131. */
  5132. this.directive = function registerDirective(name, directiveFactory) {
  5133. assertNotHasOwnProperty(name, 'directive');
  5134. if (isString(name)) {
  5135. assertArg(directiveFactory, 'directiveFactory');
  5136. if (!hasDirectives.hasOwnProperty(name)) {
  5137. hasDirectives[name] = [];
  5138. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5139. function($injector, $exceptionHandler) {
  5140. var directives = [];
  5141. forEach(hasDirectives[name], function(directiveFactory, index) {
  5142. try {
  5143. var directive = $injector.invoke(directiveFactory);
  5144. if (isFunction(directive)) {
  5145. directive = { compile: valueFn(directive) };
  5146. } else if (!directive.compile && directive.link) {
  5147. directive.compile = valueFn(directive.link);
  5148. }
  5149. directive.priority = directive.priority || 0;
  5150. directive.index = index;
  5151. directive.name = directive.name || name;
  5152. directive.require = directive.require || (directive.controller && directive.name);
  5153. directive.restrict = directive.restrict || 'A';
  5154. directives.push(directive);
  5155. } catch (e) {
  5156. $exceptionHandler(e);
  5157. }
  5158. });
  5159. return directives;
  5160. }]);
  5161. }
  5162. hasDirectives[name].push(directiveFactory);
  5163. } else {
  5164. forEach(name, reverseParams(registerDirective));
  5165. }
  5166. return this;
  5167. };
  5168. /**
  5169. * @ngdoc method
  5170. * @name $compileProvider#aHrefSanitizationWhitelist
  5171. * @kind function
  5172. *
  5173. * @description
  5174. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5175. * urls during a[href] sanitization.
  5176. *
  5177. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5178. *
  5179. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5180. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5181. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5182. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5183. *
  5184. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5185. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5186. * chaining otherwise.
  5187. */
  5188. this.aHrefSanitizationWhitelist = function(regexp) {
  5189. if (isDefined(regexp)) {
  5190. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5191. return this;
  5192. } else {
  5193. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5194. }
  5195. };
  5196. /**
  5197. * @ngdoc method
  5198. * @name $compileProvider#imgSrcSanitizationWhitelist
  5199. * @kind function
  5200. *
  5201. * @description
  5202. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5203. * urls during img[src] sanitization.
  5204. *
  5205. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5206. *
  5207. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5208. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5209. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5210. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5211. *
  5212. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5213. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5214. * chaining otherwise.
  5215. */
  5216. this.imgSrcSanitizationWhitelist = function(regexp) {
  5217. if (isDefined(regexp)) {
  5218. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5219. return this;
  5220. } else {
  5221. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5222. }
  5223. };
  5224. this.$get = [
  5225. '$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
  5226. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5227. function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
  5228. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5229. var Attributes = function(element, attr) {
  5230. this.$$element = element;
  5231. this.$attr = attr || {};
  5232. };
  5233. Attributes.prototype = {
  5234. $normalize: directiveNormalize,
  5235. /**
  5236. * @ngdoc method
  5237. * @name $compile.directive.Attributes#$addClass
  5238. * @kind function
  5239. *
  5240. * @description
  5241. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5242. * are enabled then an animation will be triggered for the class addition.
  5243. *
  5244. * @param {string} classVal The className value that will be added to the element
  5245. */
  5246. $addClass : function(classVal) {
  5247. if(classVal && classVal.length > 0) {
  5248. $animate.addClass(this.$$element, classVal);
  5249. }
  5250. },
  5251. /**
  5252. * @ngdoc method
  5253. * @name $compile.directive.Attributes#$removeClass
  5254. * @kind function
  5255. *
  5256. * @description
  5257. * Removes the CSS class value specified by the classVal parameter from the element. If
  5258. * animations are enabled then an animation will be triggered for the class removal.
  5259. *
  5260. * @param {string} classVal The className value that will be removed from the element
  5261. */
  5262. $removeClass : function(classVal) {
  5263. if(classVal && classVal.length > 0) {
  5264. $animate.removeClass(this.$$element, classVal);
  5265. }
  5266. },
  5267. /**
  5268. * @ngdoc method
  5269. * @name $compile.directive.Attributes#$updateClass
  5270. * @kind function
  5271. *
  5272. * @description
  5273. * Adds and removes the appropriate CSS class values to the element based on the difference
  5274. * between the new and old CSS class values (specified as newClasses and oldClasses).
  5275. *
  5276. * @param {string} newClasses The current CSS className value
  5277. * @param {string} oldClasses The former CSS className value
  5278. */
  5279. $updateClass : function(newClasses, oldClasses) {
  5280. var toAdd = tokenDifference(newClasses, oldClasses);
  5281. var toRemove = tokenDifference(oldClasses, newClasses);
  5282. if(toAdd.length === 0) {
  5283. $animate.removeClass(this.$$element, toRemove);
  5284. } else if(toRemove.length === 0) {
  5285. $animate.addClass(this.$$element, toAdd);
  5286. } else {
  5287. $animate.setClass(this.$$element, toAdd, toRemove);
  5288. }
  5289. },
  5290. /**
  5291. * Set a normalized attribute on the element in a way such that all directives
  5292. * can share the attribute. This function properly handles boolean attributes.
  5293. * @param {string} key Normalized key. (ie ngAttribute)
  5294. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  5295. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  5296. * Defaults to true.
  5297. * @param {string=} attrName Optional none normalized name. Defaults to key.
  5298. */
  5299. $set: function(key, value, writeAttr, attrName) {
  5300. // TODO: decide whether or not to throw an error if "class"
  5301. //is set through this function since it may cause $updateClass to
  5302. //become unstable.
  5303. var booleanKey = getBooleanAttrName(this.$$element[0], key),
  5304. normalizedVal,
  5305. nodeName;
  5306. if (booleanKey) {
  5307. this.$$element.prop(key, value);
  5308. attrName = booleanKey;
  5309. }
  5310. this[key] = value;
  5311. // translate normalized key to actual key
  5312. if (attrName) {
  5313. this.$attr[key] = attrName;
  5314. } else {
  5315. attrName = this.$attr[key];
  5316. if (!attrName) {
  5317. this.$attr[key] = attrName = snake_case(key, '-');
  5318. }
  5319. }
  5320. nodeName = nodeName_(this.$$element);
  5321. // sanitize a[href] and img[src] values
  5322. if ((nodeName === 'A' && key === 'href') ||
  5323. (nodeName === 'IMG' && key === 'src')) {
  5324. this[key] = value = $$sanitizeUri(value, key === 'src');
  5325. }
  5326. if (writeAttr !== false) {
  5327. if (value === null || value === undefined) {
  5328. this.$$element.removeAttr(attrName);
  5329. } else {
  5330. this.$$element.attr(attrName, value);
  5331. }
  5332. }
  5333. // fire observers
  5334. var $$observers = this.$$observers;
  5335. $$observers && forEach($$observers[key], function(fn) {
  5336. try {
  5337. fn(value);
  5338. } catch (e) {
  5339. $exceptionHandler(e);
  5340. }
  5341. });
  5342. },
  5343. /**
  5344. * @ngdoc method
  5345. * @name $compile.directive.Attributes#$observe
  5346. * @kind function
  5347. *
  5348. * @description
  5349. * Observes an interpolated attribute.
  5350. *
  5351. * The observer function will be invoked once during the next `$digest` following
  5352. * compilation. The observer is then invoked whenever the interpolated value
  5353. * changes.
  5354. *
  5355. * @param {string} key Normalized key. (ie ngAttribute) .
  5356. * @param {function(interpolatedValue)} fn Function that will be called whenever
  5357. the interpolated value of the attribute changes.
  5358. * See the {@link guide/directive#Attributes Directives} guide for more info.
  5359. * @returns {function()} the `fn` parameter.
  5360. */
  5361. $observe: function(key, fn) {
  5362. var attrs = this,
  5363. $$observers = (attrs.$$observers || (attrs.$$observers = {})),
  5364. listeners = ($$observers[key] || ($$observers[key] = []));
  5365. listeners.push(fn);
  5366. $rootScope.$evalAsync(function() {
  5367. if (!listeners.$$inter) {
  5368. // no one registered attribute interpolation function, so lets call it manually
  5369. fn(attrs[key]);
  5370. }
  5371. });
  5372. return fn;
  5373. }
  5374. };
  5375. var startSymbol = $interpolate.startSymbol(),
  5376. endSymbol = $interpolate.endSymbol(),
  5377. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  5378. ? identity
  5379. : function denormalizeTemplate(template) {
  5380. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  5381. },
  5382. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  5383. return compile;
  5384. //================================
  5385. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  5386. previousCompileContext) {
  5387. if (!($compileNodes instanceof jqLite)) {
  5388. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  5389. // modify it.
  5390. $compileNodes = jqLite($compileNodes);
  5391. }
  5392. // We can not compile top level text elements since text nodes can be merged and we will
  5393. // not be able to attach scope data to them, so we will wrap them in <span>
  5394. forEach($compileNodes, function(node, index){
  5395. if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  5396. $compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
  5397. }
  5398. });
  5399. var compositeLinkFn =
  5400. compileNodes($compileNodes, transcludeFn, $compileNodes,
  5401. maxPriority, ignoreDirective, previousCompileContext);
  5402. safeAddClass($compileNodes, 'ng-scope');
  5403. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn){
  5404. assertArg(scope, 'scope');
  5405. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  5406. // and sometimes changes the structure of the DOM.
  5407. var $linkNode = cloneConnectFn
  5408. ? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
  5409. : $compileNodes;
  5410. forEach(transcludeControllers, function(instance, name) {
  5411. $linkNode.data('$' + name + 'Controller', instance);
  5412. });
  5413. // Attach scope only to non-text nodes.
  5414. for(var i = 0, ii = $linkNode.length; i<ii; i++) {
  5415. var node = $linkNode[i],
  5416. nodeType = node.nodeType;
  5417. if (nodeType === 1 /* element */ || nodeType === 9 /* document */) {
  5418. $linkNode.eq(i).data('$scope', scope);
  5419. }
  5420. }
  5421. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  5422. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  5423. return $linkNode;
  5424. };
  5425. }
  5426. function safeAddClass($element, className) {
  5427. try {
  5428. $element.addClass(className);
  5429. } catch(e) {
  5430. // ignore, since it means that we are trying to set class on
  5431. // SVG element, where class name is read-only.
  5432. }
  5433. }
  5434. /**
  5435. * Compile function matches each node in nodeList against the directives. Once all directives
  5436. * for a particular node are collected their compile functions are executed. The compile
  5437. * functions return values - the linking functions - are combined into a composite linking
  5438. * function, which is the a linking function for the node.
  5439. *
  5440. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  5441. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5442. * scope argument is auto-generated to the new child of the transcluded parent scope.
  5443. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  5444. * the rootElement must be set the jqLite collection of the compile root. This is
  5445. * needed so that the jqLite collection items can be replaced with widgets.
  5446. * @param {number=} maxPriority Max directive priority.
  5447. * @returns {Function} A composite linking function of all of the matched directives or null.
  5448. */
  5449. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  5450. previousCompileContext) {
  5451. var linkFns = [],
  5452. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound;
  5453. for (var i = 0; i < nodeList.length; i++) {
  5454. attrs = new Attributes();
  5455. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  5456. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  5457. ignoreDirective);
  5458. nodeLinkFn = (directives.length)
  5459. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  5460. null, [], [], previousCompileContext)
  5461. : null;
  5462. if (nodeLinkFn && nodeLinkFn.scope) {
  5463. safeAddClass(attrs.$$element, 'ng-scope');
  5464. }
  5465. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  5466. !(childNodes = nodeList[i].childNodes) ||
  5467. !childNodes.length)
  5468. ? null
  5469. : compileNodes(childNodes,
  5470. nodeLinkFn ? (
  5471. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  5472. && nodeLinkFn.transclude) : transcludeFn);
  5473. linkFns.push(nodeLinkFn, childLinkFn);
  5474. linkFnFound = linkFnFound || nodeLinkFn || childLinkFn;
  5475. //use the previous context only for the first element in the virtual group
  5476. previousCompileContext = null;
  5477. }
  5478. // return a linking function if we have found anything, null otherwise
  5479. return linkFnFound ? compositeLinkFn : null;
  5480. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  5481. var nodeLinkFn, childLinkFn, node, childScope, i, ii, n, childBoundTranscludeFn;
  5482. // copy nodeList so that linking doesn't break due to live list updates.
  5483. var nodeListLength = nodeList.length,
  5484. stableNodeList = new Array(nodeListLength);
  5485. for (i = 0; i < nodeListLength; i++) {
  5486. stableNodeList[i] = nodeList[i];
  5487. }
  5488. for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
  5489. node = stableNodeList[n];
  5490. nodeLinkFn = linkFns[i++];
  5491. childLinkFn = linkFns[i++];
  5492. if (nodeLinkFn) {
  5493. if (nodeLinkFn.scope) {
  5494. childScope = scope.$new();
  5495. jqLite.data(node, '$scope', childScope);
  5496. } else {
  5497. childScope = scope;
  5498. }
  5499. if ( nodeLinkFn.transcludeOnThisElement ) {
  5500. childBoundTranscludeFn = createBoundTranscludeFn(scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  5501. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  5502. childBoundTranscludeFn = parentBoundTranscludeFn;
  5503. } else if (!parentBoundTranscludeFn && transcludeFn) {
  5504. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  5505. } else {
  5506. childBoundTranscludeFn = null;
  5507. }
  5508. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  5509. } else if (childLinkFn) {
  5510. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  5511. }
  5512. }
  5513. }
  5514. }
  5515. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  5516. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers) {
  5517. var scopeCreated = false;
  5518. if (!transcludedScope) {
  5519. transcludedScope = scope.$new();
  5520. transcludedScope.$$transcluded = true;
  5521. scopeCreated = true;
  5522. }
  5523. var clone = transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn);
  5524. if (scopeCreated) {
  5525. clone.on('$destroy', function() { transcludedScope.$destroy(); });
  5526. }
  5527. return clone;
  5528. };
  5529. return boundTranscludeFn;
  5530. }
  5531. /**
  5532. * Looks for directives on the given node and adds them to the directive collection which is
  5533. * sorted.
  5534. *
  5535. * @param node Node to search.
  5536. * @param directives An array to which the directives are added to. This array is sorted before
  5537. * the function returns.
  5538. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  5539. * @param {number=} maxPriority Max directive priority.
  5540. */
  5541. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  5542. var nodeType = node.nodeType,
  5543. attrsMap = attrs.$attr,
  5544. match,
  5545. className;
  5546. switch(nodeType) {
  5547. case 1: /* Element */
  5548. // use the node name: <directive>
  5549. addDirective(directives,
  5550. directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
  5551. // iterate over the attributes
  5552. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  5553. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  5554. var attrStartName = false;
  5555. var attrEndName = false;
  5556. attr = nAttrs[j];
  5557. if (!msie || msie >= 8 || attr.specified) {
  5558. name = attr.name;
  5559. value = trim(attr.value);
  5560. // support ngAttr attribute binding
  5561. ngAttrName = directiveNormalize(name);
  5562. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  5563. name = snake_case(ngAttrName.substr(6), '-');
  5564. }
  5565. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  5566. if (ngAttrName === directiveNName + 'Start') {
  5567. attrStartName = name;
  5568. attrEndName = name.substr(0, name.length - 5) + 'end';
  5569. name = name.substr(0, name.length - 6);
  5570. }
  5571. nName = directiveNormalize(name.toLowerCase());
  5572. attrsMap[nName] = name;
  5573. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  5574. attrs[nName] = value;
  5575. if (getBooleanAttrName(node, nName)) {
  5576. attrs[nName] = true; // presence means true
  5577. }
  5578. }
  5579. addAttrInterpolateDirective(node, directives, value, nName);
  5580. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  5581. attrEndName);
  5582. }
  5583. }
  5584. // use class as directive
  5585. className = node.className;
  5586. if (isString(className) && className !== '') {
  5587. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  5588. nName = directiveNormalize(match[2]);
  5589. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  5590. attrs[nName] = trim(match[3]);
  5591. }
  5592. className = className.substr(match.index + match[0].length);
  5593. }
  5594. }
  5595. break;
  5596. case 3: /* Text Node */
  5597. addTextInterpolateDirective(directives, node.nodeValue);
  5598. break;
  5599. case 8: /* Comment */
  5600. try {
  5601. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  5602. if (match) {
  5603. nName = directiveNormalize(match[1]);
  5604. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  5605. attrs[nName] = trim(match[2]);
  5606. }
  5607. }
  5608. } catch (e) {
  5609. // turns out that under some circumstances IE9 throws errors when one attempts to read
  5610. // comment's node value.
  5611. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  5612. }
  5613. break;
  5614. }
  5615. directives.sort(byPriority);
  5616. return directives;
  5617. }
  5618. /**
  5619. * Given a node with an directive-start it collects all of the siblings until it finds
  5620. * directive-end.
  5621. * @param node
  5622. * @param attrStart
  5623. * @param attrEnd
  5624. * @returns {*}
  5625. */
  5626. function groupScan(node, attrStart, attrEnd) {
  5627. var nodes = [];
  5628. var depth = 0;
  5629. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  5630. var startNode = node;
  5631. do {
  5632. if (!node) {
  5633. throw $compileMinErr('uterdir',
  5634. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  5635. attrStart, attrEnd);
  5636. }
  5637. if (node.nodeType == 1 /** Element **/) {
  5638. if (node.hasAttribute(attrStart)) depth++;
  5639. if (node.hasAttribute(attrEnd)) depth--;
  5640. }
  5641. nodes.push(node);
  5642. node = node.nextSibling;
  5643. } while (depth > 0);
  5644. } else {
  5645. nodes.push(node);
  5646. }
  5647. return jqLite(nodes);
  5648. }
  5649. /**
  5650. * Wrapper for linking function which converts normal linking function into a grouped
  5651. * linking function.
  5652. * @param linkFn
  5653. * @param attrStart
  5654. * @param attrEnd
  5655. * @returns {Function}
  5656. */
  5657. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  5658. return function(scope, element, attrs, controllers, transcludeFn) {
  5659. element = groupScan(element[0], attrStart, attrEnd);
  5660. return linkFn(scope, element, attrs, controllers, transcludeFn);
  5661. };
  5662. }
  5663. /**
  5664. * Once the directives have been collected, their compile functions are executed. This method
  5665. * is responsible for inlining directive templates as well as terminating the application
  5666. * of the directives if the terminal directive has been reached.
  5667. *
  5668. * @param {Array} directives Array of collected directives to execute their compile function.
  5669. * this needs to be pre-sorted by priority order.
  5670. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  5671. * @param {Object} templateAttrs The shared attribute function
  5672. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  5673. * scope argument is auto-generated to the new
  5674. * child of the transcluded parent scope.
  5675. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  5676. * argument has the root jqLite array so that we can replace nodes
  5677. * on it.
  5678. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  5679. * compiling the transclusion.
  5680. * @param {Array.<Function>} preLinkFns
  5681. * @param {Array.<Function>} postLinkFns
  5682. * @param {Object} previousCompileContext Context used for previous compilation of the current
  5683. * node
  5684. * @returns {Function} linkFn
  5685. */
  5686. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  5687. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  5688. previousCompileContext) {
  5689. previousCompileContext = previousCompileContext || {};
  5690. var terminalPriority = -Number.MAX_VALUE,
  5691. newScopeDirective,
  5692. controllerDirectives = previousCompileContext.controllerDirectives,
  5693. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  5694. templateDirective = previousCompileContext.templateDirective,
  5695. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  5696. hasTranscludeDirective = false,
  5697. hasTemplate = false,
  5698. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  5699. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  5700. directive,
  5701. directiveName,
  5702. $template,
  5703. replaceDirective = originalReplaceDirective,
  5704. childTranscludeFn = transcludeFn,
  5705. linkFn,
  5706. directiveValue;
  5707. // executes all directives on the current element
  5708. for(var i = 0, ii = directives.length; i < ii; i++) {
  5709. directive = directives[i];
  5710. var attrStart = directive.$$start;
  5711. var attrEnd = directive.$$end;
  5712. // collect multiblock sections
  5713. if (attrStart) {
  5714. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  5715. }
  5716. $template = undefined;
  5717. if (terminalPriority > directive.priority) {
  5718. break; // prevent further processing of directives
  5719. }
  5720. if (directiveValue = directive.scope) {
  5721. newScopeDirective = newScopeDirective || directive;
  5722. // skip the check for directives with async templates, we'll check the derived sync
  5723. // directive when the template arrives
  5724. if (!directive.templateUrl) {
  5725. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  5726. $compileNode);
  5727. if (isObject(directiveValue)) {
  5728. newIsolateScopeDirective = directive;
  5729. }
  5730. }
  5731. }
  5732. directiveName = directive.name;
  5733. if (!directive.templateUrl && directive.controller) {
  5734. directiveValue = directive.controller;
  5735. controllerDirectives = controllerDirectives || {};
  5736. assertNoDuplicate("'" + directiveName + "' controller",
  5737. controllerDirectives[directiveName], directive, $compileNode);
  5738. controllerDirectives[directiveName] = directive;
  5739. }
  5740. if (directiveValue = directive.transclude) {
  5741. hasTranscludeDirective = true;
  5742. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  5743. // This option should only be used by directives that know how to safely handle element transclusion,
  5744. // where the transcluded nodes are added or replaced after linking.
  5745. if (!directive.$$tlb) {
  5746. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  5747. nonTlbTranscludeDirective = directive;
  5748. }
  5749. if (directiveValue == 'element') {
  5750. hasElementTranscludeDirective = true;
  5751. terminalPriority = directive.priority;
  5752. $template = $compileNode;
  5753. $compileNode = templateAttrs.$$element =
  5754. jqLite(document.createComment(' ' + directiveName + ': ' +
  5755. templateAttrs[directiveName] + ' '));
  5756. compileNode = $compileNode[0];
  5757. replaceWith(jqCollection, sliceArgs($template), compileNode);
  5758. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  5759. replaceDirective && replaceDirective.name, {
  5760. // Don't pass in:
  5761. // - controllerDirectives - otherwise we'll create duplicates controllers
  5762. // - newIsolateScopeDirective or templateDirective - combining templates with
  5763. // element transclusion doesn't make sense.
  5764. //
  5765. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  5766. // on the same element more than once.
  5767. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5768. });
  5769. } else {
  5770. $template = jqLite(jqLiteClone(compileNode)).contents();
  5771. $compileNode.empty(); // clear contents
  5772. childTranscludeFn = compile($template, transcludeFn);
  5773. }
  5774. }
  5775. if (directive.template) {
  5776. hasTemplate = true;
  5777. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5778. templateDirective = directive;
  5779. directiveValue = (isFunction(directive.template))
  5780. ? directive.template($compileNode, templateAttrs)
  5781. : directive.template;
  5782. directiveValue = denormalizeTemplate(directiveValue);
  5783. if (directive.replace) {
  5784. replaceDirective = directive;
  5785. if (jqLiteIsTextNode(directiveValue)) {
  5786. $template = [];
  5787. } else {
  5788. $template = jqLite(trim(directiveValue));
  5789. }
  5790. compileNode = $template[0];
  5791. if ($template.length != 1 || compileNode.nodeType !== 1) {
  5792. throw $compileMinErr('tplrt',
  5793. "Template for directive '{0}' must have exactly one root element. {1}",
  5794. directiveName, '');
  5795. }
  5796. replaceWith(jqCollection, $compileNode, compileNode);
  5797. var newTemplateAttrs = {$attr: {}};
  5798. // combine directives from the original node and from the template:
  5799. // - take the array of directives for this element
  5800. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  5801. // - collect directives from the template and sort them by priority
  5802. // - combine directives as: processed + template + unprocessed
  5803. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  5804. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  5805. if (newIsolateScopeDirective) {
  5806. markDirectivesAsIsolate(templateDirectives);
  5807. }
  5808. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  5809. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  5810. ii = directives.length;
  5811. } else {
  5812. $compileNode.html(directiveValue);
  5813. }
  5814. }
  5815. if (directive.templateUrl) {
  5816. hasTemplate = true;
  5817. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  5818. templateDirective = directive;
  5819. if (directive.replace) {
  5820. replaceDirective = directive;
  5821. }
  5822. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  5823. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  5824. controllerDirectives: controllerDirectives,
  5825. newIsolateScopeDirective: newIsolateScopeDirective,
  5826. templateDirective: templateDirective,
  5827. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  5828. });
  5829. ii = directives.length;
  5830. } else if (directive.compile) {
  5831. try {
  5832. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  5833. if (isFunction(linkFn)) {
  5834. addLinkFns(null, linkFn, attrStart, attrEnd);
  5835. } else if (linkFn) {
  5836. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  5837. }
  5838. } catch (e) {
  5839. $exceptionHandler(e, startingTag($compileNode));
  5840. }
  5841. }
  5842. if (directive.terminal) {
  5843. nodeLinkFn.terminal = true;
  5844. terminalPriority = Math.max(terminalPriority, directive.priority);
  5845. }
  5846. }
  5847. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  5848. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  5849. nodeLinkFn.templateOnThisElement = hasTemplate;
  5850. nodeLinkFn.transclude = childTranscludeFn;
  5851. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  5852. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  5853. return nodeLinkFn;
  5854. ////////////////////
  5855. function addLinkFns(pre, post, attrStart, attrEnd) {
  5856. if (pre) {
  5857. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  5858. pre.require = directive.require;
  5859. pre.directiveName = directiveName;
  5860. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5861. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  5862. }
  5863. preLinkFns.push(pre);
  5864. }
  5865. if (post) {
  5866. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  5867. post.require = directive.require;
  5868. post.directiveName = directiveName;
  5869. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  5870. post = cloneAndAnnotateFn(post, {isolateScope: true});
  5871. }
  5872. postLinkFns.push(post);
  5873. }
  5874. }
  5875. function getControllers(directiveName, require, $element, elementControllers) {
  5876. var value, retrievalMethod = 'data', optional = false;
  5877. if (isString(require)) {
  5878. while((value = require.charAt(0)) == '^' || value == '?') {
  5879. require = require.substr(1);
  5880. if (value == '^') {
  5881. retrievalMethod = 'inheritedData';
  5882. }
  5883. optional = optional || value == '?';
  5884. }
  5885. value = null;
  5886. if (elementControllers && retrievalMethod === 'data') {
  5887. value = elementControllers[require];
  5888. }
  5889. value = value || $element[retrievalMethod]('$' + require + 'Controller');
  5890. if (!value && !optional) {
  5891. throw $compileMinErr('ctreq',
  5892. "Controller '{0}', required by directive '{1}', can't be found!",
  5893. require, directiveName);
  5894. }
  5895. return value;
  5896. } else if (isArray(require)) {
  5897. value = [];
  5898. forEach(require, function(require) {
  5899. value.push(getControllers(directiveName, require, $element, elementControllers));
  5900. });
  5901. }
  5902. return value;
  5903. }
  5904. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  5905. var attrs, $element, i, ii, linkFn, controller, isolateScope, elementControllers = {}, transcludeFn;
  5906. attrs = (compileNode === linkNode)
  5907. ? templateAttrs
  5908. : shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
  5909. $element = attrs.$$element;
  5910. if (newIsolateScopeDirective) {
  5911. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5912. isolateScope = scope.$new(true);
  5913. if (templateDirective && (templateDirective === newIsolateScopeDirective ||
  5914. templateDirective === newIsolateScopeDirective.$$originalDirective)) {
  5915. $element.data('$isolateScope', isolateScope);
  5916. } else {
  5917. $element.data('$isolateScopeNoTemplate', isolateScope);
  5918. }
  5919. safeAddClass($element, 'ng-isolate-scope');
  5920. forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
  5921. var match = definition.match(LOCAL_REGEXP) || [],
  5922. attrName = match[3] || scopeName,
  5923. optional = (match[2] == '?'),
  5924. mode = match[1], // @, =, or &
  5925. lastValue,
  5926. parentGet, parentSet, compare;
  5927. isolateScope.$$isolateBindings[scopeName] = mode + attrName;
  5928. switch (mode) {
  5929. case '@':
  5930. attrs.$observe(attrName, function(value) {
  5931. isolateScope[scopeName] = value;
  5932. });
  5933. attrs.$$observers[attrName].$$scope = scope;
  5934. if( attrs[attrName] ) {
  5935. // If the attribute has been provided then we trigger an interpolation to ensure
  5936. // the value is there for use in the link fn
  5937. isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
  5938. }
  5939. break;
  5940. case '=':
  5941. if (optional && !attrs[attrName]) {
  5942. return;
  5943. }
  5944. parentGet = $parse(attrs[attrName]);
  5945. if (parentGet.literal) {
  5946. compare = equals;
  5947. } else {
  5948. compare = function(a,b) { return a === b; };
  5949. }
  5950. parentSet = parentGet.assign || function() {
  5951. // reset the change, or we will throw this exception on every $digest
  5952. lastValue = isolateScope[scopeName] = parentGet(scope);
  5953. throw $compileMinErr('nonassign',
  5954. "Expression '{0}' used with directive '{1}' is non-assignable!",
  5955. attrs[attrName], newIsolateScopeDirective.name);
  5956. };
  5957. lastValue = isolateScope[scopeName] = parentGet(scope);
  5958. isolateScope.$watch(function parentValueWatch() {
  5959. var parentValue = parentGet(scope);
  5960. if (!compare(parentValue, isolateScope[scopeName])) {
  5961. // we are out of sync and need to copy
  5962. if (!compare(parentValue, lastValue)) {
  5963. // parent changed and it has precedence
  5964. isolateScope[scopeName] = parentValue;
  5965. } else {
  5966. // if the parent can be assigned then do so
  5967. parentSet(scope, parentValue = isolateScope[scopeName]);
  5968. }
  5969. }
  5970. return lastValue = parentValue;
  5971. }, null, parentGet.literal);
  5972. break;
  5973. case '&':
  5974. parentGet = $parse(attrs[attrName]);
  5975. isolateScope[scopeName] = function(locals) {
  5976. return parentGet(scope, locals);
  5977. };
  5978. break;
  5979. default:
  5980. throw $compileMinErr('iscp',
  5981. "Invalid isolate scope definition for directive '{0}'." +
  5982. " Definition: {... {1}: '{2}' ...}",
  5983. newIsolateScopeDirective.name, scopeName, definition);
  5984. }
  5985. });
  5986. }
  5987. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  5988. if (controllerDirectives) {
  5989. forEach(controllerDirectives, function(directive) {
  5990. var locals = {
  5991. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  5992. $element: $element,
  5993. $attrs: attrs,
  5994. $transclude: transcludeFn
  5995. }, controllerInstance;
  5996. controller = directive.controller;
  5997. if (controller == '@') {
  5998. controller = attrs[directive.name];
  5999. }
  6000. controllerInstance = $controller(controller, locals);
  6001. // For directives with element transclusion the element is a comment,
  6002. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6003. // clean up (http://bugs.jquery.com/ticket/8335).
  6004. // Instead, we save the controllers for the element in a local hash and attach to .data
  6005. // later, once we have the actual element.
  6006. elementControllers[directive.name] = controllerInstance;
  6007. if (!hasElementTranscludeDirective) {
  6008. $element.data('$' + directive.name + 'Controller', controllerInstance);
  6009. }
  6010. if (directive.controllerAs) {
  6011. locals.$scope[directive.controllerAs] = controllerInstance;
  6012. }
  6013. });
  6014. }
  6015. // PRELINKING
  6016. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  6017. try {
  6018. linkFn = preLinkFns[i];
  6019. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  6020. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  6021. } catch (e) {
  6022. $exceptionHandler(e, startingTag($element));
  6023. }
  6024. }
  6025. // RECURSION
  6026. // We only pass the isolate scope, if the isolate directive has a template,
  6027. // otherwise the child elements do not belong to the isolate directive.
  6028. var scopeToChild = scope;
  6029. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6030. scopeToChild = isolateScope;
  6031. }
  6032. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6033. // POSTLINKING
  6034. for(i = postLinkFns.length - 1; i >= 0; i--) {
  6035. try {
  6036. linkFn = postLinkFns[i];
  6037. linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
  6038. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers), transcludeFn);
  6039. } catch (e) {
  6040. $exceptionHandler(e, startingTag($element));
  6041. }
  6042. }
  6043. // This is the function that is injected as `$transclude`.
  6044. function controllersBoundTransclude(scope, cloneAttachFn) {
  6045. var transcludeControllers;
  6046. // no scope passed
  6047. if (arguments.length < 2) {
  6048. cloneAttachFn = scope;
  6049. scope = undefined;
  6050. }
  6051. if (hasElementTranscludeDirective) {
  6052. transcludeControllers = elementControllers;
  6053. }
  6054. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers);
  6055. }
  6056. }
  6057. }
  6058. function markDirectivesAsIsolate(directives) {
  6059. // mark all directives as needing isolate scope.
  6060. for (var j = 0, jj = directives.length; j < jj; j++) {
  6061. directives[j] = inherit(directives[j], {$$isolateScope: true});
  6062. }
  6063. }
  6064. /**
  6065. * looks up the directive and decorates it with exception handling and proper parameters. We
  6066. * call this the boundDirective.
  6067. *
  6068. * @param {string} name name of the directive to look up.
  6069. * @param {string} location The directive must be found in specific format.
  6070. * String containing any of theses characters:
  6071. *
  6072. * * `E`: element name
  6073. * * `A': attribute
  6074. * * `C`: class
  6075. * * `M`: comment
  6076. * @returns {boolean} true if directive was added.
  6077. */
  6078. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6079. endAttrName) {
  6080. if (name === ignoreDirective) return null;
  6081. var match = null;
  6082. if (hasDirectives.hasOwnProperty(name)) {
  6083. for(var directive, directives = $injector.get(name + Suffix),
  6084. i = 0, ii = directives.length; i<ii; i++) {
  6085. try {
  6086. directive = directives[i];
  6087. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  6088. directive.restrict.indexOf(location) != -1) {
  6089. if (startAttrName) {
  6090. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6091. }
  6092. tDirectives.push(directive);
  6093. match = directive;
  6094. }
  6095. } catch(e) { $exceptionHandler(e); }
  6096. }
  6097. }
  6098. return match;
  6099. }
  6100. /**
  6101. * When the element is replaced with HTML template then the new attributes
  6102. * on the template need to be merged with the existing attributes in the DOM.
  6103. * The desired effect is to have both of the attributes present.
  6104. *
  6105. * @param {object} dst destination attributes (original DOM)
  6106. * @param {object} src source attributes (from the directive template)
  6107. */
  6108. function mergeTemplateAttributes(dst, src) {
  6109. var srcAttr = src.$attr,
  6110. dstAttr = dst.$attr,
  6111. $element = dst.$$element;
  6112. // reapply the old attributes to the new element
  6113. forEach(dst, function(value, key) {
  6114. if (key.charAt(0) != '$') {
  6115. if (src[key] && src[key] !== value) {
  6116. value += (key === 'style' ? ';' : ' ') + src[key];
  6117. }
  6118. dst.$set(key, value, true, srcAttr[key]);
  6119. }
  6120. });
  6121. // copy the new attributes on the old attrs object
  6122. forEach(src, function(value, key) {
  6123. if (key == 'class') {
  6124. safeAddClass($element, value);
  6125. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  6126. } else if (key == 'style') {
  6127. $element.attr('style', $element.attr('style') + ';' + value);
  6128. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  6129. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  6130. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  6131. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  6132. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  6133. dst[key] = value;
  6134. dstAttr[key] = srcAttr[key];
  6135. }
  6136. });
  6137. }
  6138. function compileTemplateUrl(directives, $compileNode, tAttrs,
  6139. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  6140. var linkQueue = [],
  6141. afterTemplateNodeLinkFn,
  6142. afterTemplateChildLinkFn,
  6143. beforeTemplateCompileNode = $compileNode[0],
  6144. origAsyncDirective = directives.shift(),
  6145. // The fact that we have to copy and patch the directive seems wrong!
  6146. derivedSyncDirective = extend({}, origAsyncDirective, {
  6147. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  6148. }),
  6149. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  6150. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  6151. : origAsyncDirective.templateUrl;
  6152. $compileNode.empty();
  6153. $http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
  6154. success(function(content) {
  6155. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  6156. content = denormalizeTemplate(content);
  6157. if (origAsyncDirective.replace) {
  6158. if (jqLiteIsTextNode(content)) {
  6159. $template = [];
  6160. } else {
  6161. $template = jqLite(trim(content));
  6162. }
  6163. compileNode = $template[0];
  6164. if ($template.length != 1 || compileNode.nodeType !== 1) {
  6165. throw $compileMinErr('tplrt',
  6166. "Template for directive '{0}' must have exactly one root element. {1}",
  6167. origAsyncDirective.name, templateUrl);
  6168. }
  6169. tempTemplateAttrs = {$attr: {}};
  6170. replaceWith($rootElement, $compileNode, compileNode);
  6171. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  6172. if (isObject(origAsyncDirective.scope)) {
  6173. markDirectivesAsIsolate(templateDirectives);
  6174. }
  6175. directives = templateDirectives.concat(directives);
  6176. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  6177. } else {
  6178. compileNode = beforeTemplateCompileNode;
  6179. $compileNode.html(content);
  6180. }
  6181. directives.unshift(derivedSyncDirective);
  6182. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  6183. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  6184. previousCompileContext);
  6185. forEach($rootElement, function(node, i) {
  6186. if (node == compileNode) {
  6187. $rootElement[i] = $compileNode[0];
  6188. }
  6189. });
  6190. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  6191. while(linkQueue.length) {
  6192. var scope = linkQueue.shift(),
  6193. beforeTemplateLinkNode = linkQueue.shift(),
  6194. linkRootElement = linkQueue.shift(),
  6195. boundTranscludeFn = linkQueue.shift(),
  6196. linkNode = $compileNode[0];
  6197. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  6198. var oldClasses = beforeTemplateLinkNode.className;
  6199. if (!(previousCompileContext.hasElementTranscludeDirective &&
  6200. origAsyncDirective.replace)) {
  6201. // it was cloned therefore we have to clone as well.
  6202. linkNode = jqLiteClone(compileNode);
  6203. }
  6204. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  6205. // Copy in CSS classes from original node
  6206. safeAddClass(jqLite(linkNode), oldClasses);
  6207. }
  6208. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  6209. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  6210. } else {
  6211. childBoundTranscludeFn = boundTranscludeFn;
  6212. }
  6213. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  6214. childBoundTranscludeFn);
  6215. }
  6216. linkQueue = null;
  6217. }).
  6218. error(function(response, code, headers, config) {
  6219. throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
  6220. });
  6221. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  6222. var childBoundTranscludeFn = boundTranscludeFn;
  6223. if (linkQueue) {
  6224. linkQueue.push(scope);
  6225. linkQueue.push(node);
  6226. linkQueue.push(rootElement);
  6227. linkQueue.push(childBoundTranscludeFn);
  6228. } else {
  6229. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  6230. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  6231. }
  6232. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  6233. }
  6234. };
  6235. }
  6236. /**
  6237. * Sorting function for bound directives.
  6238. */
  6239. function byPriority(a, b) {
  6240. var diff = b.priority - a.priority;
  6241. if (diff !== 0) return diff;
  6242. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  6243. return a.index - b.index;
  6244. }
  6245. function assertNoDuplicate(what, previousDirective, directive, element) {
  6246. if (previousDirective) {
  6247. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  6248. previousDirective.name, directive.name, what, startingTag(element));
  6249. }
  6250. }
  6251. function addTextInterpolateDirective(directives, text) {
  6252. var interpolateFn = $interpolate(text, true);
  6253. if (interpolateFn) {
  6254. directives.push({
  6255. priority: 0,
  6256. compile: function textInterpolateCompileFn(templateNode) {
  6257. // when transcluding a template that has bindings in the root
  6258. // then we don't have a parent and should do this in the linkFn
  6259. var parent = templateNode.parent(), hasCompileParent = parent.length;
  6260. if (hasCompileParent) safeAddClass(templateNode.parent(), 'ng-binding');
  6261. return function textInterpolateLinkFn(scope, node) {
  6262. var parent = node.parent(),
  6263. bindings = parent.data('$binding') || [];
  6264. bindings.push(interpolateFn);
  6265. parent.data('$binding', bindings);
  6266. if (!hasCompileParent) safeAddClass(parent, 'ng-binding');
  6267. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  6268. node[0].nodeValue = value;
  6269. });
  6270. };
  6271. }
  6272. });
  6273. }
  6274. }
  6275. function getTrustedContext(node, attrNormalizedName) {
  6276. if (attrNormalizedName == "srcdoc") {
  6277. return $sce.HTML;
  6278. }
  6279. var tag = nodeName_(node);
  6280. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  6281. if (attrNormalizedName == "xlinkHref" ||
  6282. (tag == "FORM" && attrNormalizedName == "action") ||
  6283. (tag != "IMG" && (attrNormalizedName == "src" ||
  6284. attrNormalizedName == "ngSrc"))) {
  6285. return $sce.RESOURCE_URL;
  6286. }
  6287. }
  6288. function addAttrInterpolateDirective(node, directives, value, name) {
  6289. var interpolateFn = $interpolate(value, true);
  6290. // no interpolation found -> ignore
  6291. if (!interpolateFn) return;
  6292. if (name === "multiple" && nodeName_(node) === "SELECT") {
  6293. throw $compileMinErr("selmulti",
  6294. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  6295. startingTag(node));
  6296. }
  6297. directives.push({
  6298. priority: 100,
  6299. compile: function() {
  6300. return {
  6301. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  6302. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  6303. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  6304. throw $compileMinErr('nodomevents',
  6305. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  6306. "ng- versions (such as ng-click instead of onclick) instead.");
  6307. }
  6308. // we need to interpolate again, in case the attribute value has been updated
  6309. // (e.g. by another directive's compile function)
  6310. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
  6311. // if attribute was updated so that there is no interpolation going on we don't want to
  6312. // register any observers
  6313. if (!interpolateFn) return;
  6314. // TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
  6315. // actual attr value
  6316. attr[name] = interpolateFn(scope);
  6317. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  6318. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  6319. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  6320. //special case for class attribute addition + removal
  6321. //so that class changes can tap into the animation
  6322. //hooks provided by the $animate service. Be sure to
  6323. //skip animations when the first digest occurs (when
  6324. //both the new and the old values are the same) since
  6325. //the CSS classes are the non-interpolated values
  6326. if(name === 'class' && newValue != oldValue) {
  6327. attr.$updateClass(newValue, oldValue);
  6328. } else {
  6329. attr.$set(name, newValue);
  6330. }
  6331. });
  6332. }
  6333. };
  6334. }
  6335. });
  6336. }
  6337. /**
  6338. * This is a special jqLite.replaceWith, which can replace items which
  6339. * have no parents, provided that the containing jqLite collection is provided.
  6340. *
  6341. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  6342. * in the root of the tree.
  6343. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  6344. * the shell, but replace its DOM node reference.
  6345. * @param {Node} newNode The new DOM node.
  6346. */
  6347. function replaceWith($rootElement, elementsToRemove, newNode) {
  6348. var firstElementToRemove = elementsToRemove[0],
  6349. removeCount = elementsToRemove.length,
  6350. parent = firstElementToRemove.parentNode,
  6351. i, ii;
  6352. if ($rootElement) {
  6353. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  6354. if ($rootElement[i] == firstElementToRemove) {
  6355. $rootElement[i++] = newNode;
  6356. for (var j = i, j2 = j + removeCount - 1,
  6357. jj = $rootElement.length;
  6358. j < jj; j++, j2++) {
  6359. if (j2 < jj) {
  6360. $rootElement[j] = $rootElement[j2];
  6361. } else {
  6362. delete $rootElement[j];
  6363. }
  6364. }
  6365. $rootElement.length -= removeCount - 1;
  6366. break;
  6367. }
  6368. }
  6369. }
  6370. if (parent) {
  6371. parent.replaceChild(newNode, firstElementToRemove);
  6372. }
  6373. var fragment = document.createDocumentFragment();
  6374. fragment.appendChild(firstElementToRemove);
  6375. newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
  6376. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  6377. var element = elementsToRemove[k];
  6378. jqLite(element).remove(); // must do this way to clean up expando
  6379. fragment.appendChild(element);
  6380. delete elementsToRemove[k];
  6381. }
  6382. elementsToRemove[0] = newNode;
  6383. elementsToRemove.length = 1;
  6384. }
  6385. function cloneAndAnnotateFn(fn, annotation) {
  6386. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  6387. }
  6388. }];
  6389. }
  6390. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  6391. /**
  6392. * Converts all accepted directives format into proper directive name.
  6393. * All of these will become 'myDirective':
  6394. * my:Directive
  6395. * my-directive
  6396. * x-my-directive
  6397. * data-my:directive
  6398. *
  6399. * Also there is special case for Moz prefix starting with upper case letter.
  6400. * @param name Name to normalize
  6401. */
  6402. function directiveNormalize(name) {
  6403. return camelCase(name.replace(PREFIX_REGEXP, ''));
  6404. }
  6405. /**
  6406. * @ngdoc type
  6407. * @name $compile.directive.Attributes
  6408. *
  6409. * @description
  6410. * A shared object between directive compile / linking functions which contains normalized DOM
  6411. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  6412. * needed since all of these are treated as equivalent in Angular:
  6413. *
  6414. * ```
  6415. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  6416. * ```
  6417. */
  6418. /**
  6419. * @ngdoc property
  6420. * @name $compile.directive.Attributes#$attr
  6421. * @returns {object} A map of DOM element attribute names to the normalized name. This is
  6422. * needed to do reverse lookup from normalized name back to actual name.
  6423. */
  6424. /**
  6425. * @ngdoc method
  6426. * @name $compile.directive.Attributes#$set
  6427. * @kind function
  6428. *
  6429. * @description
  6430. * Set DOM element attribute value.
  6431. *
  6432. *
  6433. * @param {string} name Normalized element attribute name of the property to modify. The name is
  6434. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  6435. * property to the original name.
  6436. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  6437. */
  6438. /**
  6439. * Closure compiler type information
  6440. */
  6441. function nodesetLinkingFn(
  6442. /* angular.Scope */ scope,
  6443. /* NodeList */ nodeList,
  6444. /* Element */ rootElement,
  6445. /* function(Function) */ boundTranscludeFn
  6446. ){}
  6447. function directiveLinkingFn(
  6448. /* nodesetLinkingFn */ nodesetLinkingFn,
  6449. /* angular.Scope */ scope,
  6450. /* Node */ node,
  6451. /* Element */ rootElement,
  6452. /* function(Function) */ boundTranscludeFn
  6453. ){}
  6454. function tokenDifference(str1, str2) {
  6455. var values = '',
  6456. tokens1 = str1.split(/\s+/),
  6457. tokens2 = str2.split(/\s+/);
  6458. outer:
  6459. for(var i = 0; i < tokens1.length; i++) {
  6460. var token = tokens1[i];
  6461. for(var j = 0; j < tokens2.length; j++) {
  6462. if(token == tokens2[j]) continue outer;
  6463. }
  6464. values += (values.length > 0 ? ' ' : '') + token;
  6465. }
  6466. return values;
  6467. }
  6468. /**
  6469. * @ngdoc provider
  6470. * @name $controllerProvider
  6471. * @description
  6472. * The {@link ng.$controller $controller service} is used by Angular to create new
  6473. * controllers.
  6474. *
  6475. * This provider allows controller registration via the
  6476. * {@link ng.$controllerProvider#register register} method.
  6477. */
  6478. function $ControllerProvider() {
  6479. var controllers = {},
  6480. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  6481. /**
  6482. * @ngdoc method
  6483. * @name $controllerProvider#register
  6484. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  6485. * the names and the values are the constructors.
  6486. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  6487. * annotations in the array notation).
  6488. */
  6489. this.register = function(name, constructor) {
  6490. assertNotHasOwnProperty(name, 'controller');
  6491. if (isObject(name)) {
  6492. extend(controllers, name);
  6493. } else {
  6494. controllers[name] = constructor;
  6495. }
  6496. };
  6497. this.$get = ['$injector', '$window', function($injector, $window) {
  6498. /**
  6499. * @ngdoc service
  6500. * @name $controller
  6501. * @requires $injector
  6502. *
  6503. * @param {Function|string} constructor If called with a function then it's considered to be the
  6504. * controller constructor function. Otherwise it's considered to be a string which is used
  6505. * to retrieve the controller constructor using the following steps:
  6506. *
  6507. * * check if a controller with given name is registered via `$controllerProvider`
  6508. * * check if evaluating the string on the current scope returns a constructor
  6509. * * check `window[constructor]` on the global `window` object
  6510. *
  6511. * @param {Object} locals Injection locals for Controller.
  6512. * @return {Object} Instance of given controller.
  6513. *
  6514. * @description
  6515. * `$controller` service is responsible for instantiating controllers.
  6516. *
  6517. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  6518. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  6519. */
  6520. return function(expression, locals) {
  6521. var instance, match, constructor, identifier;
  6522. if(isString(expression)) {
  6523. match = expression.match(CNTRL_REG),
  6524. constructor = match[1],
  6525. identifier = match[3];
  6526. expression = controllers.hasOwnProperty(constructor)
  6527. ? controllers[constructor]
  6528. : getter(locals.$scope, constructor, true) || getter($window, constructor, true);
  6529. assertArgFn(expression, constructor, true);
  6530. }
  6531. instance = $injector.instantiate(expression, locals);
  6532. if (identifier) {
  6533. if (!(locals && typeof locals.$scope === 'object')) {
  6534. throw minErr('$controller')('noscp',
  6535. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  6536. constructor || expression.name, identifier);
  6537. }
  6538. locals.$scope[identifier] = instance;
  6539. }
  6540. return instance;
  6541. };
  6542. }];
  6543. }
  6544. /**
  6545. * @ngdoc service
  6546. * @name $document
  6547. * @requires $window
  6548. *
  6549. * @description
  6550. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  6551. *
  6552. * @example
  6553. <example module="documentExample">
  6554. <file name="index.html">
  6555. <div ng-controller="ExampleController">
  6556. <p>$document title: <b ng-bind="title"></b></p>
  6557. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  6558. </div>
  6559. </file>
  6560. <file name="script.js">
  6561. angular.module('documentExample', [])
  6562. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  6563. $scope.title = $document[0].title;
  6564. $scope.windowTitle = angular.element(window.document)[0].title;
  6565. }]);
  6566. </file>
  6567. </example>
  6568. */
  6569. function $DocumentProvider(){
  6570. this.$get = ['$window', function(window){
  6571. return jqLite(window.document);
  6572. }];
  6573. }
  6574. /**
  6575. * @ngdoc service
  6576. * @name $exceptionHandler
  6577. * @requires ng.$log
  6578. *
  6579. * @description
  6580. * Any uncaught exception in angular expressions is delegated to this service.
  6581. * The default implementation simply delegates to `$log.error` which logs it into
  6582. * the browser console.
  6583. *
  6584. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  6585. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  6586. *
  6587. * ## Example:
  6588. *
  6589. * ```js
  6590. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  6591. * return function (exception, cause) {
  6592. * exception.message += ' (caused by "' + cause + '")';
  6593. * throw exception;
  6594. * };
  6595. * });
  6596. * ```
  6597. *
  6598. * This example will override the normal action of `$exceptionHandler`, to make angular
  6599. * exceptions fail hard when they happen, instead of just logging to the console.
  6600. *
  6601. * @param {Error} exception Exception associated with the error.
  6602. * @param {string=} cause optional information about the context in which
  6603. * the error was thrown.
  6604. *
  6605. */
  6606. function $ExceptionHandlerProvider() {
  6607. this.$get = ['$log', function($log) {
  6608. return function(exception, cause) {
  6609. $log.error.apply($log, arguments);
  6610. };
  6611. }];
  6612. }
  6613. /**
  6614. * Parse headers into key value object
  6615. *
  6616. * @param {string} headers Raw headers as a string
  6617. * @returns {Object} Parsed headers as key value object
  6618. */
  6619. function parseHeaders(headers) {
  6620. var parsed = {}, key, val, i;
  6621. if (!headers) return parsed;
  6622. forEach(headers.split('\n'), function(line) {
  6623. i = line.indexOf(':');
  6624. key = lowercase(trim(line.substr(0, i)));
  6625. val = trim(line.substr(i + 1));
  6626. if (key) {
  6627. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  6628. }
  6629. });
  6630. return parsed;
  6631. }
  6632. /**
  6633. * Returns a function that provides access to parsed headers.
  6634. *
  6635. * Headers are lazy parsed when first requested.
  6636. * @see parseHeaders
  6637. *
  6638. * @param {(string|Object)} headers Headers to provide access to.
  6639. * @returns {function(string=)} Returns a getter function which if called with:
  6640. *
  6641. * - if called with single an argument returns a single header value or null
  6642. * - if called with no arguments returns an object containing all headers.
  6643. */
  6644. function headersGetter(headers) {
  6645. var headersObj = isObject(headers) ? headers : undefined;
  6646. return function(name) {
  6647. if (!headersObj) headersObj = parseHeaders(headers);
  6648. if (name) {
  6649. return headersObj[lowercase(name)] || null;
  6650. }
  6651. return headersObj;
  6652. };
  6653. }
  6654. /**
  6655. * Chain all given functions
  6656. *
  6657. * This function is used for both request and response transforming
  6658. *
  6659. * @param {*} data Data to transform.
  6660. * @param {function(string=)} headers Http headers getter fn.
  6661. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  6662. * @returns {*} Transformed data.
  6663. */
  6664. function transformData(data, headers, fns) {
  6665. if (isFunction(fns))
  6666. return fns(data, headers);
  6667. forEach(fns, function(fn) {
  6668. data = fn(data, headers);
  6669. });
  6670. return data;
  6671. }
  6672. function isSuccess(status) {
  6673. return 200 <= status && status < 300;
  6674. }
  6675. /**
  6676. * @ngdoc provider
  6677. * @name $httpProvider
  6678. * @description
  6679. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  6680. * */
  6681. function $HttpProvider() {
  6682. var JSON_START = /^\s*(\[|\{[^\{])/,
  6683. JSON_END = /[\}\]]\s*$/,
  6684. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  6685. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
  6686. /**
  6687. * @ngdoc property
  6688. * @name $httpProvider#defaults
  6689. * @description
  6690. *
  6691. * Object containing default values for all {@link ng.$http $http} requests.
  6692. *
  6693. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  6694. * Defaults value is `'XSRF-TOKEN'`.
  6695. *
  6696. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  6697. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  6698. *
  6699. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  6700. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  6701. * setting default headers.
  6702. * - **`defaults.headers.common`**
  6703. * - **`defaults.headers.post`**
  6704. * - **`defaults.headers.put`**
  6705. * - **`defaults.headers.patch`**
  6706. **/
  6707. var defaults = this.defaults = {
  6708. // transform incoming response data
  6709. transformResponse: [function(data) {
  6710. if (isString(data)) {
  6711. // strip json vulnerability protection prefix
  6712. data = data.replace(PROTECTION_PREFIX, '');
  6713. if (JSON_START.test(data) && JSON_END.test(data))
  6714. data = fromJson(data);
  6715. }
  6716. return data;
  6717. }],
  6718. // transform outgoing request data
  6719. transformRequest: [function(d) {
  6720. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  6721. }],
  6722. // default headers
  6723. headers: {
  6724. common: {
  6725. 'Accept': 'application/json, text/plain, */*'
  6726. },
  6727. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6728. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  6729. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  6730. },
  6731. xsrfCookieName: 'XSRF-TOKEN',
  6732. xsrfHeaderName: 'X-XSRF-TOKEN'
  6733. };
  6734. /**
  6735. * Are ordered by request, i.e. they are applied in the same order as the
  6736. * array, on request, but reverse order, on response.
  6737. */
  6738. var interceptorFactories = this.interceptors = [];
  6739. /**
  6740. * For historical reasons, response interceptors are ordered by the order in which
  6741. * they are applied to the response. (This is the opposite of interceptorFactories)
  6742. */
  6743. var responseInterceptorFactories = this.responseInterceptors = [];
  6744. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  6745. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  6746. var defaultCache = $cacheFactory('$http');
  6747. /**
  6748. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  6749. * The reversal is needed so that we can build up the interception chain around the
  6750. * server request.
  6751. */
  6752. var reversedInterceptors = [];
  6753. forEach(interceptorFactories, function(interceptorFactory) {
  6754. reversedInterceptors.unshift(isString(interceptorFactory)
  6755. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  6756. });
  6757. forEach(responseInterceptorFactories, function(interceptorFactory, index) {
  6758. var responseFn = isString(interceptorFactory)
  6759. ? $injector.get(interceptorFactory)
  6760. : $injector.invoke(interceptorFactory);
  6761. /**
  6762. * Response interceptors go before "around" interceptors (no real reason, just
  6763. * had to pick one.) But they are already reversed, so we can't use unshift, hence
  6764. * the splice.
  6765. */
  6766. reversedInterceptors.splice(index, 0, {
  6767. response: function(response) {
  6768. return responseFn($q.when(response));
  6769. },
  6770. responseError: function(response) {
  6771. return responseFn($q.reject(response));
  6772. }
  6773. });
  6774. });
  6775. /**
  6776. * @ngdoc service
  6777. * @kind function
  6778. * @name $http
  6779. * @requires ng.$httpBackend
  6780. * @requires $cacheFactory
  6781. * @requires $rootScope
  6782. * @requires $q
  6783. * @requires $injector
  6784. *
  6785. * @description
  6786. * The `$http` service is a core Angular service that facilitates communication with the remote
  6787. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  6788. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  6789. *
  6790. * For unit testing applications that use `$http` service, see
  6791. * {@link ngMock.$httpBackend $httpBackend mock}.
  6792. *
  6793. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  6794. * $resource} service.
  6795. *
  6796. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  6797. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  6798. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  6799. *
  6800. *
  6801. * # General usage
  6802. * The `$http` service is a function which takes a single argument — a configuration object —
  6803. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  6804. * with two $http specific methods: `success` and `error`.
  6805. *
  6806. * ```js
  6807. * $http({method: 'GET', url: '/someUrl'}).
  6808. * success(function(data, status, headers, config) {
  6809. * // this callback will be called asynchronously
  6810. * // when the response is available
  6811. * }).
  6812. * error(function(data, status, headers, config) {
  6813. * // called asynchronously if an error occurs
  6814. * // or server returns response with an error status.
  6815. * });
  6816. * ```
  6817. *
  6818. * Since the returned value of calling the $http function is a `promise`, you can also use
  6819. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  6820. * an object representing the response. See the API signature and type info below for more
  6821. * details.
  6822. *
  6823. * A response status code between 200 and 299 is considered a success status and
  6824. * will result in the success callback being called. Note that if the response is a redirect,
  6825. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  6826. * called for such responses.
  6827. *
  6828. * # Writing Unit Tests that use $http
  6829. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  6830. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  6831. * request using trained responses.
  6832. *
  6833. * ```
  6834. * $httpBackend.expectGET(...);
  6835. * $http.get(...);
  6836. * $httpBackend.flush();
  6837. * ```
  6838. *
  6839. * # Shortcut methods
  6840. *
  6841. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  6842. * request data must be passed in for POST/PUT requests.
  6843. *
  6844. * ```js
  6845. * $http.get('/someUrl').success(successCallback);
  6846. * $http.post('/someUrl', data).success(successCallback);
  6847. * ```
  6848. *
  6849. * Complete list of shortcut methods:
  6850. *
  6851. * - {@link ng.$http#get $http.get}
  6852. * - {@link ng.$http#head $http.head}
  6853. * - {@link ng.$http#post $http.post}
  6854. * - {@link ng.$http#put $http.put}
  6855. * - {@link ng.$http#delete $http.delete}
  6856. * - {@link ng.$http#jsonp $http.jsonp}
  6857. *
  6858. *
  6859. * # Setting HTTP Headers
  6860. *
  6861. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  6862. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  6863. * object, which currently contains this default configuration:
  6864. *
  6865. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  6866. * - `Accept: application/json, text/plain, * / *`
  6867. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  6868. * - `Content-Type: application/json`
  6869. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  6870. * - `Content-Type: application/json`
  6871. *
  6872. * To add or overwrite these defaults, simply add or remove a property from these configuration
  6873. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  6874. * with the lowercased HTTP method name as the key, e.g.
  6875. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  6876. *
  6877. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  6878. * fashion. For example:
  6879. *
  6880. * ```
  6881. * module.run(function($http) {
  6882. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  6883. * });
  6884. * ```
  6885. *
  6886. * In addition, you can supply a `headers` property in the config object passed when
  6887. * calling `$http(config)`, which overrides the defaults without changing them globally.
  6888. *
  6889. *
  6890. * # Transforming Requests and Responses
  6891. *
  6892. * Both requests and responses can be transformed using transform functions. By default, Angular
  6893. * applies these transformations:
  6894. *
  6895. * Request transformations:
  6896. *
  6897. * - If the `data` property of the request configuration object contains an object, serialize it
  6898. * into JSON format.
  6899. *
  6900. * Response transformations:
  6901. *
  6902. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  6903. * - If JSON response is detected, deserialize it using a JSON parser.
  6904. *
  6905. * To globally augment or override the default transforms, modify the
  6906. * `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
  6907. * properties. These properties are by default an array of transform functions, which allows you
  6908. * to `push` or `unshift` a new transformation function into the transformation chain. You can
  6909. * also decide to completely override any default transformations by assigning your
  6910. * transformation functions to these properties directly without the array wrapper. These defaults
  6911. * are again available on the $http factory at run-time, which may be useful if you have run-time
  6912. * services you wish to be involved in your transformations.
  6913. *
  6914. * Similarly, to locally override the request/response transforms, augment the
  6915. * `transformRequest` and/or `transformResponse` properties of the configuration object passed
  6916. * into `$http`.
  6917. *
  6918. *
  6919. * # Caching
  6920. *
  6921. * To enable caching, set the request configuration `cache` property to `true` (to use default
  6922. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  6923. * When the cache is enabled, `$http` stores the response from the server in the specified
  6924. * cache. The next time the same request is made, the response is served from the cache without
  6925. * sending a request to the server.
  6926. *
  6927. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  6928. * the same way that real requests are.
  6929. *
  6930. * If there are multiple GET requests for the same URL that should be cached using the same
  6931. * cache, but the cache is not populated yet, only one request to the server will be made and
  6932. * the remaining requests will be fulfilled using the response from the first request.
  6933. *
  6934. * You can change the default cache to a new object (built with
  6935. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  6936. * {@link ng.$http#properties_defaults `$http.defaults.cache`} property. All requests who set
  6937. * their `cache` property to `true` will now use this cache object.
  6938. *
  6939. * If you set the default cache to `false` then only requests that specify their own custom
  6940. * cache object will be cached.
  6941. *
  6942. * # Interceptors
  6943. *
  6944. * Before you start creating interceptors, be sure to understand the
  6945. * {@link ng.$q $q and deferred/promise APIs}.
  6946. *
  6947. * For purposes of global error handling, authentication, or any kind of synchronous or
  6948. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  6949. * able to intercept requests before they are handed to the server and
  6950. * responses before they are handed over to the application code that
  6951. * initiated these requests. The interceptors leverage the {@link ng.$q
  6952. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  6953. *
  6954. * The interceptors are service factories that are registered with the `$httpProvider` by
  6955. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  6956. * injected with dependencies (if specified) and returns the interceptor.
  6957. *
  6958. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  6959. *
  6960. * * `request`: interceptors get called with a http `config` object. The function is free to
  6961. * modify the `config` object or create a new one. The function needs to return the `config`
  6962. * object directly, or a promise containing the `config` or a new `config` object.
  6963. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  6964. * resolved with a rejection.
  6965. * * `response`: interceptors get called with http `response` object. The function is free to
  6966. * modify the `response` object or create a new one. The function needs to return the `response`
  6967. * object directly, or as a promise containing the `response` or a new `response` object.
  6968. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  6969. * resolved with a rejection.
  6970. *
  6971. *
  6972. * ```js
  6973. * // register the interceptor as a service
  6974. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  6975. * return {
  6976. * // optional method
  6977. * 'request': function(config) {
  6978. * // do something on success
  6979. * return config;
  6980. * },
  6981. *
  6982. * // optional method
  6983. * 'requestError': function(rejection) {
  6984. * // do something on error
  6985. * if (canRecover(rejection)) {
  6986. * return responseOrNewPromise
  6987. * }
  6988. * return $q.reject(rejection);
  6989. * },
  6990. *
  6991. *
  6992. *
  6993. * // optional method
  6994. * 'response': function(response) {
  6995. * // do something on success
  6996. * return response;
  6997. * },
  6998. *
  6999. * // optional method
  7000. * 'responseError': function(rejection) {
  7001. * // do something on error
  7002. * if (canRecover(rejection)) {
  7003. * return responseOrNewPromise
  7004. * }
  7005. * return $q.reject(rejection);
  7006. * }
  7007. * };
  7008. * });
  7009. *
  7010. * $httpProvider.interceptors.push('myHttpInterceptor');
  7011. *
  7012. *
  7013. * // alternatively, register the interceptor via an anonymous factory
  7014. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  7015. * return {
  7016. * 'request': function(config) {
  7017. * // same as above
  7018. * },
  7019. *
  7020. * 'response': function(response) {
  7021. * // same as above
  7022. * }
  7023. * };
  7024. * });
  7025. * ```
  7026. *
  7027. * # Response interceptors (DEPRECATED)
  7028. *
  7029. * Before you start creating interceptors, be sure to understand the
  7030. * {@link ng.$q $q and deferred/promise APIs}.
  7031. *
  7032. * For purposes of global error handling, authentication or any kind of synchronous or
  7033. * asynchronous preprocessing of received responses, it is desirable to be able to intercept
  7034. * responses for http requests before they are handed over to the application code that
  7035. * initiated these requests. The response interceptors leverage the {@link ng.$q
  7036. * promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
  7037. *
  7038. * The interceptors are service factories that are registered with the $httpProvider by
  7039. * adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
  7040. * injected with dependencies (if specified) and returns the interceptor — a function that
  7041. * takes a {@link ng.$q promise} and returns the original or a new promise.
  7042. *
  7043. * ```js
  7044. * // register the interceptor as a service
  7045. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  7046. * return function(promise) {
  7047. * return promise.then(function(response) {
  7048. * // do something on success
  7049. * return response;
  7050. * }, function(response) {
  7051. * // do something on error
  7052. * if (canRecover(response)) {
  7053. * return responseOrNewPromise
  7054. * }
  7055. * return $q.reject(response);
  7056. * });
  7057. * }
  7058. * });
  7059. *
  7060. * $httpProvider.responseInterceptors.push('myHttpInterceptor');
  7061. *
  7062. *
  7063. * // register the interceptor via an anonymous factory
  7064. * $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
  7065. * return function(promise) {
  7066. * // same as above
  7067. * }
  7068. * });
  7069. * ```
  7070. *
  7071. *
  7072. * # Security Considerations
  7073. *
  7074. * When designing web applications, consider security threats from:
  7075. *
  7076. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  7077. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  7078. *
  7079. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  7080. * pre-configured with strategies that address these issues, but for this to work backend server
  7081. * cooperation is required.
  7082. *
  7083. * ## JSON Vulnerability Protection
  7084. *
  7085. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  7086. * allows third party website to turn your JSON resource URL into
  7087. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  7088. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  7089. * Angular will automatically strip the prefix before processing it as JSON.
  7090. *
  7091. * For example if your server needs to return:
  7092. * ```js
  7093. * ['one','two']
  7094. * ```
  7095. *
  7096. * which is vulnerable to attack, your server can return:
  7097. * ```js
  7098. * )]}',
  7099. * ['one','two']
  7100. * ```
  7101. *
  7102. * Angular will strip the prefix, before processing the JSON.
  7103. *
  7104. *
  7105. * ## Cross Site Request Forgery (XSRF) Protection
  7106. *
  7107. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  7108. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  7109. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  7110. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  7111. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  7112. * the XHR came from JavaScript running on your domain. The header will not be set for
  7113. * cross-domain requests.
  7114. *
  7115. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  7116. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  7117. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  7118. * that only JavaScript running on your domain could have sent the request. The token must be
  7119. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  7120. * making up its own tokens). We recommend that the token is a digest of your site's
  7121. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography))
  7122. * for added security.
  7123. *
  7124. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  7125. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  7126. * or the per-request config object.
  7127. *
  7128. *
  7129. * @param {object} config Object describing the request to be made and how it should be
  7130. * processed. The object has following properties:
  7131. *
  7132. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  7133. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  7134. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  7135. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  7136. * JSONified.
  7137. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  7138. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  7139. * HTTP headers to send to the server. If the return value of a function is null, the
  7140. * header will not be sent.
  7141. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  7142. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  7143. * - **transformRequest** –
  7144. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7145. * transform function or an array of such functions. The transform function takes the http
  7146. * request body and headers and returns its transformed (typically serialized) version.
  7147. * - **transformResponse** –
  7148. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  7149. * transform function or an array of such functions. The transform function takes the http
  7150. * response body and headers and returns its transformed (typically deserialized) version.
  7151. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  7152. * GET request, otherwise if a cache instance built with
  7153. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  7154. * caching.
  7155. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  7156. * that should abort the request when resolved.
  7157. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  7158. * XHR object. See [requests with credentials]https://developer.mozilla.org/en/http_access_control#section_5
  7159. * for more information.
  7160. * - **responseType** - `{string}` - see
  7161. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  7162. *
  7163. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  7164. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  7165. * method takes two arguments a success and an error callback which will be called with a
  7166. * response object. The `success` and `error` methods take a single argument - a function that
  7167. * will be called when the request succeeds or fails respectively. The arguments passed into
  7168. * these functions are destructured representation of the response object passed into the
  7169. * `then` method. The response object has these properties:
  7170. *
  7171. * - **data** – `{string|Object}` – The response body transformed with the transform
  7172. * functions.
  7173. * - **status** – `{number}` – HTTP status code of the response.
  7174. * - **headers** – `{function([headerName])}` – Header getter function.
  7175. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  7176. * - **statusText** – `{string}` – HTTP status text of the response.
  7177. *
  7178. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  7179. * requests. This is primarily meant to be used for debugging purposes.
  7180. *
  7181. *
  7182. * @example
  7183. <example module="httpExample">
  7184. <file name="index.html">
  7185. <div ng-controller="FetchController">
  7186. <select ng-model="method">
  7187. <option>GET</option>
  7188. <option>JSONP</option>
  7189. </select>
  7190. <input type="text" ng-model="url" size="80"/>
  7191. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  7192. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  7193. <button id="samplejsonpbtn"
  7194. ng-click="updateModel('JSONP',
  7195. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  7196. Sample JSONP
  7197. </button>
  7198. <button id="invalidjsonpbtn"
  7199. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  7200. Invalid JSONP
  7201. </button>
  7202. <pre>http status code: {{status}}</pre>
  7203. <pre>http response data: {{data}}</pre>
  7204. </div>
  7205. </file>
  7206. <file name="script.js">
  7207. angular.module('httpExample', [])
  7208. .controller('FetchController', ['$scope', '$http', '$templateCache',
  7209. function($scope, $http, $templateCache) {
  7210. $scope.method = 'GET';
  7211. $scope.url = 'http-hello.html';
  7212. $scope.fetch = function() {
  7213. $scope.code = null;
  7214. $scope.response = null;
  7215. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  7216. success(function(data, status) {
  7217. $scope.status = status;
  7218. $scope.data = data;
  7219. }).
  7220. error(function(data, status) {
  7221. $scope.data = data || "Request failed";
  7222. $scope.status = status;
  7223. });
  7224. };
  7225. $scope.updateModel = function(method, url) {
  7226. $scope.method = method;
  7227. $scope.url = url;
  7228. };
  7229. }]);
  7230. </file>
  7231. <file name="http-hello.html">
  7232. Hello, $http!
  7233. </file>
  7234. <file name="protractor.js" type="protractor">
  7235. var status = element(by.binding('status'));
  7236. var data = element(by.binding('data'));
  7237. var fetchBtn = element(by.id('fetchbtn'));
  7238. var sampleGetBtn = element(by.id('samplegetbtn'));
  7239. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  7240. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  7241. it('should make an xhr GET request', function() {
  7242. sampleGetBtn.click();
  7243. fetchBtn.click();
  7244. expect(status.getText()).toMatch('200');
  7245. expect(data.getText()).toMatch(/Hello, \$http!/);
  7246. });
  7247. it('should make a JSONP request to angularjs.org', function() {
  7248. sampleJsonpBtn.click();
  7249. fetchBtn.click();
  7250. expect(status.getText()).toMatch('200');
  7251. expect(data.getText()).toMatch(/Super Hero!/);
  7252. });
  7253. it('should make JSONP request to invalid URL and invoke the error handler',
  7254. function() {
  7255. invalidJsonpBtn.click();
  7256. fetchBtn.click();
  7257. expect(status.getText()).toMatch('0');
  7258. expect(data.getText()).toMatch('Request failed');
  7259. });
  7260. </file>
  7261. </example>
  7262. */
  7263. function $http(requestConfig) {
  7264. var config = {
  7265. method: 'get',
  7266. transformRequest: defaults.transformRequest,
  7267. transformResponse: defaults.transformResponse
  7268. };
  7269. var headers = mergeHeaders(requestConfig);
  7270. extend(config, requestConfig);
  7271. config.headers = headers;
  7272. config.method = uppercase(config.method);
  7273. var serverRequest = function(config) {
  7274. headers = config.headers;
  7275. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  7276. // strip content-type if data is undefined
  7277. if (isUndefined(reqData)) {
  7278. forEach(headers, function(value, header) {
  7279. if (lowercase(header) === 'content-type') {
  7280. delete headers[header];
  7281. }
  7282. });
  7283. }
  7284. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  7285. config.withCredentials = defaults.withCredentials;
  7286. }
  7287. // send request
  7288. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  7289. };
  7290. var chain = [serverRequest, undefined];
  7291. var promise = $q.when(config);
  7292. // apply interceptors
  7293. forEach(reversedInterceptors, function(interceptor) {
  7294. if (interceptor.request || interceptor.requestError) {
  7295. chain.unshift(interceptor.request, interceptor.requestError);
  7296. }
  7297. if (interceptor.response || interceptor.responseError) {
  7298. chain.push(interceptor.response, interceptor.responseError);
  7299. }
  7300. });
  7301. while(chain.length) {
  7302. var thenFn = chain.shift();
  7303. var rejectFn = chain.shift();
  7304. promise = promise.then(thenFn, rejectFn);
  7305. }
  7306. promise.success = function(fn) {
  7307. promise.then(function(response) {
  7308. fn(response.data, response.status, response.headers, config);
  7309. });
  7310. return promise;
  7311. };
  7312. promise.error = function(fn) {
  7313. promise.then(null, function(response) {
  7314. fn(response.data, response.status, response.headers, config);
  7315. });
  7316. return promise;
  7317. };
  7318. return promise;
  7319. function transformResponse(response) {
  7320. // make a copy since the response must be cacheable
  7321. var resp = extend({}, response, {
  7322. data: transformData(response.data, response.headers, config.transformResponse)
  7323. });
  7324. return (isSuccess(response.status))
  7325. ? resp
  7326. : $q.reject(resp);
  7327. }
  7328. function mergeHeaders(config) {
  7329. var defHeaders = defaults.headers,
  7330. reqHeaders = extend({}, config.headers),
  7331. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  7332. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  7333. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  7334. defaultHeadersIteration:
  7335. for (defHeaderName in defHeaders) {
  7336. lowercaseDefHeaderName = lowercase(defHeaderName);
  7337. for (reqHeaderName in reqHeaders) {
  7338. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  7339. continue defaultHeadersIteration;
  7340. }
  7341. }
  7342. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  7343. }
  7344. // execute if header value is a function for merged headers
  7345. execHeaders(reqHeaders);
  7346. return reqHeaders;
  7347. function execHeaders(headers) {
  7348. var headerContent;
  7349. forEach(headers, function(headerFn, header) {
  7350. if (isFunction(headerFn)) {
  7351. headerContent = headerFn();
  7352. if (headerContent != null) {
  7353. headers[header] = headerContent;
  7354. } else {
  7355. delete headers[header];
  7356. }
  7357. }
  7358. });
  7359. }
  7360. }
  7361. }
  7362. $http.pendingRequests = [];
  7363. /**
  7364. * @ngdoc method
  7365. * @name $http#get
  7366. *
  7367. * @description
  7368. * Shortcut method to perform `GET` request.
  7369. *
  7370. * @param {string} url Relative or absolute URL specifying the destination of the request
  7371. * @param {Object=} config Optional configuration object
  7372. * @returns {HttpPromise} Future object
  7373. */
  7374. /**
  7375. * @ngdoc method
  7376. * @name $http#delete
  7377. *
  7378. * @description
  7379. * Shortcut method to perform `DELETE` request.
  7380. *
  7381. * @param {string} url Relative or absolute URL specifying the destination of the request
  7382. * @param {Object=} config Optional configuration object
  7383. * @returns {HttpPromise} Future object
  7384. */
  7385. /**
  7386. * @ngdoc method
  7387. * @name $http#head
  7388. *
  7389. * @description
  7390. * Shortcut method to perform `HEAD` request.
  7391. *
  7392. * @param {string} url Relative or absolute URL specifying the destination of the request
  7393. * @param {Object=} config Optional configuration object
  7394. * @returns {HttpPromise} Future object
  7395. */
  7396. /**
  7397. * @ngdoc method
  7398. * @name $http#jsonp
  7399. *
  7400. * @description
  7401. * Shortcut method to perform `JSONP` request.
  7402. *
  7403. * @param {string} url Relative or absolute URL specifying the destination of the request.
  7404. * The name of the callback should be the string `JSON_CALLBACK`.
  7405. * @param {Object=} config Optional configuration object
  7406. * @returns {HttpPromise} Future object
  7407. */
  7408. createShortMethods('get', 'delete', 'head', 'jsonp');
  7409. /**
  7410. * @ngdoc method
  7411. * @name $http#post
  7412. *
  7413. * @description
  7414. * Shortcut method to perform `POST` request.
  7415. *
  7416. * @param {string} url Relative or absolute URL specifying the destination of the request
  7417. * @param {*} data Request content
  7418. * @param {Object=} config Optional configuration object
  7419. * @returns {HttpPromise} Future object
  7420. */
  7421. /**
  7422. * @ngdoc method
  7423. * @name $http#put
  7424. *
  7425. * @description
  7426. * Shortcut method to perform `PUT` request.
  7427. *
  7428. * @param {string} url Relative or absolute URL specifying the destination of the request
  7429. * @param {*} data Request content
  7430. * @param {Object=} config Optional configuration object
  7431. * @returns {HttpPromise} Future object
  7432. */
  7433. createShortMethodsWithData('post', 'put');
  7434. /**
  7435. * @ngdoc property
  7436. * @name $http#defaults
  7437. *
  7438. * @description
  7439. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  7440. * default headers, withCredentials as well as request and response transformations.
  7441. *
  7442. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  7443. */
  7444. $http.defaults = defaults;
  7445. return $http;
  7446. function createShortMethods(names) {
  7447. forEach(arguments, function(name) {
  7448. $http[name] = function(url, config) {
  7449. return $http(extend(config || {}, {
  7450. method: name,
  7451. url: url
  7452. }));
  7453. };
  7454. });
  7455. }
  7456. function createShortMethodsWithData(name) {
  7457. forEach(arguments, function(name) {
  7458. $http[name] = function(url, data, config) {
  7459. return $http(extend(config || {}, {
  7460. method: name,
  7461. url: url,
  7462. data: data
  7463. }));
  7464. };
  7465. });
  7466. }
  7467. /**
  7468. * Makes the request.
  7469. *
  7470. * !!! ACCESSES CLOSURE VARS:
  7471. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  7472. */
  7473. function sendReq(config, reqData, reqHeaders) {
  7474. var deferred = $q.defer(),
  7475. promise = deferred.promise,
  7476. cache,
  7477. cachedResp,
  7478. url = buildUrl(config.url, config.params);
  7479. $http.pendingRequests.push(config);
  7480. promise.then(removePendingReq, removePendingReq);
  7481. if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
  7482. cache = isObject(config.cache) ? config.cache
  7483. : isObject(defaults.cache) ? defaults.cache
  7484. : defaultCache;
  7485. }
  7486. if (cache) {
  7487. cachedResp = cache.get(url);
  7488. if (isDefined(cachedResp)) {
  7489. if (isPromiseLike(cachedResp)) {
  7490. // cached request has already been sent, but there is no response yet
  7491. cachedResp.then(removePendingReq, removePendingReq);
  7492. return cachedResp;
  7493. } else {
  7494. // serving from cache
  7495. if (isArray(cachedResp)) {
  7496. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  7497. } else {
  7498. resolvePromise(cachedResp, 200, {}, 'OK');
  7499. }
  7500. }
  7501. } else {
  7502. // put the promise for the non-transformed response into cache as a placeholder
  7503. cache.put(url, promise);
  7504. }
  7505. }
  7506. // if we won't have the response in cache, set the xsrf headers and
  7507. // send the request to the backend
  7508. if (isUndefined(cachedResp)) {
  7509. var xsrfValue = urlIsSameOrigin(config.url)
  7510. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  7511. : undefined;
  7512. if (xsrfValue) {
  7513. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  7514. }
  7515. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  7516. config.withCredentials, config.responseType);
  7517. }
  7518. return promise;
  7519. /**
  7520. * Callback registered to $httpBackend():
  7521. * - caches the response if desired
  7522. * - resolves the raw $http promise
  7523. * - calls $apply
  7524. */
  7525. function done(status, response, headersString, statusText) {
  7526. if (cache) {
  7527. if (isSuccess(status)) {
  7528. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  7529. } else {
  7530. // remove promise from the cache
  7531. cache.remove(url);
  7532. }
  7533. }
  7534. resolvePromise(response, status, headersString, statusText);
  7535. if (!$rootScope.$$phase) $rootScope.$apply();
  7536. }
  7537. /**
  7538. * Resolves the raw $http promise.
  7539. */
  7540. function resolvePromise(response, status, headers, statusText) {
  7541. // normalize internal statuses to 0
  7542. status = Math.max(status, 0);
  7543. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  7544. data: response,
  7545. status: status,
  7546. headers: headersGetter(headers),
  7547. config: config,
  7548. statusText : statusText
  7549. });
  7550. }
  7551. function removePendingReq() {
  7552. var idx = indexOf($http.pendingRequests, config);
  7553. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  7554. }
  7555. }
  7556. function buildUrl(url, params) {
  7557. if (!params) return url;
  7558. var parts = [];
  7559. forEachSorted(params, function(value, key) {
  7560. if (value === null || isUndefined(value)) return;
  7561. if (!isArray(value)) value = [value];
  7562. forEach(value, function(v) {
  7563. if (isObject(v)) {
  7564. if (isDate(v)){
  7565. v = v.toISOString();
  7566. } else if (isObject(v)) {
  7567. v = toJson(v);
  7568. }
  7569. }
  7570. parts.push(encodeUriQuery(key) + '=' +
  7571. encodeUriQuery(v));
  7572. });
  7573. });
  7574. if(parts.length > 0) {
  7575. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  7576. }
  7577. return url;
  7578. }
  7579. }];
  7580. }
  7581. function createXhr(method) {
  7582. //if IE and the method is not RFC2616 compliant, or if XMLHttpRequest
  7583. //is not available, try getting an ActiveXObject. Otherwise, use XMLHttpRequest
  7584. //if it is available
  7585. if (msie <= 8 && (!method.match(/^(get|post|head|put|delete|options)$/i) ||
  7586. !window.XMLHttpRequest)) {
  7587. return new window.ActiveXObject("Microsoft.XMLHTTP");
  7588. } else if (window.XMLHttpRequest) {
  7589. return new window.XMLHttpRequest();
  7590. }
  7591. throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
  7592. }
  7593. /**
  7594. * @ngdoc service
  7595. * @name $httpBackend
  7596. * @requires $window
  7597. * @requires $document
  7598. *
  7599. * @description
  7600. * HTTP backend used by the {@link ng.$http service} that delegates to
  7601. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  7602. *
  7603. * You should never need to use this service directly, instead use the higher-level abstractions:
  7604. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  7605. *
  7606. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  7607. * $httpBackend} which can be trained with responses.
  7608. */
  7609. function $HttpBackendProvider() {
  7610. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  7611. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  7612. }];
  7613. }
  7614. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  7615. var ABORTED = -1;
  7616. // TODO(vojta): fix the signature
  7617. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  7618. var status;
  7619. $browser.$$incOutstandingRequestCount();
  7620. url = url || $browser.url();
  7621. if (lowercase(method) == 'jsonp') {
  7622. var callbackId = '_' + (callbacks.counter++).toString(36);
  7623. callbacks[callbackId] = function(data) {
  7624. callbacks[callbackId].data = data;
  7625. callbacks[callbackId].called = true;
  7626. };
  7627. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  7628. callbackId, function(status, text) {
  7629. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  7630. callbacks[callbackId] = noop;
  7631. });
  7632. } else {
  7633. var xhr = createXhr(method);
  7634. xhr.open(method, url, true);
  7635. forEach(headers, function(value, key) {
  7636. if (isDefined(value)) {
  7637. xhr.setRequestHeader(key, value);
  7638. }
  7639. });
  7640. // In IE6 and 7, this might be called synchronously when xhr.send below is called and the
  7641. // response is in the cache. the promise api will ensure that to the app code the api is
  7642. // always async
  7643. xhr.onreadystatechange = function() {
  7644. // onreadystatechange might get called multiple times with readyState === 4 on mobile webkit caused by
  7645. // xhrs that are resolved while the app is in the background (see #5426).
  7646. // since calling completeRequest sets the `xhr` variable to null, we just check if it's not null before
  7647. // continuing
  7648. //
  7649. // we can't set xhr.onreadystatechange to undefined or delete it because that breaks IE8 (method=PATCH) and
  7650. // Safari respectively.
  7651. if (xhr && xhr.readyState == 4) {
  7652. var responseHeaders = null,
  7653. response = null,
  7654. statusText = '';
  7655. if(status !== ABORTED) {
  7656. responseHeaders = xhr.getAllResponseHeaders();
  7657. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  7658. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  7659. response = ('response' in xhr) ? xhr.response : xhr.responseText;
  7660. }
  7661. // Accessing statusText on an aborted xhr object will
  7662. // throw an 'c00c023f error' in IE9 and lower, don't touch it.
  7663. if (!(status === ABORTED && msie < 10)) {
  7664. statusText = xhr.statusText;
  7665. }
  7666. completeRequest(callback,
  7667. status || xhr.status,
  7668. response,
  7669. responseHeaders,
  7670. statusText);
  7671. }
  7672. };
  7673. if (withCredentials) {
  7674. xhr.withCredentials = true;
  7675. }
  7676. if (responseType) {
  7677. try {
  7678. xhr.responseType = responseType;
  7679. } catch (e) {
  7680. // WebKit added support for the json responseType value on 09/03/2013
  7681. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  7682. // known to throw when setting the value "json" as the response type. Other older
  7683. // browsers implementing the responseType
  7684. //
  7685. // The json response type can be ignored if not supported, because JSON payloads are
  7686. // parsed on the client-side regardless.
  7687. if (responseType !== 'json') {
  7688. throw e;
  7689. }
  7690. }
  7691. }
  7692. xhr.send(post || null);
  7693. }
  7694. if (timeout > 0) {
  7695. var timeoutId = $browserDefer(timeoutRequest, timeout);
  7696. } else if (isPromiseLike(timeout)) {
  7697. timeout.then(timeoutRequest);
  7698. }
  7699. function timeoutRequest() {
  7700. status = ABORTED;
  7701. jsonpDone && jsonpDone();
  7702. xhr && xhr.abort();
  7703. }
  7704. function completeRequest(callback, status, response, headersString, statusText) {
  7705. // cancel timeout and subsequent timeout promise resolution
  7706. timeoutId && $browserDefer.cancel(timeoutId);
  7707. jsonpDone = xhr = null;
  7708. // fix status code when it is 0 (0 status is undocumented).
  7709. // Occurs when accessing file resources or on Android 4.1 stock browser
  7710. // while retrieving files from application cache.
  7711. if (status === 0) {
  7712. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  7713. }
  7714. // normalize IE bug (http://bugs.jquery.com/ticket/1450)
  7715. status = status === 1223 ? 204 : status;
  7716. statusText = statusText || '';
  7717. callback(status, response, headersString, statusText);
  7718. $browser.$$completeOutstandingRequest(noop);
  7719. }
  7720. };
  7721. function jsonpReq(url, callbackId, done) {
  7722. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  7723. // - fetches local scripts via XHR and evals them
  7724. // - adds and immediately removes script elements from the document
  7725. var script = rawDocument.createElement('script'), callback = null;
  7726. script.type = "text/javascript";
  7727. script.src = url;
  7728. script.async = true;
  7729. callback = function(event) {
  7730. removeEventListenerFn(script, "load", callback);
  7731. removeEventListenerFn(script, "error", callback);
  7732. rawDocument.body.removeChild(script);
  7733. script = null;
  7734. var status = -1;
  7735. var text = "unknown";
  7736. if (event) {
  7737. if (event.type === "load" && !callbacks[callbackId].called) {
  7738. event = { type: "error" };
  7739. }
  7740. text = event.type;
  7741. status = event.type === "error" ? 404 : 200;
  7742. }
  7743. if (done) {
  7744. done(status, text);
  7745. }
  7746. };
  7747. addEventListenerFn(script, "load", callback);
  7748. addEventListenerFn(script, "error", callback);
  7749. if (msie <= 8) {
  7750. script.onreadystatechange = function() {
  7751. if (isString(script.readyState) && /loaded|complete/.test(script.readyState)) {
  7752. script.onreadystatechange = null;
  7753. callback({
  7754. type: 'load'
  7755. });
  7756. }
  7757. };
  7758. }
  7759. rawDocument.body.appendChild(script);
  7760. return callback;
  7761. }
  7762. }
  7763. var $interpolateMinErr = minErr('$interpolate');
  7764. /**
  7765. * @ngdoc provider
  7766. * @name $interpolateProvider
  7767. * @kind function
  7768. *
  7769. * @description
  7770. *
  7771. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  7772. *
  7773. * @example
  7774. <example module="customInterpolationApp">
  7775. <file name="index.html">
  7776. <script>
  7777. var customInterpolationApp = angular.module('customInterpolationApp', []);
  7778. customInterpolationApp.config(function($interpolateProvider) {
  7779. $interpolateProvider.startSymbol('//');
  7780. $interpolateProvider.endSymbol('//');
  7781. });
  7782. customInterpolationApp.controller('DemoController', function() {
  7783. this.label = "This binding is brought you by // interpolation symbols.";
  7784. });
  7785. </script>
  7786. <div ng-app="App" ng-controller="DemoController as demo">
  7787. //demo.label//
  7788. </div>
  7789. </file>
  7790. <file name="protractor.js" type="protractor">
  7791. it('should interpolate binding with custom symbols', function() {
  7792. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  7793. });
  7794. </file>
  7795. </example>
  7796. */
  7797. function $InterpolateProvider() {
  7798. var startSymbol = '{{';
  7799. var endSymbol = '}}';
  7800. /**
  7801. * @ngdoc method
  7802. * @name $interpolateProvider#startSymbol
  7803. * @description
  7804. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  7805. *
  7806. * @param {string=} value new value to set the starting symbol to.
  7807. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7808. */
  7809. this.startSymbol = function(value){
  7810. if (value) {
  7811. startSymbol = value;
  7812. return this;
  7813. } else {
  7814. return startSymbol;
  7815. }
  7816. };
  7817. /**
  7818. * @ngdoc method
  7819. * @name $interpolateProvider#endSymbol
  7820. * @description
  7821. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7822. *
  7823. * @param {string=} value new value to set the ending symbol to.
  7824. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  7825. */
  7826. this.endSymbol = function(value){
  7827. if (value) {
  7828. endSymbol = value;
  7829. return this;
  7830. } else {
  7831. return endSymbol;
  7832. }
  7833. };
  7834. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  7835. var startSymbolLength = startSymbol.length,
  7836. endSymbolLength = endSymbol.length;
  7837. /**
  7838. * @ngdoc service
  7839. * @name $interpolate
  7840. * @kind function
  7841. *
  7842. * @requires $parse
  7843. * @requires $sce
  7844. *
  7845. * @description
  7846. *
  7847. * Compiles a string with markup into an interpolation function. This service is used by the
  7848. * HTML {@link ng.$compile $compile} service for data binding. See
  7849. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  7850. * interpolation markup.
  7851. *
  7852. *
  7853. * ```js
  7854. * var $interpolate = ...; // injected
  7855. * var exp = $interpolate('Hello {{name | uppercase}}!');
  7856. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  7857. * ```
  7858. *
  7859. *
  7860. * @param {string} text The text with markup to interpolate.
  7861. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  7862. * embedded expression in order to return an interpolation function. Strings with no
  7863. * embedded expression will return null for the interpolation function.
  7864. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  7865. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  7866. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  7867. * provides Strict Contextual Escaping for details.
  7868. * @returns {function(context)} an interpolation function which is used to compute the
  7869. * interpolated string. The function has these parameters:
  7870. *
  7871. * * `context`: an object against which any expressions embedded in the strings are evaluated
  7872. * against.
  7873. *
  7874. */
  7875. function $interpolate(text, mustHaveExpression, trustedContext) {
  7876. var startIndex,
  7877. endIndex,
  7878. index = 0,
  7879. parts = [],
  7880. length = text.length,
  7881. hasInterpolation = false,
  7882. fn,
  7883. exp,
  7884. concat = [];
  7885. while(index < length) {
  7886. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  7887. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  7888. (index != startIndex) && parts.push(text.substring(index, startIndex));
  7889. parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
  7890. fn.exp = exp;
  7891. index = endIndex + endSymbolLength;
  7892. hasInterpolation = true;
  7893. } else {
  7894. // we did not find anything, so we have to add the remainder to the parts array
  7895. (index != length) && parts.push(text.substring(index));
  7896. index = length;
  7897. }
  7898. }
  7899. if (!(length = parts.length)) {
  7900. // we added, nothing, must have been an empty string.
  7901. parts.push('');
  7902. length = 1;
  7903. }
  7904. // Concatenating expressions makes it hard to reason about whether some combination of
  7905. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  7906. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  7907. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  7908. // make it obvious that you bound the value to some user controlled value. This helps reduce
  7909. // the load when auditing for XSS issues.
  7910. if (trustedContext && parts.length > 1) {
  7911. throw $interpolateMinErr('noconcat',
  7912. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  7913. "interpolations that concatenate multiple expressions when a trusted value is " +
  7914. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  7915. }
  7916. if (!mustHaveExpression || hasInterpolation) {
  7917. concat.length = length;
  7918. fn = function(context) {
  7919. try {
  7920. for(var i = 0, ii = length, part; i<ii; i++) {
  7921. if (typeof (part = parts[i]) == 'function') {
  7922. part = part(context);
  7923. if (trustedContext) {
  7924. part = $sce.getTrusted(trustedContext, part);
  7925. } else {
  7926. part = $sce.valueOf(part);
  7927. }
  7928. if (part == null) { // null || undefined
  7929. part = '';
  7930. } else {
  7931. switch (typeof part) {
  7932. case 'string':
  7933. {
  7934. break;
  7935. }
  7936. case 'number':
  7937. {
  7938. part = '' + part;
  7939. break;
  7940. }
  7941. default:
  7942. {
  7943. part = toJson(part);
  7944. }
  7945. }
  7946. }
  7947. }
  7948. concat[i] = part;
  7949. }
  7950. return concat.join('');
  7951. }
  7952. catch(err) {
  7953. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  7954. err.toString());
  7955. $exceptionHandler(newErr);
  7956. }
  7957. };
  7958. fn.exp = text;
  7959. fn.parts = parts;
  7960. return fn;
  7961. }
  7962. }
  7963. /**
  7964. * @ngdoc method
  7965. * @name $interpolate#startSymbol
  7966. * @description
  7967. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  7968. *
  7969. * Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
  7970. * the symbol.
  7971. *
  7972. * @returns {string} start symbol.
  7973. */
  7974. $interpolate.startSymbol = function() {
  7975. return startSymbol;
  7976. };
  7977. /**
  7978. * @ngdoc method
  7979. * @name $interpolate#endSymbol
  7980. * @description
  7981. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  7982. *
  7983. * Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
  7984. * the symbol.
  7985. *
  7986. * @returns {string} end symbol.
  7987. */
  7988. $interpolate.endSymbol = function() {
  7989. return endSymbol;
  7990. };
  7991. return $interpolate;
  7992. }];
  7993. }
  7994. function $IntervalProvider() {
  7995. this.$get = ['$rootScope', '$window', '$q',
  7996. function($rootScope, $window, $q) {
  7997. var intervals = {};
  7998. /**
  7999. * @ngdoc service
  8000. * @name $interval
  8001. *
  8002. * @description
  8003. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  8004. * milliseconds.
  8005. *
  8006. * The return value of registering an interval function is a promise. This promise will be
  8007. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  8008. * run indefinitely if `count` is not defined. The value of the notification will be the
  8009. * number of iterations that have run.
  8010. * To cancel an interval, call `$interval.cancel(promise)`.
  8011. *
  8012. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  8013. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  8014. * time.
  8015. *
  8016. * <div class="alert alert-warning">
  8017. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  8018. * with them. In particular they are not automatically destroyed when a controller's scope or a
  8019. * directive's element are destroyed.
  8020. * You should take this into consideration and make sure to always cancel the interval at the
  8021. * appropriate moment. See the example below for more details on how and when to do this.
  8022. * </div>
  8023. *
  8024. * @param {function()} fn A function that should be called repeatedly.
  8025. * @param {number} delay Number of milliseconds between each function call.
  8026. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  8027. * indefinitely.
  8028. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  8029. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  8030. * @returns {promise} A promise which will be notified on each iteration.
  8031. *
  8032. * @example
  8033. * <example module="intervalExample">
  8034. * <file name="index.html">
  8035. * <script>
  8036. * angular.module('intervalExample', [])
  8037. * .controller('ExampleController', ['$scope', '$interval',
  8038. * function($scope, $interval) {
  8039. * $scope.format = 'M/d/yy h:mm:ss a';
  8040. * $scope.blood_1 = 100;
  8041. * $scope.blood_2 = 120;
  8042. *
  8043. * var stop;
  8044. * $scope.fight = function() {
  8045. * // Don't start a new fight if we are already fighting
  8046. * if ( angular.isDefined(stop) ) return;
  8047. *
  8048. * stop = $interval(function() {
  8049. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  8050. * $scope.blood_1 = $scope.blood_1 - 3;
  8051. * $scope.blood_2 = $scope.blood_2 - 4;
  8052. * } else {
  8053. * $scope.stopFight();
  8054. * }
  8055. * }, 100);
  8056. * };
  8057. *
  8058. * $scope.stopFight = function() {
  8059. * if (angular.isDefined(stop)) {
  8060. * $interval.cancel(stop);
  8061. * stop = undefined;
  8062. * }
  8063. * };
  8064. *
  8065. * $scope.resetFight = function() {
  8066. * $scope.blood_1 = 100;
  8067. * $scope.blood_2 = 120;
  8068. * };
  8069. *
  8070. * $scope.$on('$destroy', function() {
  8071. * // Make sure that the interval nis destroyed too
  8072. * $scope.stopFight();
  8073. * });
  8074. * }])
  8075. * // Register the 'myCurrentTime' directive factory method.
  8076. * // We inject $interval and dateFilter service since the factory method is DI.
  8077. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  8078. * function($interval, dateFilter) {
  8079. * // return the directive link function. (compile function not needed)
  8080. * return function(scope, element, attrs) {
  8081. * var format, // date format
  8082. * stopTime; // so that we can cancel the time updates
  8083. *
  8084. * // used to update the UI
  8085. * function updateTime() {
  8086. * element.text(dateFilter(new Date(), format));
  8087. * }
  8088. *
  8089. * // watch the expression, and update the UI on change.
  8090. * scope.$watch(attrs.myCurrentTime, function(value) {
  8091. * format = value;
  8092. * updateTime();
  8093. * });
  8094. *
  8095. * stopTime = $interval(updateTime, 1000);
  8096. *
  8097. * // listen on DOM destroy (removal) event, and cancel the next UI update
  8098. * // to prevent updating time after the DOM element was removed.
  8099. * element.bind('$destroy', function() {
  8100. * $interval.cancel(stopTime);
  8101. * });
  8102. * }
  8103. * }]);
  8104. * </script>
  8105. *
  8106. * <div>
  8107. * <div ng-controller="ExampleController">
  8108. * Date format: <input ng-model="format"> <hr/>
  8109. * Current time is: <span my-current-time="format"></span>
  8110. * <hr/>
  8111. * Blood 1 : <font color='red'>{{blood_1}}</font>
  8112. * Blood 2 : <font color='red'>{{blood_2}}</font>
  8113. * <button type="button" data-ng-click="fight()">Fight</button>
  8114. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  8115. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  8116. * </div>
  8117. * </div>
  8118. *
  8119. * </file>
  8120. * </example>
  8121. */
  8122. function interval(fn, delay, count, invokeApply) {
  8123. var setInterval = $window.setInterval,
  8124. clearInterval = $window.clearInterval,
  8125. deferred = $q.defer(),
  8126. promise = deferred.promise,
  8127. iteration = 0,
  8128. skipApply = (isDefined(invokeApply) && !invokeApply);
  8129. count = isDefined(count) ? count : 0;
  8130. promise.then(null, null, fn);
  8131. promise.$$intervalId = setInterval(function tick() {
  8132. deferred.notify(iteration++);
  8133. if (count > 0 && iteration >= count) {
  8134. deferred.resolve(iteration);
  8135. clearInterval(promise.$$intervalId);
  8136. delete intervals[promise.$$intervalId];
  8137. }
  8138. if (!skipApply) $rootScope.$apply();
  8139. }, delay);
  8140. intervals[promise.$$intervalId] = deferred;
  8141. return promise;
  8142. }
  8143. /**
  8144. * @ngdoc method
  8145. * @name $interval#cancel
  8146. *
  8147. * @description
  8148. * Cancels a task associated with the `promise`.
  8149. *
  8150. * @param {promise} promise returned by the `$interval` function.
  8151. * @returns {boolean} Returns `true` if the task was successfully canceled.
  8152. */
  8153. interval.cancel = function(promise) {
  8154. if (promise && promise.$$intervalId in intervals) {
  8155. intervals[promise.$$intervalId].reject('canceled');
  8156. $window.clearInterval(promise.$$intervalId);
  8157. delete intervals[promise.$$intervalId];
  8158. return true;
  8159. }
  8160. return false;
  8161. };
  8162. return interval;
  8163. }];
  8164. }
  8165. /**
  8166. * @ngdoc service
  8167. * @name $locale
  8168. *
  8169. * @description
  8170. * $locale service provides localization rules for various Angular components. As of right now the
  8171. * only public api is:
  8172. *
  8173. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  8174. */
  8175. function $LocaleProvider(){
  8176. this.$get = function() {
  8177. return {
  8178. id: 'en-us',
  8179. NUMBER_FORMATS: {
  8180. DECIMAL_SEP: '.',
  8181. GROUP_SEP: ',',
  8182. PATTERNS: [
  8183. { // Decimal Pattern
  8184. minInt: 1,
  8185. minFrac: 0,
  8186. maxFrac: 3,
  8187. posPre: '',
  8188. posSuf: '',
  8189. negPre: '-',
  8190. negSuf: '',
  8191. gSize: 3,
  8192. lgSize: 3
  8193. },{ //Currency Pattern
  8194. minInt: 1,
  8195. minFrac: 2,
  8196. maxFrac: 2,
  8197. posPre: '\u00A4',
  8198. posSuf: '',
  8199. negPre: '(\u00A4',
  8200. negSuf: ')',
  8201. gSize: 3,
  8202. lgSize: 3
  8203. }
  8204. ],
  8205. CURRENCY_SYM: '$'
  8206. },
  8207. DATETIME_FORMATS: {
  8208. MONTH:
  8209. 'January,February,March,April,May,June,July,August,September,October,November,December'
  8210. .split(','),
  8211. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  8212. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  8213. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  8214. AMPMS: ['AM','PM'],
  8215. medium: 'MMM d, y h:mm:ss a',
  8216. short: 'M/d/yy h:mm a',
  8217. fullDate: 'EEEE, MMMM d, y',
  8218. longDate: 'MMMM d, y',
  8219. mediumDate: 'MMM d, y',
  8220. shortDate: 'M/d/yy',
  8221. mediumTime: 'h:mm:ss a',
  8222. shortTime: 'h:mm a'
  8223. },
  8224. pluralCat: function(num) {
  8225. if (num === 1) {
  8226. return 'one';
  8227. }
  8228. return 'other';
  8229. }
  8230. };
  8231. };
  8232. }
  8233. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  8234. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  8235. var $locationMinErr = minErr('$location');
  8236. /**
  8237. * Encode path using encodeUriSegment, ignoring forward slashes
  8238. *
  8239. * @param {string} path Path to encode
  8240. * @returns {string}
  8241. */
  8242. function encodePath(path) {
  8243. var segments = path.split('/'),
  8244. i = segments.length;
  8245. while (i--) {
  8246. segments[i] = encodeUriSegment(segments[i]);
  8247. }
  8248. return segments.join('/');
  8249. }
  8250. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  8251. var parsedUrl = urlResolve(absoluteUrl, appBase);
  8252. locationObj.$$protocol = parsedUrl.protocol;
  8253. locationObj.$$host = parsedUrl.hostname;
  8254. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  8255. }
  8256. function parseAppUrl(relativeUrl, locationObj, appBase) {
  8257. var prefixed = (relativeUrl.charAt(0) !== '/');
  8258. if (prefixed) {
  8259. relativeUrl = '/' + relativeUrl;
  8260. }
  8261. var match = urlResolve(relativeUrl, appBase);
  8262. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  8263. match.pathname.substring(1) : match.pathname);
  8264. locationObj.$$search = parseKeyValue(match.search);
  8265. locationObj.$$hash = decodeURIComponent(match.hash);
  8266. // make sure path starts with '/';
  8267. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  8268. locationObj.$$path = '/' + locationObj.$$path;
  8269. }
  8270. }
  8271. /**
  8272. *
  8273. * @param {string} begin
  8274. * @param {string} whole
  8275. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  8276. * expected string.
  8277. */
  8278. function beginsWith(begin, whole) {
  8279. if (whole.indexOf(begin) === 0) {
  8280. return whole.substr(begin.length);
  8281. }
  8282. }
  8283. function stripHash(url) {
  8284. var index = url.indexOf('#');
  8285. return index == -1 ? url : url.substr(0, index);
  8286. }
  8287. function stripFile(url) {
  8288. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  8289. }
  8290. /* return the server only (scheme://host:port) */
  8291. function serverBase(url) {
  8292. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  8293. }
  8294. /**
  8295. * LocationHtml5Url represents an url
  8296. * This object is exposed as $location service when HTML5 mode is enabled and supported
  8297. *
  8298. * @constructor
  8299. * @param {string} appBase application base URL
  8300. * @param {string} basePrefix url path prefix
  8301. */
  8302. function LocationHtml5Url(appBase, basePrefix) {
  8303. this.$$html5 = true;
  8304. basePrefix = basePrefix || '';
  8305. var appBaseNoFile = stripFile(appBase);
  8306. parseAbsoluteUrl(appBase, this, appBase);
  8307. /**
  8308. * Parse given html5 (regular) url string into properties
  8309. * @param {string} newAbsoluteUrl HTML5 url
  8310. * @private
  8311. */
  8312. this.$$parse = function(url) {
  8313. var pathUrl = beginsWith(appBaseNoFile, url);
  8314. if (!isString(pathUrl)) {
  8315. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  8316. appBaseNoFile);
  8317. }
  8318. parseAppUrl(pathUrl, this, appBase);
  8319. if (!this.$$path) {
  8320. this.$$path = '/';
  8321. }
  8322. this.$$compose();
  8323. };
  8324. /**
  8325. * Compose url and update `absUrl` property
  8326. * @private
  8327. */
  8328. this.$$compose = function() {
  8329. var search = toKeyValue(this.$$search),
  8330. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8331. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8332. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  8333. };
  8334. this.$$rewrite = function(url) {
  8335. var appUrl, prevAppUrl;
  8336. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  8337. prevAppUrl = appUrl;
  8338. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  8339. return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  8340. } else {
  8341. return appBase + prevAppUrl;
  8342. }
  8343. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  8344. return appBaseNoFile + appUrl;
  8345. } else if (appBaseNoFile == url + '/') {
  8346. return appBaseNoFile;
  8347. }
  8348. };
  8349. }
  8350. /**
  8351. * LocationHashbangUrl represents url
  8352. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  8353. * It also serves as the base class for html5 mode fallback on legacy browsers.
  8354. *
  8355. * @constructor
  8356. * @param {string} appBase application base URL
  8357. * @param {string} hashPrefix hashbang prefix
  8358. */
  8359. function LocationHashbangUrl(appBase, hashPrefix) {
  8360. var appBaseNoFile = stripFile(appBase);
  8361. parseAbsoluteUrl(appBase, this, appBase);
  8362. /**
  8363. * Parse given hashbang url into properties
  8364. * @param {string} url Hashbang url
  8365. * @private
  8366. */
  8367. this.$$parse = function(url) {
  8368. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  8369. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  8370. ? beginsWith(hashPrefix, withoutBaseUrl)
  8371. : (this.$$html5)
  8372. ? withoutBaseUrl
  8373. : '';
  8374. if (!isString(withoutHashUrl)) {
  8375. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  8376. hashPrefix);
  8377. }
  8378. parseAppUrl(withoutHashUrl, this, appBase);
  8379. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  8380. this.$$compose();
  8381. /*
  8382. * In Windows, on an anchor node on documents loaded from
  8383. * the filesystem, the browser will return a pathname
  8384. * prefixed with the drive name ('/C:/path') when a
  8385. * pathname without a drive is set:
  8386. * * a.setAttribute('href', '/foo')
  8387. * * a.pathname === '/C:/foo' //true
  8388. *
  8389. * Inside of Angular, we're always using pathnames that
  8390. * do not include drive names for routing.
  8391. */
  8392. function removeWindowsDriveName (path, url, base) {
  8393. /*
  8394. Matches paths for file protocol on windows,
  8395. such as /C:/foo/bar, and captures only /foo/bar.
  8396. */
  8397. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  8398. var firstPathSegmentMatch;
  8399. //Get the relative path from the input URL.
  8400. if (url.indexOf(base) === 0) {
  8401. url = url.replace(base, '');
  8402. }
  8403. // The input URL intentionally contains a first path segment that ends with a colon.
  8404. if (windowsFilePathExp.exec(url)) {
  8405. return path;
  8406. }
  8407. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  8408. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  8409. }
  8410. };
  8411. /**
  8412. * Compose hashbang url and update `absUrl` property
  8413. * @private
  8414. */
  8415. this.$$compose = function() {
  8416. var search = toKeyValue(this.$$search),
  8417. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8418. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8419. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  8420. };
  8421. this.$$rewrite = function(url) {
  8422. if(stripHash(appBase) == stripHash(url)) {
  8423. return url;
  8424. }
  8425. };
  8426. }
  8427. /**
  8428. * LocationHashbangUrl represents url
  8429. * This object is exposed as $location service when html5 history api is enabled but the browser
  8430. * does not support it.
  8431. *
  8432. * @constructor
  8433. * @param {string} appBase application base URL
  8434. * @param {string} hashPrefix hashbang prefix
  8435. */
  8436. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  8437. this.$$html5 = true;
  8438. LocationHashbangUrl.apply(this, arguments);
  8439. var appBaseNoFile = stripFile(appBase);
  8440. this.$$rewrite = function(url) {
  8441. var appUrl;
  8442. if ( appBase == stripHash(url) ) {
  8443. return url;
  8444. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  8445. return appBase + hashPrefix + appUrl;
  8446. } else if ( appBaseNoFile === url + '/') {
  8447. return appBaseNoFile;
  8448. }
  8449. };
  8450. this.$$compose = function() {
  8451. var search = toKeyValue(this.$$search),
  8452. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  8453. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  8454. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  8455. this.$$absUrl = appBase + hashPrefix + this.$$url;
  8456. };
  8457. }
  8458. LocationHashbangInHtml5Url.prototype =
  8459. LocationHashbangUrl.prototype =
  8460. LocationHtml5Url.prototype = {
  8461. /**
  8462. * Are we in html5 mode?
  8463. * @private
  8464. */
  8465. $$html5: false,
  8466. /**
  8467. * Has any change been replacing ?
  8468. * @private
  8469. */
  8470. $$replace: false,
  8471. /**
  8472. * @ngdoc method
  8473. * @name $location#absUrl
  8474. *
  8475. * @description
  8476. * This method is getter only.
  8477. *
  8478. * Return full url representation with all segments encoded according to rules specified in
  8479. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  8480. *
  8481. * @return {string} full url
  8482. */
  8483. absUrl: locationGetter('$$absUrl'),
  8484. /**
  8485. * @ngdoc method
  8486. * @name $location#url
  8487. *
  8488. * @description
  8489. * This method is getter / setter.
  8490. *
  8491. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  8492. *
  8493. * Change path, search and hash, when called with parameter and return `$location`.
  8494. *
  8495. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  8496. * @param {string=} replace The path that will be changed
  8497. * @return {string} url
  8498. */
  8499. url: function(url, replace) {
  8500. if (isUndefined(url))
  8501. return this.$$url;
  8502. var match = PATH_MATCH.exec(url);
  8503. if (match[1]) this.path(decodeURIComponent(match[1]));
  8504. if (match[2] || match[1]) this.search(match[3] || '');
  8505. this.hash(match[5] || '', replace);
  8506. return this;
  8507. },
  8508. /**
  8509. * @ngdoc method
  8510. * @name $location#protocol
  8511. *
  8512. * @description
  8513. * This method is getter only.
  8514. *
  8515. * Return protocol of current url.
  8516. *
  8517. * @return {string} protocol of current url
  8518. */
  8519. protocol: locationGetter('$$protocol'),
  8520. /**
  8521. * @ngdoc method
  8522. * @name $location#host
  8523. *
  8524. * @description
  8525. * This method is getter only.
  8526. *
  8527. * Return host of current url.
  8528. *
  8529. * @return {string} host of current url.
  8530. */
  8531. host: locationGetter('$$host'),
  8532. /**
  8533. * @ngdoc method
  8534. * @name $location#port
  8535. *
  8536. * @description
  8537. * This method is getter only.
  8538. *
  8539. * Return port of current url.
  8540. *
  8541. * @return {Number} port
  8542. */
  8543. port: locationGetter('$$port'),
  8544. /**
  8545. * @ngdoc method
  8546. * @name $location#path
  8547. *
  8548. * @description
  8549. * This method is getter / setter.
  8550. *
  8551. * Return path of current url when called without any parameter.
  8552. *
  8553. * Change path when called with parameter and return `$location`.
  8554. *
  8555. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  8556. * if it is missing.
  8557. *
  8558. * @param {string=} path New path
  8559. * @return {string} path
  8560. */
  8561. path: locationGetterSetter('$$path', function(path) {
  8562. return path.charAt(0) == '/' ? path : '/' + path;
  8563. }),
  8564. /**
  8565. * @ngdoc method
  8566. * @name $location#search
  8567. *
  8568. * @description
  8569. * This method is getter / setter.
  8570. *
  8571. * Return search part (as object) of current url when called without any parameter.
  8572. *
  8573. * Change search part when called with parameter and return `$location`.
  8574. *
  8575. *
  8576. * ```js
  8577. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  8578. * var searchObject = $location.search();
  8579. * // => {foo: 'bar', baz: 'xoxo'}
  8580. *
  8581. *
  8582. * // set foo to 'yipee'
  8583. * $location.search('foo', 'yipee');
  8584. * // => $location
  8585. * ```
  8586. *
  8587. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  8588. * hash object.
  8589. *
  8590. * When called with a single argument the method acts as a setter, setting the `search` component
  8591. * of `$location` to the specified value.
  8592. *
  8593. * If the argument is a hash object containing an array of values, these values will be encoded
  8594. * as duplicate search parameters in the url.
  8595. *
  8596. * @param {(string|Array<string>|boolean)=} paramValue If `search` is a string, then `paramValue`
  8597. * will override only a single search property.
  8598. *
  8599. * If `paramValue` is an array, it will override the property of the `search` component of
  8600. * `$location` specified via the first argument.
  8601. *
  8602. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  8603. *
  8604. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  8605. * value nor trailing equal sign.
  8606. *
  8607. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  8608. * one or more arguments returns `$location` object itself.
  8609. */
  8610. search: function(search, paramValue) {
  8611. switch (arguments.length) {
  8612. case 0:
  8613. return this.$$search;
  8614. case 1:
  8615. if (isString(search)) {
  8616. this.$$search = parseKeyValue(search);
  8617. } else if (isObject(search)) {
  8618. // remove object undefined or null properties
  8619. forEach(search, function(value, key) {
  8620. if (value == null) delete search[key];
  8621. });
  8622. this.$$search = search;
  8623. } else {
  8624. throw $locationMinErr('isrcharg',
  8625. 'The first argument of the `$location#search()` call must be a string or an object.');
  8626. }
  8627. break;
  8628. default:
  8629. if (isUndefined(paramValue) || paramValue === null) {
  8630. delete this.$$search[search];
  8631. } else {
  8632. this.$$search[search] = paramValue;
  8633. }
  8634. }
  8635. this.$$compose();
  8636. return this;
  8637. },
  8638. /**
  8639. * @ngdoc method
  8640. * @name $location#hash
  8641. *
  8642. * @description
  8643. * This method is getter / setter.
  8644. *
  8645. * Return hash fragment when called without any parameter.
  8646. *
  8647. * Change hash fragment when called with parameter and return `$location`.
  8648. *
  8649. * @param {string=} hash New hash fragment
  8650. * @return {string} hash
  8651. */
  8652. hash: locationGetterSetter('$$hash', identity),
  8653. /**
  8654. * @ngdoc method
  8655. * @name $location#replace
  8656. *
  8657. * @description
  8658. * If called, all changes to $location during current `$digest` will be replacing current history
  8659. * record, instead of adding new one.
  8660. */
  8661. replace: function() {
  8662. this.$$replace = true;
  8663. return this;
  8664. }
  8665. };
  8666. function locationGetter(property) {
  8667. return function() {
  8668. return this[property];
  8669. };
  8670. }
  8671. function locationGetterSetter(property, preprocess) {
  8672. return function(value) {
  8673. if (isUndefined(value))
  8674. return this[property];
  8675. this[property] = preprocess(value);
  8676. this.$$compose();
  8677. return this;
  8678. };
  8679. }
  8680. /**
  8681. * @ngdoc service
  8682. * @name $location
  8683. *
  8684. * @requires $rootElement
  8685. *
  8686. * @description
  8687. * The $location service parses the URL in the browser address bar (based on the
  8688. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  8689. * available to your application. Changes to the URL in the address bar are reflected into
  8690. * $location service and changes to $location are reflected into the browser address bar.
  8691. *
  8692. * **The $location service:**
  8693. *
  8694. * - Exposes the current URL in the browser address bar, so you can
  8695. * - Watch and observe the URL.
  8696. * - Change the URL.
  8697. * - Synchronizes the URL with the browser when the user
  8698. * - Changes the address bar.
  8699. * - Clicks the back or forward button (or clicks a History link).
  8700. * - Clicks on a link.
  8701. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  8702. *
  8703. * For more information see {@link guide/$location Developer Guide: Using $location}
  8704. */
  8705. /**
  8706. * @ngdoc provider
  8707. * @name $locationProvider
  8708. * @description
  8709. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  8710. */
  8711. function $LocationProvider(){
  8712. var hashPrefix = '',
  8713. html5Mode = false;
  8714. /**
  8715. * @ngdoc method
  8716. * @name $locationProvider#hashPrefix
  8717. * @description
  8718. * @param {string=} prefix Prefix for hash part (containing path and search)
  8719. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8720. */
  8721. this.hashPrefix = function(prefix) {
  8722. if (isDefined(prefix)) {
  8723. hashPrefix = prefix;
  8724. return this;
  8725. } else {
  8726. return hashPrefix;
  8727. }
  8728. };
  8729. /**
  8730. * @ngdoc method
  8731. * @name $locationProvider#html5Mode
  8732. * @description
  8733. * @param {boolean=} mode Use HTML5 strategy if available.
  8734. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8735. */
  8736. this.html5Mode = function(mode) {
  8737. if (isDefined(mode)) {
  8738. html5Mode = mode;
  8739. return this;
  8740. } else {
  8741. return html5Mode;
  8742. }
  8743. };
  8744. /**
  8745. * @ngdoc event
  8746. * @name $location#$locationChangeStart
  8747. * @eventType broadcast on root scope
  8748. * @description
  8749. * Broadcasted before a URL will change. This change can be prevented by calling
  8750. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  8751. * details about event object. Upon successful change
  8752. * {@link ng.$location#events_$locationChangeSuccess $locationChangeSuccess} is fired.
  8753. *
  8754. * @param {Object} angularEvent Synthetic event object.
  8755. * @param {string} newUrl New URL
  8756. * @param {string=} oldUrl URL that was before it was changed.
  8757. */
  8758. /**
  8759. * @ngdoc event
  8760. * @name $location#$locationChangeSuccess
  8761. * @eventType broadcast on root scope
  8762. * @description
  8763. * Broadcasted after a URL was changed.
  8764. *
  8765. * @param {Object} angularEvent Synthetic event object.
  8766. * @param {string} newUrl New URL
  8767. * @param {string=} oldUrl URL that was before it was changed.
  8768. */
  8769. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  8770. function( $rootScope, $browser, $sniffer, $rootElement) {
  8771. var $location,
  8772. LocationMode,
  8773. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  8774. initialUrl = $browser.url(),
  8775. appBase;
  8776. if (html5Mode) {
  8777. appBase = serverBase(initialUrl) + (baseHref || '/');
  8778. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  8779. } else {
  8780. appBase = stripHash(initialUrl);
  8781. LocationMode = LocationHashbangUrl;
  8782. }
  8783. $location = new LocationMode(appBase, '#' + hashPrefix);
  8784. $location.$$parse($location.$$rewrite(initialUrl));
  8785. $rootElement.on('click', function(event) {
  8786. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  8787. // currently we open nice url link and redirect then
  8788. if (event.ctrlKey || event.metaKey || event.which == 2) return;
  8789. var elm = jqLite(event.target);
  8790. // traverse the DOM up to find first A tag
  8791. while (lowercase(elm[0].nodeName) !== 'a') {
  8792. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  8793. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  8794. }
  8795. var absHref = elm.prop('href');
  8796. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  8797. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  8798. // an animation.
  8799. absHref = urlResolve(absHref.animVal).href;
  8800. }
  8801. // Make relative links work in HTML5 mode for legacy browsers (or at least IE8 & 9)
  8802. // The href should be a regular url e.g. /link/somewhere or link/somewhere or ../somewhere or
  8803. // somewhere#anchor or http://example.com/somewhere
  8804. if (LocationMode === LocationHashbangInHtml5Url) {
  8805. // get the actual href attribute - see
  8806. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  8807. var href = elm.attr('href') || elm.attr('xlink:href');
  8808. if (href.indexOf('://') < 0) { // Ignore absolute URLs
  8809. var prefix = '#' + hashPrefix;
  8810. if (href[0] == '/') {
  8811. // absolute path - replace old path
  8812. absHref = appBase + prefix + href;
  8813. } else if (href[0] == '#') {
  8814. // local anchor
  8815. absHref = appBase + prefix + ($location.path() || '/') + href;
  8816. } else {
  8817. // relative path - join with current path
  8818. var stack = $location.path().split("/"),
  8819. parts = href.split("/");
  8820. for (var i=0; i<parts.length; i++) {
  8821. if (parts[i] == ".")
  8822. continue;
  8823. else if (parts[i] == "..")
  8824. stack.pop();
  8825. else if (parts[i].length)
  8826. stack.push(parts[i]);
  8827. }
  8828. absHref = appBase + prefix + stack.join('/');
  8829. }
  8830. }
  8831. }
  8832. var rewrittenUrl = $location.$$rewrite(absHref);
  8833. if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
  8834. event.preventDefault();
  8835. if (rewrittenUrl != $browser.url()) {
  8836. // update location manually
  8837. $location.$$parse(rewrittenUrl);
  8838. $rootScope.$apply();
  8839. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  8840. window.angular['ff-684208-preventDefault'] = true;
  8841. }
  8842. }
  8843. });
  8844. // rewrite hashbang url <> html5 url
  8845. if ($location.absUrl() != initialUrl) {
  8846. $browser.url($location.absUrl(), true);
  8847. }
  8848. // update $location when $browser url changes
  8849. $browser.onUrlChange(function(newUrl) {
  8850. if ($location.absUrl() != newUrl) {
  8851. $rootScope.$evalAsync(function() {
  8852. var oldUrl = $location.absUrl();
  8853. $location.$$parse(newUrl);
  8854. if ($rootScope.$broadcast('$locationChangeStart', newUrl,
  8855. oldUrl).defaultPrevented) {
  8856. $location.$$parse(oldUrl);
  8857. $browser.url(oldUrl);
  8858. } else {
  8859. afterLocationChange(oldUrl);
  8860. }
  8861. });
  8862. if (!$rootScope.$$phase) $rootScope.$digest();
  8863. }
  8864. });
  8865. // update browser
  8866. var changeCounter = 0;
  8867. $rootScope.$watch(function $locationWatch() {
  8868. var oldUrl = $browser.url();
  8869. var currentReplace = $location.$$replace;
  8870. if (!changeCounter || oldUrl != $location.absUrl()) {
  8871. changeCounter++;
  8872. $rootScope.$evalAsync(function() {
  8873. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
  8874. defaultPrevented) {
  8875. $location.$$parse(oldUrl);
  8876. } else {
  8877. $browser.url($location.absUrl(), currentReplace);
  8878. afterLocationChange(oldUrl);
  8879. }
  8880. });
  8881. }
  8882. $location.$$replace = false;
  8883. return changeCounter;
  8884. });
  8885. return $location;
  8886. function afterLocationChange(oldUrl) {
  8887. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
  8888. }
  8889. }];
  8890. }
  8891. /**
  8892. * @ngdoc service
  8893. * @name $log
  8894. * @requires $window
  8895. *
  8896. * @description
  8897. * Simple service for logging. Default implementation safely writes the message
  8898. * into the browser's console (if present).
  8899. *
  8900. * The main purpose of this service is to simplify debugging and troubleshooting.
  8901. *
  8902. * The default is to log `debug` messages. You can use
  8903. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  8904. *
  8905. * @example
  8906. <example module="logExample">
  8907. <file name="script.js">
  8908. angular.module('logExample', [])
  8909. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  8910. $scope.$log = $log;
  8911. $scope.message = 'Hello World!';
  8912. }]);
  8913. </file>
  8914. <file name="index.html">
  8915. <div ng-controller="LogController">
  8916. <p>Reload this page with open console, enter text and hit the log button...</p>
  8917. Message:
  8918. <input type="text" ng-model="message"/>
  8919. <button ng-click="$log.log(message)">log</button>
  8920. <button ng-click="$log.warn(message)">warn</button>
  8921. <button ng-click="$log.info(message)">info</button>
  8922. <button ng-click="$log.error(message)">error</button>
  8923. </div>
  8924. </file>
  8925. </example>
  8926. */
  8927. /**
  8928. * @ngdoc provider
  8929. * @name $logProvider
  8930. * @description
  8931. * Use the `$logProvider` to configure how the application logs messages
  8932. */
  8933. function $LogProvider(){
  8934. var debug = true,
  8935. self = this;
  8936. /**
  8937. * @ngdoc method
  8938. * @name $logProvider#debugEnabled
  8939. * @description
  8940. * @param {boolean=} flag enable or disable debug level messages
  8941. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  8942. */
  8943. this.debugEnabled = function(flag) {
  8944. if (isDefined(flag)) {
  8945. debug = flag;
  8946. return this;
  8947. } else {
  8948. return debug;
  8949. }
  8950. };
  8951. this.$get = ['$window', function($window){
  8952. return {
  8953. /**
  8954. * @ngdoc method
  8955. * @name $log#log
  8956. *
  8957. * @description
  8958. * Write a log message
  8959. */
  8960. log: consoleLog('log'),
  8961. /**
  8962. * @ngdoc method
  8963. * @name $log#info
  8964. *
  8965. * @description
  8966. * Write an information message
  8967. */
  8968. info: consoleLog('info'),
  8969. /**
  8970. * @ngdoc method
  8971. * @name $log#warn
  8972. *
  8973. * @description
  8974. * Write a warning message
  8975. */
  8976. warn: consoleLog('warn'),
  8977. /**
  8978. * @ngdoc method
  8979. * @name $log#error
  8980. *
  8981. * @description
  8982. * Write an error message
  8983. */
  8984. error: consoleLog('error'),
  8985. /**
  8986. * @ngdoc method
  8987. * @name $log#debug
  8988. *
  8989. * @description
  8990. * Write a debug message
  8991. */
  8992. debug: (function () {
  8993. var fn = consoleLog('debug');
  8994. return function() {
  8995. if (debug) {
  8996. fn.apply(self, arguments);
  8997. }
  8998. };
  8999. }())
  9000. };
  9001. function formatError(arg) {
  9002. if (arg instanceof Error) {
  9003. if (arg.stack) {
  9004. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  9005. ? 'Error: ' + arg.message + '\n' + arg.stack
  9006. : arg.stack;
  9007. } else if (arg.sourceURL) {
  9008. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  9009. }
  9010. }
  9011. return arg;
  9012. }
  9013. function consoleLog(type) {
  9014. var console = $window.console || {},
  9015. logFn = console[type] || console.log || noop,
  9016. hasApply = false;
  9017. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  9018. // The reason behind this is that console.log has type "object" in IE8...
  9019. try {
  9020. hasApply = !!logFn.apply;
  9021. } catch (e) {}
  9022. if (hasApply) {
  9023. return function() {
  9024. var args = [];
  9025. forEach(arguments, function(arg) {
  9026. args.push(formatError(arg));
  9027. });
  9028. return logFn.apply(console, args);
  9029. };
  9030. }
  9031. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  9032. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  9033. return function(arg1, arg2) {
  9034. logFn(arg1, arg2 == null ? '' : arg2);
  9035. };
  9036. }
  9037. }];
  9038. }
  9039. var $parseMinErr = minErr('$parse');
  9040. var promiseWarningCache = {};
  9041. var promiseWarning;
  9042. // Sandboxing Angular Expressions
  9043. // ------------------------------
  9044. // Angular expressions are generally considered safe because these expressions only have direct
  9045. // access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
  9046. // obtaining a reference to native JS functions such as the Function constructor.
  9047. //
  9048. // As an example, consider the following Angular expression:
  9049. //
  9050. // {}.toString.constructor('alert("evil JS code")')
  9051. //
  9052. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  9053. // against the expression language, but not to prevent exploits that were enabled by exposing
  9054. // sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
  9055. // practice and therefore we are not even trying to protect against interaction with an object
  9056. // explicitly exposed in this way.
  9057. //
  9058. // In general, it is not possible to access a Window object from an angular expression unless a
  9059. // window or some DOM object that has a reference to window is published onto a Scope.
  9060. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  9061. // native objects.
  9062. function ensureSafeMemberName(name, fullExpression) {
  9063. if (name === "__defineGetter__" || name === "__defineSetter__"
  9064. || name === "__lookupGetter__" || name === "__lookupSetter__"
  9065. || name === "__proto__") {
  9066. throw $parseMinErr('isecfld',
  9067. 'Attempting to access a disallowed field in Angular expressions! '
  9068. +'Expression: {0}', fullExpression);
  9069. }
  9070. return name;
  9071. }
  9072. function ensureSafeObject(obj, fullExpression) {
  9073. // nifty check if obj is Function that is fast and works across iframes and other contexts
  9074. if (obj) {
  9075. if (obj.constructor === obj) {
  9076. throw $parseMinErr('isecfn',
  9077. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  9078. fullExpression);
  9079. } else if (// isWindow(obj)
  9080. obj.document && obj.location && obj.alert && obj.setInterval) {
  9081. throw $parseMinErr('isecwindow',
  9082. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  9083. fullExpression);
  9084. } else if (// isElement(obj)
  9085. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  9086. throw $parseMinErr('isecdom',
  9087. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  9088. fullExpression);
  9089. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  9090. obj === Object) {
  9091. throw $parseMinErr('isecobj',
  9092. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  9093. fullExpression);
  9094. }
  9095. }
  9096. return obj;
  9097. }
  9098. var CALL = Function.prototype.call;
  9099. var APPLY = Function.prototype.apply;
  9100. var BIND = Function.prototype.bind;
  9101. function ensureSafeFunction(obj, fullExpression) {
  9102. if (obj) {
  9103. if (obj.constructor === obj) {
  9104. throw $parseMinErr('isecfn',
  9105. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  9106. fullExpression);
  9107. } else if (obj === CALL || obj === APPLY || (BIND && obj === BIND)) {
  9108. throw $parseMinErr('isecff',
  9109. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  9110. fullExpression);
  9111. }
  9112. }
  9113. }
  9114. var OPERATORS = {
  9115. /* jshint bitwise : false */
  9116. 'null':function(){return null;},
  9117. 'true':function(){return true;},
  9118. 'false':function(){return false;},
  9119. undefined:noop,
  9120. '+':function(self, locals, a,b){
  9121. a=a(self, locals); b=b(self, locals);
  9122. if (isDefined(a)) {
  9123. if (isDefined(b)) {
  9124. return a + b;
  9125. }
  9126. return a;
  9127. }
  9128. return isDefined(b)?b:undefined;},
  9129. '-':function(self, locals, a,b){
  9130. a=a(self, locals); b=b(self, locals);
  9131. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  9132. },
  9133. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  9134. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  9135. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  9136. '^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
  9137. '=':noop,
  9138. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  9139. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  9140. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  9141. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  9142. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  9143. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  9144. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  9145. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  9146. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  9147. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  9148. '&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
  9149. // '|':function(self, locals, a,b){return a|b;},
  9150. '|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
  9151. '!':function(self, locals, a){return !a(self, locals);}
  9152. };
  9153. /* jshint bitwise: true */
  9154. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  9155. /////////////////////////////////////////
  9156. /**
  9157. * @constructor
  9158. */
  9159. var Lexer = function (options) {
  9160. this.options = options;
  9161. };
  9162. Lexer.prototype = {
  9163. constructor: Lexer,
  9164. lex: function (text) {
  9165. this.text = text;
  9166. this.index = 0;
  9167. this.ch = undefined;
  9168. this.lastCh = ':'; // can start regexp
  9169. this.tokens = [];
  9170. while (this.index < this.text.length) {
  9171. this.ch = this.text.charAt(this.index);
  9172. if (this.is('"\'')) {
  9173. this.readString(this.ch);
  9174. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  9175. this.readNumber();
  9176. } else if (this.isIdent(this.ch)) {
  9177. this.readIdent();
  9178. } else if (this.is('(){}[].,;:?')) {
  9179. this.tokens.push({
  9180. index: this.index,
  9181. text: this.ch
  9182. });
  9183. this.index++;
  9184. } else if (this.isWhitespace(this.ch)) {
  9185. this.index++;
  9186. continue;
  9187. } else {
  9188. var ch2 = this.ch + this.peek();
  9189. var ch3 = ch2 + this.peek(2);
  9190. var fn = OPERATORS[this.ch];
  9191. var fn2 = OPERATORS[ch2];
  9192. var fn3 = OPERATORS[ch3];
  9193. if (fn3) {
  9194. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  9195. this.index += 3;
  9196. } else if (fn2) {
  9197. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  9198. this.index += 2;
  9199. } else if (fn) {
  9200. this.tokens.push({
  9201. index: this.index,
  9202. text: this.ch,
  9203. fn: fn
  9204. });
  9205. this.index += 1;
  9206. } else {
  9207. this.throwError('Unexpected next character ', this.index, this.index + 1);
  9208. }
  9209. }
  9210. this.lastCh = this.ch;
  9211. }
  9212. return this.tokens;
  9213. },
  9214. is: function(chars) {
  9215. return chars.indexOf(this.ch) !== -1;
  9216. },
  9217. was: function(chars) {
  9218. return chars.indexOf(this.lastCh) !== -1;
  9219. },
  9220. peek: function(i) {
  9221. var num = i || 1;
  9222. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  9223. },
  9224. isNumber: function(ch) {
  9225. return ('0' <= ch && ch <= '9');
  9226. },
  9227. isWhitespace: function(ch) {
  9228. // IE treats non-breaking space as \u00A0
  9229. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  9230. ch === '\n' || ch === '\v' || ch === '\u00A0');
  9231. },
  9232. isIdent: function(ch) {
  9233. return ('a' <= ch && ch <= 'z' ||
  9234. 'A' <= ch && ch <= 'Z' ||
  9235. '_' === ch || ch === '$');
  9236. },
  9237. isExpOperator: function(ch) {
  9238. return (ch === '-' || ch === '+' || this.isNumber(ch));
  9239. },
  9240. throwError: function(error, start, end) {
  9241. end = end || this.index;
  9242. var colStr = (isDefined(start)
  9243. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  9244. : ' ' + end);
  9245. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  9246. error, colStr, this.text);
  9247. },
  9248. readNumber: function() {
  9249. var number = '';
  9250. var start = this.index;
  9251. while (this.index < this.text.length) {
  9252. var ch = lowercase(this.text.charAt(this.index));
  9253. if (ch == '.' || this.isNumber(ch)) {
  9254. number += ch;
  9255. } else {
  9256. var peekCh = this.peek();
  9257. if (ch == 'e' && this.isExpOperator(peekCh)) {
  9258. number += ch;
  9259. } else if (this.isExpOperator(ch) &&
  9260. peekCh && this.isNumber(peekCh) &&
  9261. number.charAt(number.length - 1) == 'e') {
  9262. number += ch;
  9263. } else if (this.isExpOperator(ch) &&
  9264. (!peekCh || !this.isNumber(peekCh)) &&
  9265. number.charAt(number.length - 1) == 'e') {
  9266. this.throwError('Invalid exponent');
  9267. } else {
  9268. break;
  9269. }
  9270. }
  9271. this.index++;
  9272. }
  9273. number = 1 * number;
  9274. this.tokens.push({
  9275. index: start,
  9276. text: number,
  9277. literal: true,
  9278. constant: true,
  9279. fn: function() { return number; }
  9280. });
  9281. },
  9282. readIdent: function() {
  9283. var parser = this;
  9284. var ident = '';
  9285. var start = this.index;
  9286. var lastDot, peekIndex, methodName, ch;
  9287. while (this.index < this.text.length) {
  9288. ch = this.text.charAt(this.index);
  9289. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  9290. if (ch === '.') lastDot = this.index;
  9291. ident += ch;
  9292. } else {
  9293. break;
  9294. }
  9295. this.index++;
  9296. }
  9297. //check if this is not a method invocation and if it is back out to last dot
  9298. if (lastDot) {
  9299. peekIndex = this.index;
  9300. while (peekIndex < this.text.length) {
  9301. ch = this.text.charAt(peekIndex);
  9302. if (ch === '(') {
  9303. methodName = ident.substr(lastDot - start + 1);
  9304. ident = ident.substr(0, lastDot - start);
  9305. this.index = peekIndex;
  9306. break;
  9307. }
  9308. if (this.isWhitespace(ch)) {
  9309. peekIndex++;
  9310. } else {
  9311. break;
  9312. }
  9313. }
  9314. }
  9315. var token = {
  9316. index: start,
  9317. text: ident
  9318. };
  9319. // OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
  9320. if (OPERATORS.hasOwnProperty(ident)) {
  9321. token.fn = OPERATORS[ident];
  9322. token.literal = true;
  9323. token.constant = true;
  9324. } else {
  9325. var getter = getterFn(ident, this.options, this.text);
  9326. token.fn = extend(function(self, locals) {
  9327. return (getter(self, locals));
  9328. }, {
  9329. assign: function(self, value) {
  9330. return setter(self, ident, value, parser.text, parser.options);
  9331. }
  9332. });
  9333. }
  9334. this.tokens.push(token);
  9335. if (methodName) {
  9336. this.tokens.push({
  9337. index:lastDot,
  9338. text: '.'
  9339. });
  9340. this.tokens.push({
  9341. index: lastDot + 1,
  9342. text: methodName
  9343. });
  9344. }
  9345. },
  9346. readString: function(quote) {
  9347. var start = this.index;
  9348. this.index++;
  9349. var string = '';
  9350. var rawString = quote;
  9351. var escape = false;
  9352. while (this.index < this.text.length) {
  9353. var ch = this.text.charAt(this.index);
  9354. rawString += ch;
  9355. if (escape) {
  9356. if (ch === 'u') {
  9357. var hex = this.text.substring(this.index + 1, this.index + 5);
  9358. if (!hex.match(/[\da-f]{4}/i))
  9359. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  9360. this.index += 4;
  9361. string += String.fromCharCode(parseInt(hex, 16));
  9362. } else {
  9363. var rep = ESCAPE[ch];
  9364. string = string + (rep || ch);
  9365. }
  9366. escape = false;
  9367. } else if (ch === '\\') {
  9368. escape = true;
  9369. } else if (ch === quote) {
  9370. this.index++;
  9371. this.tokens.push({
  9372. index: start,
  9373. text: rawString,
  9374. string: string,
  9375. literal: true,
  9376. constant: true,
  9377. fn: function() { return string; }
  9378. });
  9379. return;
  9380. } else {
  9381. string += ch;
  9382. }
  9383. this.index++;
  9384. }
  9385. this.throwError('Unterminated quote', start);
  9386. }
  9387. };
  9388. /**
  9389. * @constructor
  9390. */
  9391. var Parser = function (lexer, $filter, options) {
  9392. this.lexer = lexer;
  9393. this.$filter = $filter;
  9394. this.options = options;
  9395. };
  9396. Parser.ZERO = extend(function () {
  9397. return 0;
  9398. }, {
  9399. constant: true
  9400. });
  9401. Parser.prototype = {
  9402. constructor: Parser,
  9403. parse: function (text) {
  9404. this.text = text;
  9405. this.tokens = this.lexer.lex(text);
  9406. var value = this.statements();
  9407. if (this.tokens.length !== 0) {
  9408. this.throwError('is an unexpected token', this.tokens[0]);
  9409. }
  9410. value.literal = !!value.literal;
  9411. value.constant = !!value.constant;
  9412. return value;
  9413. },
  9414. primary: function () {
  9415. var primary;
  9416. if (this.expect('(')) {
  9417. primary = this.filterChain();
  9418. this.consume(')');
  9419. } else if (this.expect('[')) {
  9420. primary = this.arrayDeclaration();
  9421. } else if (this.expect('{')) {
  9422. primary = this.object();
  9423. } else {
  9424. var token = this.expect();
  9425. primary = token.fn;
  9426. if (!primary) {
  9427. this.throwError('not a primary expression', token);
  9428. }
  9429. primary.literal = !!token.literal;
  9430. primary.constant = !!token.constant;
  9431. }
  9432. var next, context;
  9433. while ((next = this.expect('(', '[', '.'))) {
  9434. if (next.text === '(') {
  9435. primary = this.functionCall(primary, context);
  9436. context = null;
  9437. } else if (next.text === '[') {
  9438. context = primary;
  9439. primary = this.objectIndex(primary);
  9440. } else if (next.text === '.') {
  9441. context = primary;
  9442. primary = this.fieldAccess(primary);
  9443. } else {
  9444. this.throwError('IMPOSSIBLE');
  9445. }
  9446. }
  9447. return primary;
  9448. },
  9449. throwError: function(msg, token) {
  9450. throw $parseMinErr('syntax',
  9451. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  9452. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  9453. },
  9454. peekToken: function() {
  9455. if (this.tokens.length === 0)
  9456. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  9457. return this.tokens[0];
  9458. },
  9459. peek: function(e1, e2, e3, e4) {
  9460. if (this.tokens.length > 0) {
  9461. var token = this.tokens[0];
  9462. var t = token.text;
  9463. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  9464. (!e1 && !e2 && !e3 && !e4)) {
  9465. return token;
  9466. }
  9467. }
  9468. return false;
  9469. },
  9470. expect: function(e1, e2, e3, e4){
  9471. var token = this.peek(e1, e2, e3, e4);
  9472. if (token) {
  9473. this.tokens.shift();
  9474. return token;
  9475. }
  9476. return false;
  9477. },
  9478. consume: function(e1){
  9479. if (!this.expect(e1)) {
  9480. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  9481. }
  9482. },
  9483. unaryFn: function(fn, right) {
  9484. return extend(function(self, locals) {
  9485. return fn(self, locals, right);
  9486. }, {
  9487. constant:right.constant
  9488. });
  9489. },
  9490. ternaryFn: function(left, middle, right){
  9491. return extend(function(self, locals){
  9492. return left(self, locals) ? middle(self, locals) : right(self, locals);
  9493. }, {
  9494. constant: left.constant && middle.constant && right.constant
  9495. });
  9496. },
  9497. binaryFn: function(left, fn, right) {
  9498. return extend(function(self, locals) {
  9499. return fn(self, locals, left, right);
  9500. }, {
  9501. constant:left.constant && right.constant
  9502. });
  9503. },
  9504. statements: function() {
  9505. var statements = [];
  9506. while (true) {
  9507. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  9508. statements.push(this.filterChain());
  9509. if (!this.expect(';')) {
  9510. // optimize for the common case where there is only one statement.
  9511. // TODO(size): maybe we should not support multiple statements?
  9512. return (statements.length === 1)
  9513. ? statements[0]
  9514. : function(self, locals) {
  9515. var value;
  9516. for (var i = 0; i < statements.length; i++) {
  9517. var statement = statements[i];
  9518. if (statement) {
  9519. value = statement(self, locals);
  9520. }
  9521. }
  9522. return value;
  9523. };
  9524. }
  9525. }
  9526. },
  9527. filterChain: function() {
  9528. var left = this.expression();
  9529. var token;
  9530. while (true) {
  9531. if ((token = this.expect('|'))) {
  9532. left = this.binaryFn(left, token.fn, this.filter());
  9533. } else {
  9534. return left;
  9535. }
  9536. }
  9537. },
  9538. filter: function() {
  9539. var token = this.expect();
  9540. var fn = this.$filter(token.text);
  9541. var argsFn = [];
  9542. while (true) {
  9543. if ((token = this.expect(':'))) {
  9544. argsFn.push(this.expression());
  9545. } else {
  9546. var fnInvoke = function(self, locals, input) {
  9547. var args = [input];
  9548. for (var i = 0; i < argsFn.length; i++) {
  9549. args.push(argsFn[i](self, locals));
  9550. }
  9551. return fn.apply(self, args);
  9552. };
  9553. return function() {
  9554. return fnInvoke;
  9555. };
  9556. }
  9557. }
  9558. },
  9559. expression: function() {
  9560. return this.assignment();
  9561. },
  9562. assignment: function() {
  9563. var left = this.ternary();
  9564. var right;
  9565. var token;
  9566. if ((token = this.expect('='))) {
  9567. if (!left.assign) {
  9568. this.throwError('implies assignment but [' +
  9569. this.text.substring(0, token.index) + '] can not be assigned to', token);
  9570. }
  9571. right = this.ternary();
  9572. return function(scope, locals) {
  9573. return left.assign(scope, right(scope, locals), locals);
  9574. };
  9575. }
  9576. return left;
  9577. },
  9578. ternary: function() {
  9579. var left = this.logicalOR();
  9580. var middle;
  9581. var token;
  9582. if ((token = this.expect('?'))) {
  9583. middle = this.ternary();
  9584. if ((token = this.expect(':'))) {
  9585. return this.ternaryFn(left, middle, this.ternary());
  9586. } else {
  9587. this.throwError('expected :', token);
  9588. }
  9589. } else {
  9590. return left;
  9591. }
  9592. },
  9593. logicalOR: function() {
  9594. var left = this.logicalAND();
  9595. var token;
  9596. while (true) {
  9597. if ((token = this.expect('||'))) {
  9598. left = this.binaryFn(left, token.fn, this.logicalAND());
  9599. } else {
  9600. return left;
  9601. }
  9602. }
  9603. },
  9604. logicalAND: function() {
  9605. var left = this.equality();
  9606. var token;
  9607. if ((token = this.expect('&&'))) {
  9608. left = this.binaryFn(left, token.fn, this.logicalAND());
  9609. }
  9610. return left;
  9611. },
  9612. equality: function() {
  9613. var left = this.relational();
  9614. var token;
  9615. if ((token = this.expect('==','!=','===','!=='))) {
  9616. left = this.binaryFn(left, token.fn, this.equality());
  9617. }
  9618. return left;
  9619. },
  9620. relational: function() {
  9621. var left = this.additive();
  9622. var token;
  9623. if ((token = this.expect('<', '>', '<=', '>='))) {
  9624. left = this.binaryFn(left, token.fn, this.relational());
  9625. }
  9626. return left;
  9627. },
  9628. additive: function() {
  9629. var left = this.multiplicative();
  9630. var token;
  9631. while ((token = this.expect('+','-'))) {
  9632. left = this.binaryFn(left, token.fn, this.multiplicative());
  9633. }
  9634. return left;
  9635. },
  9636. multiplicative: function() {
  9637. var left = this.unary();
  9638. var token;
  9639. while ((token = this.expect('*','/','%'))) {
  9640. left = this.binaryFn(left, token.fn, this.unary());
  9641. }
  9642. return left;
  9643. },
  9644. unary: function() {
  9645. var token;
  9646. if (this.expect('+')) {
  9647. return this.primary();
  9648. } else if ((token = this.expect('-'))) {
  9649. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  9650. } else if ((token = this.expect('!'))) {
  9651. return this.unaryFn(token.fn, this.unary());
  9652. } else {
  9653. return this.primary();
  9654. }
  9655. },
  9656. fieldAccess: function(object) {
  9657. var parser = this;
  9658. var field = this.expect().text;
  9659. var getter = getterFn(field, this.options, this.text);
  9660. return extend(function(scope, locals, self) {
  9661. return getter(self || object(scope, locals));
  9662. }, {
  9663. assign: function(scope, value, locals) {
  9664. return setter(object(scope, locals), field, value, parser.text, parser.options);
  9665. }
  9666. });
  9667. },
  9668. objectIndex: function(obj) {
  9669. var parser = this;
  9670. var indexFn = this.expression();
  9671. this.consume(']');
  9672. return extend(function(self, locals) {
  9673. var o = obj(self, locals),
  9674. i = indexFn(self, locals),
  9675. v, p;
  9676. ensureSafeMemberName(i, parser.text);
  9677. if (!o) return undefined;
  9678. v = ensureSafeObject(o[i], parser.text);
  9679. if (v && v.then && parser.options.unwrapPromises) {
  9680. p = v;
  9681. if (!('$$v' in v)) {
  9682. p.$$v = undefined;
  9683. p.then(function(val) { p.$$v = val; });
  9684. }
  9685. v = v.$$v;
  9686. }
  9687. return v;
  9688. }, {
  9689. assign: function(self, value, locals) {
  9690. var key = indexFn(self, locals);
  9691. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  9692. var safe = ensureSafeObject(obj(self, locals), parser.text);
  9693. return safe[key] = value;
  9694. }
  9695. });
  9696. },
  9697. functionCall: function(fn, contextGetter) {
  9698. var argsFn = [];
  9699. if (this.peekToken().text !== ')') {
  9700. do {
  9701. argsFn.push(this.expression());
  9702. } while (this.expect(','));
  9703. }
  9704. this.consume(')');
  9705. var parser = this;
  9706. return function(scope, locals) {
  9707. var args = [];
  9708. var context = contextGetter ? contextGetter(scope, locals) : scope;
  9709. for (var i = 0; i < argsFn.length; i++) {
  9710. args.push(argsFn[i](scope, locals));
  9711. }
  9712. var fnPtr = fn(scope, locals, context) || noop;
  9713. ensureSafeObject(context, parser.text);
  9714. ensureSafeFunction(fnPtr, parser.text);
  9715. // IE stupidity! (IE doesn't have apply for some native functions)
  9716. var v = fnPtr.apply
  9717. ? fnPtr.apply(context, args)
  9718. : fnPtr(args[0], args[1], args[2], args[3], args[4]);
  9719. return ensureSafeObject(v, parser.text);
  9720. };
  9721. },
  9722. // This is used with json array declaration
  9723. arrayDeclaration: function () {
  9724. var elementFns = [];
  9725. var allConstant = true;
  9726. if (this.peekToken().text !== ']') {
  9727. do {
  9728. if (this.peek(']')) {
  9729. // Support trailing commas per ES5.1.
  9730. break;
  9731. }
  9732. var elementFn = this.expression();
  9733. elementFns.push(elementFn);
  9734. if (!elementFn.constant) {
  9735. allConstant = false;
  9736. }
  9737. } while (this.expect(','));
  9738. }
  9739. this.consume(']');
  9740. return extend(function(self, locals) {
  9741. var array = [];
  9742. for (var i = 0; i < elementFns.length; i++) {
  9743. array.push(elementFns[i](self, locals));
  9744. }
  9745. return array;
  9746. }, {
  9747. literal: true,
  9748. constant: allConstant
  9749. });
  9750. },
  9751. object: function () {
  9752. var keyValues = [];
  9753. var allConstant = true;
  9754. if (this.peekToken().text !== '}') {
  9755. do {
  9756. if (this.peek('}')) {
  9757. // Support trailing commas per ES5.1.
  9758. break;
  9759. }
  9760. var token = this.expect(),
  9761. key = token.string || token.text;
  9762. this.consume(':');
  9763. var value = this.expression();
  9764. keyValues.push({key: key, value: value});
  9765. if (!value.constant) {
  9766. allConstant = false;
  9767. }
  9768. } while (this.expect(','));
  9769. }
  9770. this.consume('}');
  9771. return extend(function(self, locals) {
  9772. var object = {};
  9773. for (var i = 0; i < keyValues.length; i++) {
  9774. var keyValue = keyValues[i];
  9775. object[keyValue.key] = keyValue.value(self, locals);
  9776. }
  9777. return object;
  9778. }, {
  9779. literal: true,
  9780. constant: allConstant
  9781. });
  9782. }
  9783. };
  9784. //////////////////////////////////////////////////
  9785. // Parser helper functions
  9786. //////////////////////////////////////////////////
  9787. function setter(obj, path, setValue, fullExp, options) {
  9788. //needed?
  9789. options = options || {};
  9790. var element = path.split('.'), key;
  9791. for (var i = 0; element.length > 1; i++) {
  9792. key = ensureSafeMemberName(element.shift(), fullExp);
  9793. var propertyObj = obj[key];
  9794. if (!propertyObj) {
  9795. propertyObj = {};
  9796. obj[key] = propertyObj;
  9797. }
  9798. obj = propertyObj;
  9799. if (obj.then && options.unwrapPromises) {
  9800. promiseWarning(fullExp);
  9801. if (!("$$v" in obj)) {
  9802. (function(promise) {
  9803. promise.then(function(val) { promise.$$v = val; }); }
  9804. )(obj);
  9805. }
  9806. if (obj.$$v === undefined) {
  9807. obj.$$v = {};
  9808. }
  9809. obj = obj.$$v;
  9810. }
  9811. }
  9812. key = ensureSafeMemberName(element.shift(), fullExp);
  9813. ensureSafeObject(obj, fullExp);
  9814. ensureSafeObject(obj[key], fullExp);
  9815. obj[key] = setValue;
  9816. return setValue;
  9817. }
  9818. var getterFnCache = {};
  9819. /**
  9820. * Implementation of the "Black Hole" variant from:
  9821. * - http://jsperf.com/angularjs-parse-getter/4
  9822. * - http://jsperf.com/path-evaluation-simplified/7
  9823. */
  9824. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
  9825. ensureSafeMemberName(key0, fullExp);
  9826. ensureSafeMemberName(key1, fullExp);
  9827. ensureSafeMemberName(key2, fullExp);
  9828. ensureSafeMemberName(key3, fullExp);
  9829. ensureSafeMemberName(key4, fullExp);
  9830. return !options.unwrapPromises
  9831. ? function cspSafeGetter(scope, locals) {
  9832. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  9833. if (pathVal == null) return pathVal;
  9834. pathVal = pathVal[key0];
  9835. if (!key1) return pathVal;
  9836. if (pathVal == null) return undefined;
  9837. pathVal = pathVal[key1];
  9838. if (!key2) return pathVal;
  9839. if (pathVal == null) return undefined;
  9840. pathVal = pathVal[key2];
  9841. if (!key3) return pathVal;
  9842. if (pathVal == null) return undefined;
  9843. pathVal = pathVal[key3];
  9844. if (!key4) return pathVal;
  9845. if (pathVal == null) return undefined;
  9846. pathVal = pathVal[key4];
  9847. return pathVal;
  9848. }
  9849. : function cspSafePromiseEnabledGetter(scope, locals) {
  9850. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
  9851. promise;
  9852. if (pathVal == null) return pathVal;
  9853. pathVal = pathVal[key0];
  9854. if (pathVal && pathVal.then) {
  9855. promiseWarning(fullExp);
  9856. if (!("$$v" in pathVal)) {
  9857. promise = pathVal;
  9858. promise.$$v = undefined;
  9859. promise.then(function(val) { promise.$$v = val; });
  9860. }
  9861. pathVal = pathVal.$$v;
  9862. }
  9863. if (!key1) return pathVal;
  9864. if (pathVal == null) return undefined;
  9865. pathVal = pathVal[key1];
  9866. if (pathVal && pathVal.then) {
  9867. promiseWarning(fullExp);
  9868. if (!("$$v" in pathVal)) {
  9869. promise = pathVal;
  9870. promise.$$v = undefined;
  9871. promise.then(function(val) { promise.$$v = val; });
  9872. }
  9873. pathVal = pathVal.$$v;
  9874. }
  9875. if (!key2) return pathVal;
  9876. if (pathVal == null) return undefined;
  9877. pathVal = pathVal[key2];
  9878. if (pathVal && pathVal.then) {
  9879. promiseWarning(fullExp);
  9880. if (!("$$v" in pathVal)) {
  9881. promise = pathVal;
  9882. promise.$$v = undefined;
  9883. promise.then(function(val) { promise.$$v = val; });
  9884. }
  9885. pathVal = pathVal.$$v;
  9886. }
  9887. if (!key3) return pathVal;
  9888. if (pathVal == null) return undefined;
  9889. pathVal = pathVal[key3];
  9890. if (pathVal && pathVal.then) {
  9891. promiseWarning(fullExp);
  9892. if (!("$$v" in pathVal)) {
  9893. promise = pathVal;
  9894. promise.$$v = undefined;
  9895. promise.then(function(val) { promise.$$v = val; });
  9896. }
  9897. pathVal = pathVal.$$v;
  9898. }
  9899. if (!key4) return pathVal;
  9900. if (pathVal == null) return undefined;
  9901. pathVal = pathVal[key4];
  9902. if (pathVal && pathVal.then) {
  9903. promiseWarning(fullExp);
  9904. if (!("$$v" in pathVal)) {
  9905. promise = pathVal;
  9906. promise.$$v = undefined;
  9907. promise.then(function(val) { promise.$$v = val; });
  9908. }
  9909. pathVal = pathVal.$$v;
  9910. }
  9911. return pathVal;
  9912. };
  9913. }
  9914. function getterFn(path, options, fullExp) {
  9915. // Check whether the cache has this getter already.
  9916. // We can use hasOwnProperty directly on the cache because we ensure,
  9917. // see below, that the cache never stores a path called 'hasOwnProperty'
  9918. if (getterFnCache.hasOwnProperty(path)) {
  9919. return getterFnCache[path];
  9920. }
  9921. var pathKeys = path.split('.'),
  9922. pathKeysLength = pathKeys.length,
  9923. fn;
  9924. // http://jsperf.com/angularjs-parse-getter/6
  9925. if (options.csp) {
  9926. if (pathKeysLength < 6) {
  9927. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
  9928. options);
  9929. } else {
  9930. fn = function(scope, locals) {
  9931. var i = 0, val;
  9932. do {
  9933. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  9934. pathKeys[i++], fullExp, options)(scope, locals);
  9935. locals = undefined; // clear after first iteration
  9936. scope = val;
  9937. } while (i < pathKeysLength);
  9938. return val;
  9939. };
  9940. }
  9941. } else {
  9942. var code = 'var p;\n';
  9943. forEach(pathKeys, function(key, index) {
  9944. ensureSafeMemberName(key, fullExp);
  9945. code += 'if(s == null) return undefined;\n' +
  9946. 's='+ (index
  9947. // we simply dereference 's' on any .dot notation
  9948. ? 's'
  9949. // but if we are first then we check locals first, and if so read it first
  9950. : '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
  9951. (options.unwrapPromises
  9952. ? 'if (s && s.then) {\n' +
  9953. ' pw("' + fullExp.replace(/(["\r\n])/g, '\\$1') + '");\n' +
  9954. ' if (!("$$v" in s)) {\n' +
  9955. ' p=s;\n' +
  9956. ' p.$$v = undefined;\n' +
  9957. ' p.then(function(v) {p.$$v=v;});\n' +
  9958. '}\n' +
  9959. ' s=s.$$v\n' +
  9960. '}\n'
  9961. : '');
  9962. });
  9963. code += 'return s;';
  9964. /* jshint -W054 */
  9965. var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
  9966. /* jshint +W054 */
  9967. evaledFnGetter.toString = valueFn(code);
  9968. fn = options.unwrapPromises ? function(scope, locals) {
  9969. return evaledFnGetter(scope, locals, promiseWarning);
  9970. } : evaledFnGetter;
  9971. }
  9972. // Only cache the value if it's not going to mess up the cache object
  9973. // This is more performant that using Object.prototype.hasOwnProperty.call
  9974. if (path !== 'hasOwnProperty') {
  9975. getterFnCache[path] = fn;
  9976. }
  9977. return fn;
  9978. }
  9979. ///////////////////////////////////
  9980. /**
  9981. * @ngdoc service
  9982. * @name $parse
  9983. * @kind function
  9984. *
  9985. * @description
  9986. *
  9987. * Converts Angular {@link guide/expression expression} into a function.
  9988. *
  9989. * ```js
  9990. * var getter = $parse('user.name');
  9991. * var setter = getter.assign;
  9992. * var context = {user:{name:'angular'}};
  9993. * var locals = {user:{name:'local'}};
  9994. *
  9995. * expect(getter(context)).toEqual('angular');
  9996. * setter(context, 'newValue');
  9997. * expect(context.user.name).toEqual('newValue');
  9998. * expect(getter(context, locals)).toEqual('local');
  9999. * ```
  10000. *
  10001. *
  10002. * @param {string} expression String expression to compile.
  10003. * @returns {function(context, locals)} a function which represents the compiled expression:
  10004. *
  10005. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  10006. * are evaluated against (typically a scope object).
  10007. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  10008. * `context`.
  10009. *
  10010. * The returned function also has the following properties:
  10011. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  10012. * literal.
  10013. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  10014. * constant literals.
  10015. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  10016. * set to a function to change its value on the given context.
  10017. *
  10018. */
  10019. /**
  10020. * @ngdoc provider
  10021. * @name $parseProvider
  10022. * @kind function
  10023. *
  10024. * @description
  10025. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  10026. * service.
  10027. */
  10028. function $ParseProvider() {
  10029. var cache = {};
  10030. var $parseOptions = {
  10031. csp: false,
  10032. unwrapPromises: false,
  10033. logPromiseWarnings: true
  10034. };
  10035. /**
  10036. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  10037. *
  10038. * @ngdoc method
  10039. * @name $parseProvider#unwrapPromises
  10040. * @description
  10041. *
  10042. * **This feature is deprecated, see deprecation notes below for more info**
  10043. *
  10044. * If set to true (default is false), $parse will unwrap promises automatically when a promise is
  10045. * found at any part of the expression. In other words, if set to true, the expression will always
  10046. * result in a non-promise value.
  10047. *
  10048. * While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
  10049. * the fulfillment value is used in place of the promise while evaluating the expression.
  10050. *
  10051. * **Deprecation notice**
  10052. *
  10053. * This is a feature that didn't prove to be wildly useful or popular, primarily because of the
  10054. * dichotomy between data access in templates (accessed as raw values) and controller code
  10055. * (accessed as promises).
  10056. *
  10057. * In most code we ended up resolving promises manually in controllers anyway and thus unifying
  10058. * the model access there.
  10059. *
  10060. * Other downsides of automatic promise unwrapping:
  10061. *
  10062. * - when building components it's often desirable to receive the raw promises
  10063. * - adds complexity and slows down expression evaluation
  10064. * - makes expression code pre-generation unattractive due to the amount of code that needs to be
  10065. * generated
  10066. * - makes IDE auto-completion and tool support hard
  10067. *
  10068. * **Warning Logs**
  10069. *
  10070. * If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
  10071. * promise (to reduce the noise, each expression is logged only once). To disable this logging use
  10072. * `$parseProvider.logPromiseWarnings(false)` api.
  10073. *
  10074. *
  10075. * @param {boolean=} value New value.
  10076. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  10077. * setter.
  10078. */
  10079. this.unwrapPromises = function(value) {
  10080. if (isDefined(value)) {
  10081. $parseOptions.unwrapPromises = !!value;
  10082. return this;
  10083. } else {
  10084. return $parseOptions.unwrapPromises;
  10085. }
  10086. };
  10087. /**
  10088. * @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
  10089. *
  10090. * @ngdoc method
  10091. * @name $parseProvider#logPromiseWarnings
  10092. * @description
  10093. *
  10094. * Controls whether Angular should log a warning on any encounter of a promise in an expression.
  10095. *
  10096. * The default is set to `true`.
  10097. *
  10098. * This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
  10099. *
  10100. * @param {boolean=} value New value.
  10101. * @returns {boolean|self} Returns the current setting when used as getter and self if used as
  10102. * setter.
  10103. */
  10104. this.logPromiseWarnings = function(value) {
  10105. if (isDefined(value)) {
  10106. $parseOptions.logPromiseWarnings = value;
  10107. return this;
  10108. } else {
  10109. return $parseOptions.logPromiseWarnings;
  10110. }
  10111. };
  10112. this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
  10113. $parseOptions.csp = $sniffer.csp;
  10114. promiseWarning = function promiseWarningFn(fullExp) {
  10115. if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
  10116. promiseWarningCache[fullExp] = true;
  10117. $log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
  10118. 'Automatic unwrapping of promises in Angular expressions is deprecated.');
  10119. };
  10120. return function(exp) {
  10121. var parsedExpression;
  10122. switch (typeof exp) {
  10123. case 'string':
  10124. if (cache.hasOwnProperty(exp)) {
  10125. return cache[exp];
  10126. }
  10127. var lexer = new Lexer($parseOptions);
  10128. var parser = new Parser(lexer, $filter, $parseOptions);
  10129. parsedExpression = parser.parse(exp);
  10130. if (exp !== 'hasOwnProperty') {
  10131. // Only cache the value if it's not going to mess up the cache object
  10132. // This is more performant that using Object.prototype.hasOwnProperty.call
  10133. cache[exp] = parsedExpression;
  10134. }
  10135. return parsedExpression;
  10136. case 'function':
  10137. return exp;
  10138. default:
  10139. return noop;
  10140. }
  10141. };
  10142. }];
  10143. }
  10144. /**
  10145. * @ngdoc service
  10146. * @name $q
  10147. * @requires $rootScope
  10148. *
  10149. * @description
  10150. * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  10151. *
  10152. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  10153. * interface for interacting with an object that represents the result of an action that is
  10154. * performed asynchronously, and may or may not be finished at any given point in time.
  10155. *
  10156. * From the perspective of dealing with error handling, deferred and promise APIs are to
  10157. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  10158. *
  10159. * ```js
  10160. * // for the purpose of this example let's assume that variables `$q`, `scope` and `okToGreet`
  10161. * // are available in the current lexical scope (they could have been injected or passed in).
  10162. *
  10163. * function asyncGreet(name) {
  10164. * var deferred = $q.defer();
  10165. *
  10166. * setTimeout(function() {
  10167. * deferred.notify('About to greet ' + name + '.');
  10168. *
  10169. * if (okToGreet(name)) {
  10170. * deferred.resolve('Hello, ' + name + '!');
  10171. * } else {
  10172. * deferred.reject('Greeting ' + name + ' is not allowed.');
  10173. * }
  10174. * }, 1000);
  10175. *
  10176. * return deferred.promise;
  10177. * }
  10178. *
  10179. * var promise = asyncGreet('Robin Hood');
  10180. * promise.then(function(greeting) {
  10181. * alert('Success: ' + greeting);
  10182. * }, function(reason) {
  10183. * alert('Failed: ' + reason);
  10184. * }, function(update) {
  10185. * alert('Got notification: ' + update);
  10186. * });
  10187. * ```
  10188. *
  10189. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  10190. * comes in the way of guarantees that promise and deferred APIs make, see
  10191. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  10192. *
  10193. * Additionally the promise api allows for composition that is very hard to do with the
  10194. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  10195. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  10196. * section on serial or parallel joining of promises.
  10197. *
  10198. *
  10199. * # The Deferred API
  10200. *
  10201. * A new instance of deferred is constructed by calling `$q.defer()`.
  10202. *
  10203. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  10204. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  10205. * of the task.
  10206. *
  10207. * **Methods**
  10208. *
  10209. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  10210. * constructed via `$q.reject`, the promise will be rejected instead.
  10211. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  10212. * resolving it with a rejection constructed via `$q.reject`.
  10213. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  10214. * multiple times before the promise is either resolved or rejected.
  10215. *
  10216. * **Properties**
  10217. *
  10218. * - promise – `{Promise}` – promise object associated with this deferred.
  10219. *
  10220. *
  10221. * # The Promise API
  10222. *
  10223. * A new promise instance is created when a deferred instance is created and can be retrieved by
  10224. * calling `deferred.promise`.
  10225. *
  10226. * The purpose of the promise object is to allow for interested parties to get access to the result
  10227. * of the deferred task when it completes.
  10228. *
  10229. * **Methods**
  10230. *
  10231. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  10232. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  10233. * as soon as the result is available. The callbacks are called with a single argument: the result
  10234. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  10235. * provide a progress indication, before the promise is resolved or rejected.
  10236. *
  10237. * This method *returns a new promise* which is resolved or rejected via the return value of the
  10238. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  10239. * `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
  10240. * method.
  10241. *
  10242. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  10243. *
  10244. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  10245. * but to do so without modifying the final value. This is useful to release resources or do some
  10246. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  10247. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  10248. * more information.
  10249. *
  10250. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  10251. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  10252. * make your code IE8 and Android 2.x compatible.
  10253. *
  10254. * # Chaining promises
  10255. *
  10256. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  10257. * possible to create a chain of promises:
  10258. *
  10259. * ```js
  10260. * promiseB = promiseA.then(function(result) {
  10261. * return result + 1;
  10262. * });
  10263. *
  10264. * // promiseB will be resolved immediately after promiseA is resolved and its value
  10265. * // will be the result of promiseA incremented by 1
  10266. * ```
  10267. *
  10268. * It is possible to create chains of any length and since a promise can be resolved with another
  10269. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  10270. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  10271. * $http's response interceptors.
  10272. *
  10273. *
  10274. * # Differences between Kris Kowal's Q and $q
  10275. *
  10276. * There are two main differences:
  10277. *
  10278. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  10279. * mechanism in angular, which means faster propagation of resolution or rejection into your
  10280. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  10281. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  10282. * all the important functionality needed for common async tasks.
  10283. *
  10284. * # Testing
  10285. *
  10286. * ```js
  10287. * it('should simulate promise', inject(function($q, $rootScope) {
  10288. * var deferred = $q.defer();
  10289. * var promise = deferred.promise;
  10290. * var resolvedValue;
  10291. *
  10292. * promise.then(function(value) { resolvedValue = value; });
  10293. * expect(resolvedValue).toBeUndefined();
  10294. *
  10295. * // Simulate resolving of promise
  10296. * deferred.resolve(123);
  10297. * // Note that the 'then' function does not get called synchronously.
  10298. * // This is because we want the promise API to always be async, whether or not
  10299. * // it got called synchronously or asynchronously.
  10300. * expect(resolvedValue).toBeUndefined();
  10301. *
  10302. * // Propagate promise resolution to 'then' functions using $apply().
  10303. * $rootScope.$apply();
  10304. * expect(resolvedValue).toEqual(123);
  10305. * }));
  10306. * ```
  10307. */
  10308. function $QProvider() {
  10309. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  10310. return qFactory(function(callback) {
  10311. $rootScope.$evalAsync(callback);
  10312. }, $exceptionHandler);
  10313. }];
  10314. }
  10315. /**
  10316. * Constructs a promise manager.
  10317. *
  10318. * @param {function(Function)} nextTick Function for executing functions in the next turn.
  10319. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  10320. * debugging purposes.
  10321. * @returns {object} Promise manager.
  10322. */
  10323. function qFactory(nextTick, exceptionHandler) {
  10324. /**
  10325. * @ngdoc method
  10326. * @name $q#defer
  10327. * @kind function
  10328. *
  10329. * @description
  10330. * Creates a `Deferred` object which represents a task which will finish in the future.
  10331. *
  10332. * @returns {Deferred} Returns a new instance of deferred.
  10333. */
  10334. var defer = function() {
  10335. var pending = [],
  10336. value, deferred;
  10337. deferred = {
  10338. resolve: function(val) {
  10339. if (pending) {
  10340. var callbacks = pending;
  10341. pending = undefined;
  10342. value = ref(val);
  10343. if (callbacks.length) {
  10344. nextTick(function() {
  10345. var callback;
  10346. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10347. callback = callbacks[i];
  10348. value.then(callback[0], callback[1], callback[2]);
  10349. }
  10350. });
  10351. }
  10352. }
  10353. },
  10354. reject: function(reason) {
  10355. deferred.resolve(createInternalRejectedPromise(reason));
  10356. },
  10357. notify: function(progress) {
  10358. if (pending) {
  10359. var callbacks = pending;
  10360. if (pending.length) {
  10361. nextTick(function() {
  10362. var callback;
  10363. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  10364. callback = callbacks[i];
  10365. callback[2](progress);
  10366. }
  10367. });
  10368. }
  10369. }
  10370. },
  10371. promise: {
  10372. then: function(callback, errback, progressback) {
  10373. var result = defer();
  10374. var wrappedCallback = function(value) {
  10375. try {
  10376. result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
  10377. } catch(e) {
  10378. result.reject(e);
  10379. exceptionHandler(e);
  10380. }
  10381. };
  10382. var wrappedErrback = function(reason) {
  10383. try {
  10384. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10385. } catch(e) {
  10386. result.reject(e);
  10387. exceptionHandler(e);
  10388. }
  10389. };
  10390. var wrappedProgressback = function(progress) {
  10391. try {
  10392. result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
  10393. } catch(e) {
  10394. exceptionHandler(e);
  10395. }
  10396. };
  10397. if (pending) {
  10398. pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
  10399. } else {
  10400. value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
  10401. }
  10402. return result.promise;
  10403. },
  10404. "catch": function(callback) {
  10405. return this.then(null, callback);
  10406. },
  10407. "finally": function(callback) {
  10408. function makePromise(value, resolved) {
  10409. var result = defer();
  10410. if (resolved) {
  10411. result.resolve(value);
  10412. } else {
  10413. result.reject(value);
  10414. }
  10415. return result.promise;
  10416. }
  10417. function handleCallback(value, isResolved) {
  10418. var callbackOutput = null;
  10419. try {
  10420. callbackOutput = (callback ||defaultCallback)();
  10421. } catch(e) {
  10422. return makePromise(e, false);
  10423. }
  10424. if (isPromiseLike(callbackOutput)) {
  10425. return callbackOutput.then(function() {
  10426. return makePromise(value, isResolved);
  10427. }, function(error) {
  10428. return makePromise(error, false);
  10429. });
  10430. } else {
  10431. return makePromise(value, isResolved);
  10432. }
  10433. }
  10434. return this.then(function(value) {
  10435. return handleCallback(value, true);
  10436. }, function(error) {
  10437. return handleCallback(error, false);
  10438. });
  10439. }
  10440. }
  10441. };
  10442. return deferred;
  10443. };
  10444. var ref = function(value) {
  10445. if (isPromiseLike(value)) return value;
  10446. return {
  10447. then: function(callback) {
  10448. var result = defer();
  10449. nextTick(function() {
  10450. result.resolve(callback(value));
  10451. });
  10452. return result.promise;
  10453. }
  10454. };
  10455. };
  10456. /**
  10457. * @ngdoc method
  10458. * @name $q#reject
  10459. * @kind function
  10460. *
  10461. * @description
  10462. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  10463. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  10464. * a promise chain, you don't need to worry about it.
  10465. *
  10466. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  10467. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  10468. * a promise error callback and you want to forward the error to the promise derived from the
  10469. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  10470. * `reject`.
  10471. *
  10472. * ```js
  10473. * promiseB = promiseA.then(function(result) {
  10474. * // success: do something and resolve promiseB
  10475. * // with the old or a new result
  10476. * return result;
  10477. * }, function(reason) {
  10478. * // error: handle the error if possible and
  10479. * // resolve promiseB with newPromiseOrValue,
  10480. * // otherwise forward the rejection to promiseB
  10481. * if (canHandle(reason)) {
  10482. * // handle the error and recover
  10483. * return newPromiseOrValue;
  10484. * }
  10485. * return $q.reject(reason);
  10486. * });
  10487. * ```
  10488. *
  10489. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  10490. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  10491. */
  10492. var reject = function(reason) {
  10493. var result = defer();
  10494. result.reject(reason);
  10495. return result.promise;
  10496. };
  10497. var createInternalRejectedPromise = function(reason) {
  10498. return {
  10499. then: function(callback, errback) {
  10500. var result = defer();
  10501. nextTick(function() {
  10502. try {
  10503. result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
  10504. } catch(e) {
  10505. result.reject(e);
  10506. exceptionHandler(e);
  10507. }
  10508. });
  10509. return result.promise;
  10510. }
  10511. };
  10512. };
  10513. /**
  10514. * @ngdoc method
  10515. * @name $q#when
  10516. * @kind function
  10517. *
  10518. * @description
  10519. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  10520. * This is useful when you are dealing with an object that might or might not be a promise, or if
  10521. * the promise comes from a source that can't be trusted.
  10522. *
  10523. * @param {*} value Value or a promise
  10524. * @returns {Promise} Returns a promise of the passed value or promise
  10525. */
  10526. var when = function(value, callback, errback, progressback) {
  10527. var result = defer(),
  10528. done;
  10529. var wrappedCallback = function(value) {
  10530. try {
  10531. return (isFunction(callback) ? callback : defaultCallback)(value);
  10532. } catch (e) {
  10533. exceptionHandler(e);
  10534. return reject(e);
  10535. }
  10536. };
  10537. var wrappedErrback = function(reason) {
  10538. try {
  10539. return (isFunction(errback) ? errback : defaultErrback)(reason);
  10540. } catch (e) {
  10541. exceptionHandler(e);
  10542. return reject(e);
  10543. }
  10544. };
  10545. var wrappedProgressback = function(progress) {
  10546. try {
  10547. return (isFunction(progressback) ? progressback : defaultCallback)(progress);
  10548. } catch (e) {
  10549. exceptionHandler(e);
  10550. }
  10551. };
  10552. nextTick(function() {
  10553. ref(value).then(function(value) {
  10554. if (done) return;
  10555. done = true;
  10556. result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
  10557. }, function(reason) {
  10558. if (done) return;
  10559. done = true;
  10560. result.resolve(wrappedErrback(reason));
  10561. }, function(progress) {
  10562. if (done) return;
  10563. result.notify(wrappedProgressback(progress));
  10564. });
  10565. });
  10566. return result.promise;
  10567. };
  10568. function defaultCallback(value) {
  10569. return value;
  10570. }
  10571. function defaultErrback(reason) {
  10572. return reject(reason);
  10573. }
  10574. /**
  10575. * @ngdoc method
  10576. * @name $q#all
  10577. * @kind function
  10578. *
  10579. * @description
  10580. * Combines multiple promises into a single promise that is resolved when all of the input
  10581. * promises are resolved.
  10582. *
  10583. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  10584. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  10585. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  10586. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  10587. * with the same rejection value.
  10588. */
  10589. function all(promises) {
  10590. var deferred = defer(),
  10591. counter = 0,
  10592. results = isArray(promises) ? [] : {};
  10593. forEach(promises, function(promise, key) {
  10594. counter++;
  10595. ref(promise).then(function(value) {
  10596. if (results.hasOwnProperty(key)) return;
  10597. results[key] = value;
  10598. if (!(--counter)) deferred.resolve(results);
  10599. }, function(reason) {
  10600. if (results.hasOwnProperty(key)) return;
  10601. deferred.reject(reason);
  10602. });
  10603. });
  10604. if (counter === 0) {
  10605. deferred.resolve(results);
  10606. }
  10607. return deferred.promise;
  10608. }
  10609. return {
  10610. defer: defer,
  10611. reject: reject,
  10612. when: when,
  10613. all: all
  10614. };
  10615. }
  10616. function $$RAFProvider(){ //rAF
  10617. this.$get = ['$window', '$timeout', function($window, $timeout) {
  10618. var requestAnimationFrame = $window.requestAnimationFrame ||
  10619. $window.webkitRequestAnimationFrame ||
  10620. $window.mozRequestAnimationFrame;
  10621. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  10622. $window.webkitCancelAnimationFrame ||
  10623. $window.mozCancelAnimationFrame ||
  10624. $window.webkitCancelRequestAnimationFrame;
  10625. var rafSupported = !!requestAnimationFrame;
  10626. var raf = rafSupported
  10627. ? function(fn) {
  10628. var id = requestAnimationFrame(fn);
  10629. return function() {
  10630. cancelAnimationFrame(id);
  10631. };
  10632. }
  10633. : function(fn) {
  10634. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  10635. return function() {
  10636. $timeout.cancel(timer);
  10637. };
  10638. };
  10639. raf.supported = rafSupported;
  10640. return raf;
  10641. }];
  10642. }
  10643. /**
  10644. * DESIGN NOTES
  10645. *
  10646. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  10647. *
  10648. * The typical use of scope is to watch the expressions, which most of the time return the same
  10649. * value as last time so we optimize the operation.
  10650. *
  10651. * Closures construction is expensive in terms of speed as well as memory:
  10652. * - No closures, instead use prototypical inheritance for API
  10653. * - Internal state needs to be stored on scope directly, which means that private state is
  10654. * exposed as $$____ properties
  10655. *
  10656. * Loop operations are optimized by using while(count--) { ... }
  10657. * - this means that in order to keep the same order of execution as addition we have to add
  10658. * items to the array at the beginning (unshift) instead of at the end (push)
  10659. *
  10660. * Child scopes are created and removed often
  10661. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  10662. *
  10663. * There are few watches then a lot of observers. This is why you don't want the observer to be
  10664. * implemented in the same way as watch. Watch requires return of initialization function which
  10665. * are expensive to construct.
  10666. */
  10667. /**
  10668. * @ngdoc provider
  10669. * @name $rootScopeProvider
  10670. * @description
  10671. *
  10672. * Provider for the $rootScope service.
  10673. */
  10674. /**
  10675. * @ngdoc method
  10676. * @name $rootScopeProvider#digestTtl
  10677. * @description
  10678. *
  10679. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  10680. * assuming that the model is unstable.
  10681. *
  10682. * The current default is 10 iterations.
  10683. *
  10684. * In complex applications it's possible that the dependencies between `$watch`s will result in
  10685. * several digest iterations. However if an application needs more than the default 10 digest
  10686. * iterations for its model to stabilize then you should investigate what is causing the model to
  10687. * continuously change during the digest.
  10688. *
  10689. * Increasing the TTL could have performance implications, so you should not change it without
  10690. * proper justification.
  10691. *
  10692. * @param {number} limit The number of digest iterations.
  10693. */
  10694. /**
  10695. * @ngdoc service
  10696. * @name $rootScope
  10697. * @description
  10698. *
  10699. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  10700. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  10701. * between the model and the view, via a mechanism for watching the model for changes.
  10702. * They also provide an event emission/broadcast and subscription facility. See the
  10703. * {@link guide/scope developer guide on scopes}.
  10704. */
  10705. function $RootScopeProvider(){
  10706. var TTL = 10;
  10707. var $rootScopeMinErr = minErr('$rootScope');
  10708. var lastDirtyWatch = null;
  10709. this.digestTtl = function(value) {
  10710. if (arguments.length) {
  10711. TTL = value;
  10712. }
  10713. return TTL;
  10714. };
  10715. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  10716. function( $injector, $exceptionHandler, $parse, $browser) {
  10717. /**
  10718. * @ngdoc type
  10719. * @name $rootScope.Scope
  10720. *
  10721. * @description
  10722. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  10723. * {@link auto.$injector $injector}. Child scopes are created using the
  10724. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  10725. * compiled HTML template is executed.)
  10726. *
  10727. * Here is a simple scope snippet to show how you can interact with the scope.
  10728. * ```html
  10729. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  10730. * ```
  10731. *
  10732. * # Inheritance
  10733. * A scope can inherit from a parent scope, as in this example:
  10734. * ```js
  10735. var parent = $rootScope;
  10736. var child = parent.$new();
  10737. parent.salutation = "Hello";
  10738. child.name = "World";
  10739. expect(child.salutation).toEqual('Hello');
  10740. child.salutation = "Welcome";
  10741. expect(child.salutation).toEqual('Welcome');
  10742. expect(parent.salutation).toEqual('Hello');
  10743. * ```
  10744. *
  10745. *
  10746. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  10747. * provided for the current scope. Defaults to {@link ng}.
  10748. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  10749. * append/override services provided by `providers`. This is handy
  10750. * when unit-testing and having the need to override a default
  10751. * service.
  10752. * @returns {Object} Newly created scope.
  10753. *
  10754. */
  10755. function Scope() {
  10756. this.$id = nextUid();
  10757. this.$$phase = this.$parent = this.$$watchers =
  10758. this.$$nextSibling = this.$$prevSibling =
  10759. this.$$childHead = this.$$childTail = null;
  10760. this['this'] = this.$root = this;
  10761. this.$$destroyed = false;
  10762. this.$$asyncQueue = [];
  10763. this.$$postDigestQueue = [];
  10764. this.$$listeners = {};
  10765. this.$$listenerCount = {};
  10766. this.$$isolateBindings = {};
  10767. }
  10768. /**
  10769. * @ngdoc property
  10770. * @name $rootScope.Scope#$id
  10771. * @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
  10772. * debugging.
  10773. */
  10774. Scope.prototype = {
  10775. constructor: Scope,
  10776. /**
  10777. * @ngdoc method
  10778. * @name $rootScope.Scope#$new
  10779. * @kind function
  10780. *
  10781. * @description
  10782. * Creates a new child {@link ng.$rootScope.Scope scope}.
  10783. *
  10784. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
  10785. * {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the
  10786. * scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  10787. *
  10788. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  10789. * desired for the scope and its child scopes to be permanently detached from the parent and
  10790. * thus stop participating in model change detection and listener notification by invoking.
  10791. *
  10792. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  10793. * parent scope. The scope is isolated, as it can not see parent scope properties.
  10794. * When creating widgets, it is useful for the widget to not accidentally read parent
  10795. * state.
  10796. *
  10797. * @returns {Object} The newly created child scope.
  10798. *
  10799. */
  10800. $new: function(isolate) {
  10801. var ChildScope,
  10802. child;
  10803. if (isolate) {
  10804. child = new Scope();
  10805. child.$root = this.$root;
  10806. // ensure that there is just one async queue per $rootScope and its children
  10807. child.$$asyncQueue = this.$$asyncQueue;
  10808. child.$$postDigestQueue = this.$$postDigestQueue;
  10809. } else {
  10810. // Only create a child scope class if somebody asks for one,
  10811. // but cache it to allow the VM to optimize lookups.
  10812. if (!this.$$childScopeClass) {
  10813. this.$$childScopeClass = function() {
  10814. this.$$watchers = this.$$nextSibling =
  10815. this.$$childHead = this.$$childTail = null;
  10816. this.$$listeners = {};
  10817. this.$$listenerCount = {};
  10818. this.$id = nextUid();
  10819. this.$$childScopeClass = null;
  10820. };
  10821. this.$$childScopeClass.prototype = this;
  10822. }
  10823. child = new this.$$childScopeClass();
  10824. }
  10825. child['this'] = child;
  10826. child.$parent = this;
  10827. child.$$prevSibling = this.$$childTail;
  10828. if (this.$$childHead) {
  10829. this.$$childTail.$$nextSibling = child;
  10830. this.$$childTail = child;
  10831. } else {
  10832. this.$$childHead = this.$$childTail = child;
  10833. }
  10834. return child;
  10835. },
  10836. /**
  10837. * @ngdoc method
  10838. * @name $rootScope.Scope#$watch
  10839. * @kind function
  10840. *
  10841. * @description
  10842. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  10843. *
  10844. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  10845. * $digest()} and should return the value that will be watched. (Since
  10846. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  10847. * `watchExpression` can execute multiple times per
  10848. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  10849. * - The `listener` is called only when the value from the current `watchExpression` and the
  10850. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  10851. * see below). Inequality is determined according to reference inequality,
  10852. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  10853. * via the `!==` Javascript operator, unless `objectEquality == true`
  10854. * (see next point)
  10855. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  10856. * according to the {@link angular.equals} function. To save the value of the object for
  10857. * later comparison, the {@link angular.copy} function is used. This therefore means that
  10858. * watching complex objects will have adverse memory and performance implications.
  10859. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  10860. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  10861. * iteration limit is 10 to prevent an infinite loop deadlock.
  10862. *
  10863. *
  10864. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  10865. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  10866. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  10867. * change is detected, be prepared for multiple calls to your listener.)
  10868. *
  10869. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  10870. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  10871. * watcher. In rare cases, this is undesirable because the listener is called when the result
  10872. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  10873. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  10874. * listener was called due to initialization.
  10875. *
  10876. * The example below contains an illustration of using a function as your $watch listener
  10877. *
  10878. *
  10879. * # Example
  10880. * ```js
  10881. // let's assume that scope was dependency injected as the $rootScope
  10882. var scope = $rootScope;
  10883. scope.name = 'misko';
  10884. scope.counter = 0;
  10885. expect(scope.counter).toEqual(0);
  10886. scope.$watch('name', function(newValue, oldValue) {
  10887. scope.counter = scope.counter + 1;
  10888. });
  10889. expect(scope.counter).toEqual(0);
  10890. scope.$digest();
  10891. // the listener is always called during the first $digest loop after it was registered
  10892. expect(scope.counter).toEqual(1);
  10893. scope.$digest();
  10894. // but now it will not be called unless the value changes
  10895. expect(scope.counter).toEqual(1);
  10896. scope.name = 'adam';
  10897. scope.$digest();
  10898. expect(scope.counter).toEqual(2);
  10899. // Using a listener function
  10900. var food;
  10901. scope.foodCounter = 0;
  10902. expect(scope.foodCounter).toEqual(0);
  10903. scope.$watch(
  10904. // This is the listener function
  10905. function() { return food; },
  10906. // This is the change handler
  10907. function(newValue, oldValue) {
  10908. if ( newValue !== oldValue ) {
  10909. // Only increment the counter if the value changed
  10910. scope.foodCounter = scope.foodCounter + 1;
  10911. }
  10912. }
  10913. );
  10914. // No digest has been run so the counter will be zero
  10915. expect(scope.foodCounter).toEqual(0);
  10916. // Run the digest but since food has not changed count will still be zero
  10917. scope.$digest();
  10918. expect(scope.foodCounter).toEqual(0);
  10919. // Update food and run digest. Now the counter will increment
  10920. food = 'cheeseburger';
  10921. scope.$digest();
  10922. expect(scope.foodCounter).toEqual(1);
  10923. * ```
  10924. *
  10925. *
  10926. *
  10927. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  10928. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  10929. * a call to the `listener`.
  10930. *
  10931. * - `string`: Evaluated as {@link guide/expression expression}
  10932. * - `function(scope)`: called with current `scope` as a parameter.
  10933. * @param {(function()|string)=} listener Callback called whenever the return value of
  10934. * the `watchExpression` changes.
  10935. *
  10936. * - `string`: Evaluated as {@link guide/expression expression}
  10937. * - `function(newValue, oldValue, scope)`: called with current and previous values as
  10938. * parameters.
  10939. *
  10940. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  10941. * comparing for reference equality.
  10942. * @returns {function()} Returns a deregistration function for this listener.
  10943. */
  10944. $watch: function(watchExp, listener, objectEquality) {
  10945. var scope = this,
  10946. get = compileToFn(watchExp, 'watch'),
  10947. array = scope.$$watchers,
  10948. watcher = {
  10949. fn: listener,
  10950. last: initWatchVal,
  10951. get: get,
  10952. exp: watchExp,
  10953. eq: !!objectEquality
  10954. };
  10955. lastDirtyWatch = null;
  10956. // in the case user pass string, we need to compile it, do we really need this ?
  10957. if (!isFunction(listener)) {
  10958. var listenFn = compileToFn(listener || noop, 'listener');
  10959. watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
  10960. }
  10961. if (typeof watchExp == 'string' && get.constant) {
  10962. var originalFn = watcher.fn;
  10963. watcher.fn = function(newVal, oldVal, scope) {
  10964. originalFn.call(this, newVal, oldVal, scope);
  10965. arrayRemove(array, watcher);
  10966. };
  10967. }
  10968. if (!array) {
  10969. array = scope.$$watchers = [];
  10970. }
  10971. // we use unshift since we use a while loop in $digest for speed.
  10972. // the while loop reads in reverse order.
  10973. array.unshift(watcher);
  10974. return function deregisterWatch() {
  10975. arrayRemove(array, watcher);
  10976. lastDirtyWatch = null;
  10977. };
  10978. },
  10979. /**
  10980. * @ngdoc method
  10981. * @name $rootScope.Scope#$watchCollection
  10982. * @kind function
  10983. *
  10984. * @description
  10985. * Shallow watches the properties of an object and fires whenever any of the properties change
  10986. * (for arrays, this implies watching the array items; for object maps, this implies watching
  10987. * the properties). If a change is detected, the `listener` callback is fired.
  10988. *
  10989. * - The `obj` collection is observed via standard $watch operation and is examined on every
  10990. * call to $digest() to see if any items have been added, removed, or moved.
  10991. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  10992. * adding, removing, and moving items belonging to an object or array.
  10993. *
  10994. *
  10995. * # Example
  10996. * ```js
  10997. $scope.names = ['igor', 'matias', 'misko', 'james'];
  10998. $scope.dataCount = 4;
  10999. $scope.$watchCollection('names', function(newNames, oldNames) {
  11000. $scope.dataCount = newNames.length;
  11001. });
  11002. expect($scope.dataCount).toEqual(4);
  11003. $scope.$digest();
  11004. //still at 4 ... no changes
  11005. expect($scope.dataCount).toEqual(4);
  11006. $scope.names.pop();
  11007. $scope.$digest();
  11008. //now there's been a change
  11009. expect($scope.dataCount).toEqual(3);
  11010. * ```
  11011. *
  11012. *
  11013. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  11014. * expression value should evaluate to an object or an array which is observed on each
  11015. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  11016. * collection will trigger a call to the `listener`.
  11017. *
  11018. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  11019. * when a change is detected.
  11020. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  11021. * - The `oldCollection` object is a copy of the former collection data.
  11022. * Due to performance considerations, the`oldCollection` value is computed only if the
  11023. * `listener` function declares two or more arguments.
  11024. * - The `scope` argument refers to the current scope.
  11025. *
  11026. * @returns {function()} Returns a de-registration function for this listener. When the
  11027. * de-registration function is executed, the internal watch operation is terminated.
  11028. */
  11029. $watchCollection: function(obj, listener) {
  11030. var self = this;
  11031. // the current value, updated on each dirty-check run
  11032. var newValue;
  11033. // a shallow copy of the newValue from the last dirty-check run,
  11034. // updated to match newValue during dirty-check run
  11035. var oldValue;
  11036. // a shallow copy of the newValue from when the last change happened
  11037. var veryOldValue;
  11038. // only track veryOldValue if the listener is asking for it
  11039. var trackVeryOldValue = (listener.length > 1);
  11040. var changeDetected = 0;
  11041. var objGetter = $parse(obj);
  11042. var internalArray = [];
  11043. var internalObject = {};
  11044. var initRun = true;
  11045. var oldLength = 0;
  11046. function $watchCollectionWatch() {
  11047. newValue = objGetter(self);
  11048. var newLength, key, bothNaN;
  11049. if (!isObject(newValue)) { // if primitive
  11050. if (oldValue !== newValue) {
  11051. oldValue = newValue;
  11052. changeDetected++;
  11053. }
  11054. } else if (isArrayLike(newValue)) {
  11055. if (oldValue !== internalArray) {
  11056. // we are transitioning from something which was not an array into array.
  11057. oldValue = internalArray;
  11058. oldLength = oldValue.length = 0;
  11059. changeDetected++;
  11060. }
  11061. newLength = newValue.length;
  11062. if (oldLength !== newLength) {
  11063. // if lengths do not match we need to trigger change notification
  11064. changeDetected++;
  11065. oldValue.length = oldLength = newLength;
  11066. }
  11067. // copy the items to oldValue and look for changes.
  11068. for (var i = 0; i < newLength; i++) {
  11069. bothNaN = (oldValue[i] !== oldValue[i]) &&
  11070. (newValue[i] !== newValue[i]);
  11071. if (!bothNaN && (oldValue[i] !== newValue[i])) {
  11072. changeDetected++;
  11073. oldValue[i] = newValue[i];
  11074. }
  11075. }
  11076. } else {
  11077. if (oldValue !== internalObject) {
  11078. // we are transitioning from something which was not an object into object.
  11079. oldValue = internalObject = {};
  11080. oldLength = 0;
  11081. changeDetected++;
  11082. }
  11083. // copy the items to oldValue and look for changes.
  11084. newLength = 0;
  11085. for (key in newValue) {
  11086. if (newValue.hasOwnProperty(key)) {
  11087. newLength++;
  11088. if (oldValue.hasOwnProperty(key)) {
  11089. bothNaN = (oldValue[key] !== oldValue[key]) &&
  11090. (newValue[key] !== newValue[key]);
  11091. if (!bothNaN && (oldValue[key] !== newValue[key])) {
  11092. changeDetected++;
  11093. oldValue[key] = newValue[key];
  11094. }
  11095. } else {
  11096. oldLength++;
  11097. oldValue[key] = newValue[key];
  11098. changeDetected++;
  11099. }
  11100. }
  11101. }
  11102. if (oldLength > newLength) {
  11103. // we used to have more keys, need to find them and destroy them.
  11104. changeDetected++;
  11105. for(key in oldValue) {
  11106. if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
  11107. oldLength--;
  11108. delete oldValue[key];
  11109. }
  11110. }
  11111. }
  11112. }
  11113. return changeDetected;
  11114. }
  11115. function $watchCollectionAction() {
  11116. if (initRun) {
  11117. initRun = false;
  11118. listener(newValue, newValue, self);
  11119. } else {
  11120. listener(newValue, veryOldValue, self);
  11121. }
  11122. // make a copy for the next time a collection is changed
  11123. if (trackVeryOldValue) {
  11124. if (!isObject(newValue)) {
  11125. //primitive
  11126. veryOldValue = newValue;
  11127. } else if (isArrayLike(newValue)) {
  11128. veryOldValue = new Array(newValue.length);
  11129. for (var i = 0; i < newValue.length; i++) {
  11130. veryOldValue[i] = newValue[i];
  11131. }
  11132. } else { // if object
  11133. veryOldValue = {};
  11134. for (var key in newValue) {
  11135. if (hasOwnProperty.call(newValue, key)) {
  11136. veryOldValue[key] = newValue[key];
  11137. }
  11138. }
  11139. }
  11140. }
  11141. }
  11142. return this.$watch($watchCollectionWatch, $watchCollectionAction);
  11143. },
  11144. /**
  11145. * @ngdoc method
  11146. * @name $rootScope.Scope#$digest
  11147. * @kind function
  11148. *
  11149. * @description
  11150. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  11151. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  11152. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  11153. * until no more listeners are firing. This means that it is possible to get into an infinite
  11154. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  11155. * iterations exceeds 10.
  11156. *
  11157. * Usually, you don't call `$digest()` directly in
  11158. * {@link ng.directive:ngController controllers} or in
  11159. * {@link ng.$compileProvider#directive directives}.
  11160. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  11161. * a {@link ng.$compileProvider#directive directives}), which will force a `$digest()`.
  11162. *
  11163. * If you want to be notified whenever `$digest()` is called,
  11164. * you can register a `watchExpression` function with
  11165. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  11166. *
  11167. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  11168. *
  11169. * # Example
  11170. * ```js
  11171. var scope = ...;
  11172. scope.name = 'misko';
  11173. scope.counter = 0;
  11174. expect(scope.counter).toEqual(0);
  11175. scope.$watch('name', function(newValue, oldValue) {
  11176. scope.counter = scope.counter + 1;
  11177. });
  11178. expect(scope.counter).toEqual(0);
  11179. scope.$digest();
  11180. // the listener is always called during the first $digest loop after it was registered
  11181. expect(scope.counter).toEqual(1);
  11182. scope.$digest();
  11183. // but now it will not be called unless the value changes
  11184. expect(scope.counter).toEqual(1);
  11185. scope.name = 'adam';
  11186. scope.$digest();
  11187. expect(scope.counter).toEqual(2);
  11188. * ```
  11189. *
  11190. */
  11191. $digest: function() {
  11192. var watch, value, last,
  11193. watchers,
  11194. asyncQueue = this.$$asyncQueue,
  11195. postDigestQueue = this.$$postDigestQueue,
  11196. length,
  11197. dirty, ttl = TTL,
  11198. next, current, target = this,
  11199. watchLog = [],
  11200. logIdx, logMsg, asyncTask;
  11201. beginPhase('$digest');
  11202. lastDirtyWatch = null;
  11203. do { // "while dirty" loop
  11204. dirty = false;
  11205. current = target;
  11206. while(asyncQueue.length) {
  11207. try {
  11208. asyncTask = asyncQueue.shift();
  11209. asyncTask.scope.$eval(asyncTask.expression);
  11210. } catch (e) {
  11211. clearPhase();
  11212. $exceptionHandler(e);
  11213. }
  11214. lastDirtyWatch = null;
  11215. }
  11216. traverseScopesLoop:
  11217. do { // "traverse the scopes" loop
  11218. if ((watchers = current.$$watchers)) {
  11219. // process our watches
  11220. length = watchers.length;
  11221. while (length--) {
  11222. try {
  11223. watch = watchers[length];
  11224. // Most common watches are on primitives, in which case we can short
  11225. // circuit it with === operator, only when === fails do we use .equals
  11226. if (watch) {
  11227. if ((value = watch.get(current)) !== (last = watch.last) &&
  11228. !(watch.eq
  11229. ? equals(value, last)
  11230. : (typeof value === 'number' && typeof last === 'number'
  11231. && isNaN(value) && isNaN(last)))) {
  11232. dirty = true;
  11233. lastDirtyWatch = watch;
  11234. watch.last = watch.eq ? copy(value, null) : value;
  11235. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  11236. if (ttl < 5) {
  11237. logIdx = 4 - ttl;
  11238. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  11239. logMsg = (isFunction(watch.exp))
  11240. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  11241. : watch.exp;
  11242. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  11243. watchLog[logIdx].push(logMsg);
  11244. }
  11245. } else if (watch === lastDirtyWatch) {
  11246. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  11247. // have already been tested.
  11248. dirty = false;
  11249. break traverseScopesLoop;
  11250. }
  11251. }
  11252. } catch (e) {
  11253. clearPhase();
  11254. $exceptionHandler(e);
  11255. }
  11256. }
  11257. }
  11258. // Insanity Warning: scope depth-first traversal
  11259. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11260. // this piece should be kept in sync with the traversal in $broadcast
  11261. if (!(next = (current.$$childHead ||
  11262. (current !== target && current.$$nextSibling)))) {
  11263. while(current !== target && !(next = current.$$nextSibling)) {
  11264. current = current.$parent;
  11265. }
  11266. }
  11267. } while ((current = next));
  11268. // `break traverseScopesLoop;` takes us to here
  11269. if((dirty || asyncQueue.length) && !(ttl--)) {
  11270. clearPhase();
  11271. throw $rootScopeMinErr('infdig',
  11272. '{0} $digest() iterations reached. Aborting!\n' +
  11273. 'Watchers fired in the last 5 iterations: {1}',
  11274. TTL, toJson(watchLog));
  11275. }
  11276. } while (dirty || asyncQueue.length);
  11277. clearPhase();
  11278. while(postDigestQueue.length) {
  11279. try {
  11280. postDigestQueue.shift()();
  11281. } catch (e) {
  11282. $exceptionHandler(e);
  11283. }
  11284. }
  11285. },
  11286. /**
  11287. * @ngdoc event
  11288. * @name $rootScope.Scope#$destroy
  11289. * @eventType broadcast on scope being destroyed
  11290. *
  11291. * @description
  11292. * Broadcasted when a scope and its children are being destroyed.
  11293. *
  11294. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11295. * clean up DOM bindings before an element is removed from the DOM.
  11296. */
  11297. /**
  11298. * @ngdoc method
  11299. * @name $rootScope.Scope#$destroy
  11300. * @kind function
  11301. *
  11302. * @description
  11303. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  11304. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  11305. * propagate to the current scope and its children. Removal also implies that the current
  11306. * scope is eligible for garbage collection.
  11307. *
  11308. * The `$destroy()` is usually used by directives such as
  11309. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  11310. * unrolling of the loop.
  11311. *
  11312. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  11313. * Application code can register a `$destroy` event handler that will give it a chance to
  11314. * perform any necessary cleanup.
  11315. *
  11316. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  11317. * clean up DOM bindings before an element is removed from the DOM.
  11318. */
  11319. $destroy: function() {
  11320. // we can't destroy the root scope or a scope that has been already destroyed
  11321. if (this.$$destroyed) return;
  11322. var parent = this.$parent;
  11323. this.$broadcast('$destroy');
  11324. this.$$destroyed = true;
  11325. if (this === $rootScope) return;
  11326. forEach(this.$$listenerCount, bind(null, decrementListenerCount, this));
  11327. // sever all the references to parent scopes (after this cleanup, the current scope should
  11328. // not be retained by any of our references and should be eligible for garbage collection)
  11329. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  11330. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  11331. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  11332. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  11333. // All of the code below is bogus code that works around V8's memory leak via optimized code
  11334. // and inline caches.
  11335. //
  11336. // see:
  11337. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  11338. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  11339. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  11340. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  11341. this.$$childTail = this.$root = null;
  11342. // don't reset these to null in case some async task tries to register a listener/watch/task
  11343. this.$$listeners = {};
  11344. this.$$watchers = this.$$asyncQueue = this.$$postDigestQueue = [];
  11345. // prevent NPEs since these methods have references to properties we nulled out
  11346. this.$destroy = this.$digest = this.$apply = noop;
  11347. this.$on = this.$watch = function() { return noop; };
  11348. },
  11349. /**
  11350. * @ngdoc method
  11351. * @name $rootScope.Scope#$eval
  11352. * @kind function
  11353. *
  11354. * @description
  11355. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  11356. * the expression are propagated (uncaught). This is useful when evaluating Angular
  11357. * expressions.
  11358. *
  11359. * # Example
  11360. * ```js
  11361. var scope = ng.$rootScope.Scope();
  11362. scope.a = 1;
  11363. scope.b = 2;
  11364. expect(scope.$eval('a+b')).toEqual(3);
  11365. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  11366. * ```
  11367. *
  11368. * @param {(string|function())=} expression An angular expression to be executed.
  11369. *
  11370. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11371. * - `function(scope)`: execute the function with the current `scope` parameter.
  11372. *
  11373. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  11374. * @returns {*} The result of evaluating the expression.
  11375. */
  11376. $eval: function(expr, locals) {
  11377. return $parse(expr)(this, locals);
  11378. },
  11379. /**
  11380. * @ngdoc method
  11381. * @name $rootScope.Scope#$evalAsync
  11382. * @kind function
  11383. *
  11384. * @description
  11385. * Executes the expression on the current scope at a later point in time.
  11386. *
  11387. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  11388. * that:
  11389. *
  11390. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  11391. * rendering).
  11392. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  11393. * `expression` execution.
  11394. *
  11395. * Any exceptions from the execution of the expression are forwarded to the
  11396. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11397. *
  11398. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  11399. * will be scheduled. However, it is encouraged to always call code that changes the model
  11400. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  11401. *
  11402. * @param {(string|function())=} expression An angular expression to be executed.
  11403. *
  11404. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11405. * - `function(scope)`: execute the function with the current `scope` parameter.
  11406. *
  11407. */
  11408. $evalAsync: function(expr) {
  11409. // if we are outside of an $digest loop and this is the first time we are scheduling async
  11410. // task also schedule async auto-flush
  11411. if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
  11412. $browser.defer(function() {
  11413. if ($rootScope.$$asyncQueue.length) {
  11414. $rootScope.$digest();
  11415. }
  11416. });
  11417. }
  11418. this.$$asyncQueue.push({scope: this, expression: expr});
  11419. },
  11420. $$postDigest : function(fn) {
  11421. this.$$postDigestQueue.push(fn);
  11422. },
  11423. /**
  11424. * @ngdoc method
  11425. * @name $rootScope.Scope#$apply
  11426. * @kind function
  11427. *
  11428. * @description
  11429. * `$apply()` is used to execute an expression in angular from outside of the angular
  11430. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  11431. * Because we are calling into the angular framework we need to perform proper scope life
  11432. * cycle of {@link ng.$exceptionHandler exception handling},
  11433. * {@link ng.$rootScope.Scope#$digest executing watches}.
  11434. *
  11435. * ## Life cycle
  11436. *
  11437. * # Pseudo-Code of `$apply()`
  11438. * ```js
  11439. function $apply(expr) {
  11440. try {
  11441. return $eval(expr);
  11442. } catch (e) {
  11443. $exceptionHandler(e);
  11444. } finally {
  11445. $root.$digest();
  11446. }
  11447. }
  11448. * ```
  11449. *
  11450. *
  11451. * Scope's `$apply()` method transitions through the following stages:
  11452. *
  11453. * 1. The {@link guide/expression expression} is executed using the
  11454. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  11455. * 2. Any exceptions from the execution of the expression are forwarded to the
  11456. * {@link ng.$exceptionHandler $exceptionHandler} service.
  11457. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  11458. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  11459. *
  11460. *
  11461. * @param {(string|function())=} exp An angular expression to be executed.
  11462. *
  11463. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  11464. * - `function(scope)`: execute the function with current `scope` parameter.
  11465. *
  11466. * @returns {*} The result of evaluating the expression.
  11467. */
  11468. $apply: function(expr) {
  11469. try {
  11470. beginPhase('$apply');
  11471. return this.$eval(expr);
  11472. } catch (e) {
  11473. $exceptionHandler(e);
  11474. } finally {
  11475. clearPhase();
  11476. try {
  11477. $rootScope.$digest();
  11478. } catch (e) {
  11479. $exceptionHandler(e);
  11480. throw e;
  11481. }
  11482. }
  11483. },
  11484. /**
  11485. * @ngdoc method
  11486. * @name $rootScope.Scope#$on
  11487. * @kind function
  11488. *
  11489. * @description
  11490. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  11491. * discussion of event life cycle.
  11492. *
  11493. * The event listener function format is: `function(event, args...)`. The `event` object
  11494. * passed into the listener has the following attributes:
  11495. *
  11496. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  11497. * `$broadcast`-ed.
  11498. * - `currentScope` - `{Scope}`: the current scope which is handling the event.
  11499. * - `name` - `{string}`: name of the event.
  11500. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  11501. * further event propagation (available only for events that were `$emit`-ed).
  11502. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  11503. * to true.
  11504. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  11505. *
  11506. * @param {string} name Event name to listen on.
  11507. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  11508. * @returns {function()} Returns a deregistration function for this listener.
  11509. */
  11510. $on: function(name, listener) {
  11511. var namedListeners = this.$$listeners[name];
  11512. if (!namedListeners) {
  11513. this.$$listeners[name] = namedListeners = [];
  11514. }
  11515. namedListeners.push(listener);
  11516. var current = this;
  11517. do {
  11518. if (!current.$$listenerCount[name]) {
  11519. current.$$listenerCount[name] = 0;
  11520. }
  11521. current.$$listenerCount[name]++;
  11522. } while ((current = current.$parent));
  11523. var self = this;
  11524. return function() {
  11525. namedListeners[indexOf(namedListeners, listener)] = null;
  11526. decrementListenerCount(self, 1, name);
  11527. };
  11528. },
  11529. /**
  11530. * @ngdoc method
  11531. * @name $rootScope.Scope#$emit
  11532. * @kind function
  11533. *
  11534. * @description
  11535. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  11536. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11537. *
  11538. * The event life cycle starts at the scope on which `$emit` was called. All
  11539. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11540. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  11541. * registered listeners along the way. The event will stop propagating if one of the listeners
  11542. * cancels it.
  11543. *
  11544. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11545. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11546. *
  11547. * @param {string} name Event name to emit.
  11548. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11549. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  11550. */
  11551. $emit: function(name, args) {
  11552. var empty = [],
  11553. namedListeners,
  11554. scope = this,
  11555. stopPropagation = false,
  11556. event = {
  11557. name: name,
  11558. targetScope: scope,
  11559. stopPropagation: function() {stopPropagation = true;},
  11560. preventDefault: function() {
  11561. event.defaultPrevented = true;
  11562. },
  11563. defaultPrevented: false
  11564. },
  11565. listenerArgs = concat([event], arguments, 1),
  11566. i, length;
  11567. do {
  11568. namedListeners = scope.$$listeners[name] || empty;
  11569. event.currentScope = scope;
  11570. for (i=0, length=namedListeners.length; i<length; i++) {
  11571. // if listeners were deregistered, defragment the array
  11572. if (!namedListeners[i]) {
  11573. namedListeners.splice(i, 1);
  11574. i--;
  11575. length--;
  11576. continue;
  11577. }
  11578. try {
  11579. //allow all listeners attached to the current scope to run
  11580. namedListeners[i].apply(null, listenerArgs);
  11581. } catch (e) {
  11582. $exceptionHandler(e);
  11583. }
  11584. }
  11585. //if any listener on the current scope stops propagation, prevent bubbling
  11586. if (stopPropagation) return event;
  11587. //traverse upwards
  11588. scope = scope.$parent;
  11589. } while (scope);
  11590. return event;
  11591. },
  11592. /**
  11593. * @ngdoc method
  11594. * @name $rootScope.Scope#$broadcast
  11595. * @kind function
  11596. *
  11597. * @description
  11598. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  11599. * registered {@link ng.$rootScope.Scope#$on} listeners.
  11600. *
  11601. * The event life cycle starts at the scope on which `$broadcast` was called. All
  11602. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  11603. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  11604. * scope and calls all registered listeners along the way. The event cannot be canceled.
  11605. *
  11606. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  11607. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  11608. *
  11609. * @param {string} name Event name to broadcast.
  11610. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  11611. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  11612. */
  11613. $broadcast: function(name, args) {
  11614. var target = this,
  11615. current = target,
  11616. next = target,
  11617. event = {
  11618. name: name,
  11619. targetScope: target,
  11620. preventDefault: function() {
  11621. event.defaultPrevented = true;
  11622. },
  11623. defaultPrevented: false
  11624. },
  11625. listenerArgs = concat([event], arguments, 1),
  11626. listeners, i, length;
  11627. //down while you can, then up and next sibling or up and next sibling until back at root
  11628. while ((current = next)) {
  11629. event.currentScope = current;
  11630. listeners = current.$$listeners[name] || [];
  11631. for (i=0, length = listeners.length; i<length; i++) {
  11632. // if listeners were deregistered, defragment the array
  11633. if (!listeners[i]) {
  11634. listeners.splice(i, 1);
  11635. i--;
  11636. length--;
  11637. continue;
  11638. }
  11639. try {
  11640. listeners[i].apply(null, listenerArgs);
  11641. } catch(e) {
  11642. $exceptionHandler(e);
  11643. }
  11644. }
  11645. // Insanity Warning: scope depth-first traversal
  11646. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  11647. // this piece should be kept in sync with the traversal in $digest
  11648. // (though it differs due to having the extra check for $$listenerCount)
  11649. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  11650. (current !== target && current.$$nextSibling)))) {
  11651. while(current !== target && !(next = current.$$nextSibling)) {
  11652. current = current.$parent;
  11653. }
  11654. }
  11655. }
  11656. return event;
  11657. }
  11658. };
  11659. var $rootScope = new Scope();
  11660. return $rootScope;
  11661. function beginPhase(phase) {
  11662. if ($rootScope.$$phase) {
  11663. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  11664. }
  11665. $rootScope.$$phase = phase;
  11666. }
  11667. function clearPhase() {
  11668. $rootScope.$$phase = null;
  11669. }
  11670. function compileToFn(exp, name) {
  11671. var fn = $parse(exp);
  11672. assertArgFn(fn, name);
  11673. return fn;
  11674. }
  11675. function decrementListenerCount(current, count, name) {
  11676. do {
  11677. current.$$listenerCount[name] -= count;
  11678. if (current.$$listenerCount[name] === 0) {
  11679. delete current.$$listenerCount[name];
  11680. }
  11681. } while ((current = current.$parent));
  11682. }
  11683. /**
  11684. * function used as an initial value for watchers.
  11685. * because it's unique we can easily tell it apart from other values
  11686. */
  11687. function initWatchVal() {}
  11688. }];
  11689. }
  11690. /**
  11691. * @description
  11692. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  11693. */
  11694. function $$SanitizeUriProvider() {
  11695. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  11696. imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
  11697. /**
  11698. * @description
  11699. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11700. * urls during a[href] sanitization.
  11701. *
  11702. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11703. *
  11704. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  11705. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  11706. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11707. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11708. *
  11709. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11710. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11711. * chaining otherwise.
  11712. */
  11713. this.aHrefSanitizationWhitelist = function(regexp) {
  11714. if (isDefined(regexp)) {
  11715. aHrefSanitizationWhitelist = regexp;
  11716. return this;
  11717. }
  11718. return aHrefSanitizationWhitelist;
  11719. };
  11720. /**
  11721. * @description
  11722. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  11723. * urls during img[src] sanitization.
  11724. *
  11725. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  11726. *
  11727. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  11728. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  11729. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  11730. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  11731. *
  11732. * @param {RegExp=} regexp New regexp to whitelist urls with.
  11733. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  11734. * chaining otherwise.
  11735. */
  11736. this.imgSrcSanitizationWhitelist = function(regexp) {
  11737. if (isDefined(regexp)) {
  11738. imgSrcSanitizationWhitelist = regexp;
  11739. return this;
  11740. }
  11741. return imgSrcSanitizationWhitelist;
  11742. };
  11743. this.$get = function() {
  11744. return function sanitizeUri(uri, isImage) {
  11745. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  11746. var normalizedVal;
  11747. // NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
  11748. if (!msie || msie >= 8 ) {
  11749. normalizedVal = urlResolve(uri).href;
  11750. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  11751. return 'unsafe:'+normalizedVal;
  11752. }
  11753. }
  11754. return uri;
  11755. };
  11756. };
  11757. }
  11758. var $sceMinErr = minErr('$sce');
  11759. var SCE_CONTEXTS = {
  11760. HTML: 'html',
  11761. CSS: 'css',
  11762. URL: 'url',
  11763. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  11764. // url. (e.g. ng-include, script src, templateUrl)
  11765. RESOURCE_URL: 'resourceUrl',
  11766. JS: 'js'
  11767. };
  11768. // Helper functions follow.
  11769. // Copied from:
  11770. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  11771. // Prereq: s is a string.
  11772. function escapeForRegexp(s) {
  11773. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  11774. replace(/\x08/g, '\\x08');
  11775. }
  11776. function adjustMatcher(matcher) {
  11777. if (matcher === 'self') {
  11778. return matcher;
  11779. } else if (isString(matcher)) {
  11780. // Strings match exactly except for 2 wildcards - '*' and '**'.
  11781. // '*' matches any character except those from the set ':/.?&'.
  11782. // '**' matches any character (like .* in a RegExp).
  11783. // More than 2 *'s raises an error as it's ill defined.
  11784. if (matcher.indexOf('***') > -1) {
  11785. throw $sceMinErr('iwcard',
  11786. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  11787. }
  11788. matcher = escapeForRegexp(matcher).
  11789. replace('\\*\\*', '.*').
  11790. replace('\\*', '[^:/.?&;]*');
  11791. return new RegExp('^' + matcher + '$');
  11792. } else if (isRegExp(matcher)) {
  11793. // The only other type of matcher allowed is a Regexp.
  11794. // Match entire URL / disallow partial matches.
  11795. // Flags are reset (i.e. no global, ignoreCase or multiline)
  11796. return new RegExp('^' + matcher.source + '$');
  11797. } else {
  11798. throw $sceMinErr('imatcher',
  11799. 'Matchers may only be "self", string patterns or RegExp objects');
  11800. }
  11801. }
  11802. function adjustMatchers(matchers) {
  11803. var adjustedMatchers = [];
  11804. if (isDefined(matchers)) {
  11805. forEach(matchers, function(matcher) {
  11806. adjustedMatchers.push(adjustMatcher(matcher));
  11807. });
  11808. }
  11809. return adjustedMatchers;
  11810. }
  11811. /**
  11812. * @ngdoc service
  11813. * @name $sceDelegate
  11814. * @kind function
  11815. *
  11816. * @description
  11817. *
  11818. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  11819. * Contextual Escaping (SCE)} services to AngularJS.
  11820. *
  11821. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  11822. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  11823. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  11824. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  11825. * work because `$sce` delegates to `$sceDelegate` for these operations.
  11826. *
  11827. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  11828. *
  11829. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  11830. * can override it completely to change the behavior of `$sce`, the common case would
  11831. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  11832. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  11833. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  11834. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  11835. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11836. */
  11837. /**
  11838. * @ngdoc provider
  11839. * @name $sceDelegateProvider
  11840. * @description
  11841. *
  11842. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  11843. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  11844. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  11845. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  11846. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  11847. *
  11848. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  11849. * Strict Contextual Escaping (SCE)}.
  11850. *
  11851. * **Example**: Consider the following case. <a name="example"></a>
  11852. *
  11853. * - your app is hosted at url `http://myapp.example.com/`
  11854. * - but some of your templates are hosted on other domains you control such as
  11855. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  11856. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  11857. *
  11858. * Here is what a secure configuration for this scenario might look like:
  11859. *
  11860. * ```
  11861. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  11862. * $sceDelegateProvider.resourceUrlWhitelist([
  11863. * // Allow same origin resource loads.
  11864. * 'self',
  11865. * // Allow loading from our assets domain. Notice the difference between * and **.
  11866. * 'http://srv*.assets.example.com/**'
  11867. * ]);
  11868. *
  11869. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  11870. * $sceDelegateProvider.resourceUrlBlacklist([
  11871. * 'http://myapp.example.com/clickThru**'
  11872. * ]);
  11873. * });
  11874. * ```
  11875. */
  11876. function $SceDelegateProvider() {
  11877. this.SCE_CONTEXTS = SCE_CONTEXTS;
  11878. // Resource URLs can also be trusted by policy.
  11879. var resourceUrlWhitelist = ['self'],
  11880. resourceUrlBlacklist = [];
  11881. /**
  11882. * @ngdoc method
  11883. * @name $sceDelegateProvider#resourceUrlWhitelist
  11884. * @kind function
  11885. *
  11886. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  11887. * provided. This must be an array or null. A snapshot of this array is used so further
  11888. * changes to the array are ignored.
  11889. *
  11890. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11891. * allowed in this array.
  11892. *
  11893. * Note: **an empty whitelist array will block all URLs**!
  11894. *
  11895. * @return {Array} the currently set whitelist array.
  11896. *
  11897. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  11898. * same origin resource requests.
  11899. *
  11900. * @description
  11901. * Sets/Gets the whitelist of trusted resource URLs.
  11902. */
  11903. this.resourceUrlWhitelist = function (value) {
  11904. if (arguments.length) {
  11905. resourceUrlWhitelist = adjustMatchers(value);
  11906. }
  11907. return resourceUrlWhitelist;
  11908. };
  11909. /**
  11910. * @ngdoc method
  11911. * @name $sceDelegateProvider#resourceUrlBlacklist
  11912. * @kind function
  11913. *
  11914. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  11915. * provided. This must be an array or null. A snapshot of this array is used so further
  11916. * changes to the array are ignored.
  11917. *
  11918. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  11919. * allowed in this array.
  11920. *
  11921. * The typical usage for the blacklist is to **block
  11922. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  11923. * these would otherwise be trusted but actually return content from the redirected domain.
  11924. *
  11925. * Finally, **the blacklist overrides the whitelist** and has the final say.
  11926. *
  11927. * @return {Array} the currently set blacklist array.
  11928. *
  11929. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  11930. * is no blacklist.)
  11931. *
  11932. * @description
  11933. * Sets/Gets the blacklist of trusted resource URLs.
  11934. */
  11935. this.resourceUrlBlacklist = function (value) {
  11936. if (arguments.length) {
  11937. resourceUrlBlacklist = adjustMatchers(value);
  11938. }
  11939. return resourceUrlBlacklist;
  11940. };
  11941. this.$get = ['$injector', function($injector) {
  11942. var htmlSanitizer = function htmlSanitizer(html) {
  11943. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  11944. };
  11945. if ($injector.has('$sanitize')) {
  11946. htmlSanitizer = $injector.get('$sanitize');
  11947. }
  11948. function matchUrl(matcher, parsedUrl) {
  11949. if (matcher === 'self') {
  11950. return urlIsSameOrigin(parsedUrl);
  11951. } else {
  11952. // definitely a regex. See adjustMatchers()
  11953. return !!matcher.exec(parsedUrl.href);
  11954. }
  11955. }
  11956. function isResourceUrlAllowedByPolicy(url) {
  11957. var parsedUrl = urlResolve(url.toString());
  11958. var i, n, allowed = false;
  11959. // Ensure that at least one item from the whitelist allows this url.
  11960. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  11961. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  11962. allowed = true;
  11963. break;
  11964. }
  11965. }
  11966. if (allowed) {
  11967. // Ensure that no item from the blacklist blocked this url.
  11968. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  11969. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  11970. allowed = false;
  11971. break;
  11972. }
  11973. }
  11974. }
  11975. return allowed;
  11976. }
  11977. function generateHolderType(Base) {
  11978. var holderType = function TrustedValueHolderType(trustedValue) {
  11979. this.$$unwrapTrustedValue = function() {
  11980. return trustedValue;
  11981. };
  11982. };
  11983. if (Base) {
  11984. holderType.prototype = new Base();
  11985. }
  11986. holderType.prototype.valueOf = function sceValueOf() {
  11987. return this.$$unwrapTrustedValue();
  11988. };
  11989. holderType.prototype.toString = function sceToString() {
  11990. return this.$$unwrapTrustedValue().toString();
  11991. };
  11992. return holderType;
  11993. }
  11994. var trustedValueHolderBase = generateHolderType(),
  11995. byType = {};
  11996. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  11997. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  11998. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  11999. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  12000. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  12001. /**
  12002. * @ngdoc method
  12003. * @name $sceDelegate#trustAs
  12004. *
  12005. * @description
  12006. * Returns an object that is trusted by angular for use in specified strict
  12007. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  12008. * attribute interpolation, any dom event binding attribute interpolation
  12009. * such as for onclick, etc.) that uses the provided value.
  12010. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  12011. *
  12012. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12013. * resourceUrl, html, js and css.
  12014. * @param {*} value The value that that should be considered trusted/safe.
  12015. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12016. * where Angular expects a $sce.trustAs() return value.
  12017. */
  12018. function trustAs(type, trustedValue) {
  12019. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  12020. if (!Constructor) {
  12021. throw $sceMinErr('icontext',
  12022. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  12023. type, trustedValue);
  12024. }
  12025. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  12026. return trustedValue;
  12027. }
  12028. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  12029. // mutable objects, we ensure here that the value passed in is actually a string.
  12030. if (typeof trustedValue !== 'string') {
  12031. throw $sceMinErr('itype',
  12032. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  12033. type);
  12034. }
  12035. return new Constructor(trustedValue);
  12036. }
  12037. /**
  12038. * @ngdoc method
  12039. * @name $sceDelegate#valueOf
  12040. *
  12041. * @description
  12042. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  12043. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  12044. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  12045. *
  12046. * If the passed parameter is not a value that had been returned by {@link
  12047. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  12048. *
  12049. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  12050. * call or anything else.
  12051. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  12052. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  12053. * `value` unchanged.
  12054. */
  12055. function valueOf(maybeTrusted) {
  12056. if (maybeTrusted instanceof trustedValueHolderBase) {
  12057. return maybeTrusted.$$unwrapTrustedValue();
  12058. } else {
  12059. return maybeTrusted;
  12060. }
  12061. }
  12062. /**
  12063. * @ngdoc method
  12064. * @name $sceDelegate#getTrusted
  12065. *
  12066. * @description
  12067. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  12068. * returns the originally supplied value if the queried context type is a supertype of the
  12069. * created type. If this condition isn't satisfied, throws an exception.
  12070. *
  12071. * @param {string} type The kind of context in which this value is to be used.
  12072. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  12073. * `$sceDelegate.trustAs`} call.
  12074. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  12075. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  12076. */
  12077. function getTrusted(type, maybeTrusted) {
  12078. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  12079. return maybeTrusted;
  12080. }
  12081. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  12082. if (constructor && maybeTrusted instanceof constructor) {
  12083. return maybeTrusted.$$unwrapTrustedValue();
  12084. }
  12085. // If we get here, then we may only take one of two actions.
  12086. // 1. sanitize the value for the requested type, or
  12087. // 2. throw an exception.
  12088. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  12089. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  12090. return maybeTrusted;
  12091. } else {
  12092. throw $sceMinErr('insecurl',
  12093. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  12094. maybeTrusted.toString());
  12095. }
  12096. } else if (type === SCE_CONTEXTS.HTML) {
  12097. return htmlSanitizer(maybeTrusted);
  12098. }
  12099. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  12100. }
  12101. return { trustAs: trustAs,
  12102. getTrusted: getTrusted,
  12103. valueOf: valueOf };
  12104. }];
  12105. }
  12106. /**
  12107. * @ngdoc provider
  12108. * @name $sceProvider
  12109. * @description
  12110. *
  12111. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  12112. * - enable/disable Strict Contextual Escaping (SCE) in a module
  12113. * - override the default implementation with a custom delegate
  12114. *
  12115. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  12116. */
  12117. /* jshint maxlen: false*/
  12118. /**
  12119. * @ngdoc service
  12120. * @name $sce
  12121. * @kind function
  12122. *
  12123. * @description
  12124. *
  12125. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  12126. *
  12127. * # Strict Contextual Escaping
  12128. *
  12129. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  12130. * contexts to result in a value that is marked as safe to use for that context. One example of
  12131. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  12132. * to these contexts as privileged or SCE contexts.
  12133. *
  12134. * As of version 1.2, Angular ships with SCE enabled by default.
  12135. *
  12136. * Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
  12137. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  12138. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  12139. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  12140. * to the top of your HTML document.
  12141. *
  12142. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  12143. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  12144. *
  12145. * Here's an example of a binding in a privileged context:
  12146. *
  12147. * ```
  12148. * <input ng-model="userHtml">
  12149. * <div ng-bind-html="userHtml"></div>
  12150. * ```
  12151. *
  12152. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  12153. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  12154. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  12155. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  12156. * security vulnerabilities.)
  12157. *
  12158. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  12159. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  12160. *
  12161. * How would you ensure that every place that used these types of bindings was bound to a value that
  12162. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  12163. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  12164. * properties/fields and forgot to update the binding to the sanitized value?
  12165. *
  12166. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  12167. * determine that something explicitly says it's safe to use a value for binding in that
  12168. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  12169. * for those values that you can easily tell are safe - because they were received from your server,
  12170. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  12171. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  12172. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  12173. *
  12174. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  12175. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  12176. * obtain values that will be accepted by SCE / privileged contexts.
  12177. *
  12178. *
  12179. * ## How does it work?
  12180. *
  12181. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  12182. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  12183. * ng.$sce#parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  12184. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  12185. *
  12186. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  12187. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  12188. * simplified):
  12189. *
  12190. * ```
  12191. * var ngBindHtmlDirective = ['$sce', function($sce) {
  12192. * return function(scope, element, attr) {
  12193. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  12194. * element.html(value || '');
  12195. * });
  12196. * };
  12197. * }];
  12198. * ```
  12199. *
  12200. * ## Impact on loading templates
  12201. *
  12202. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  12203. * `templateUrl`'s specified by {@link guide/directive directives}.
  12204. *
  12205. * By default, Angular only loads templates from the same domain and protocol as the application
  12206. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  12207. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  12208. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  12209. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  12210. *
  12211. * *Please note*:
  12212. * The browser's
  12213. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  12214. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  12215. * policy apply in addition to this and may further restrict whether the template is successfully
  12216. * loaded. This means that without the right CORS policy, loading templates from a different domain
  12217. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  12218. * browsers.
  12219. *
  12220. * ## This feels like too much overhead for the developer?
  12221. *
  12222. * It's important to remember that SCE only applies to interpolation expressions.
  12223. *
  12224. * If your expressions are constant literals, they're automatically trusted and you don't need to
  12225. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  12226. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  12227. *
  12228. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  12229. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  12230. *
  12231. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  12232. * templates in `ng-include` from your application's domain without having to even know about SCE.
  12233. * It blocks loading templates from other domains or loading templates over http from an https
  12234. * served document. You can change these by setting your own custom {@link
  12235. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  12236. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  12237. *
  12238. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  12239. * application that's secure and can be audited to verify that with much more ease than bolting
  12240. * security onto an application later.
  12241. *
  12242. * <a name="contexts"></a>
  12243. * ## What trusted context types are supported?
  12244. *
  12245. * | Context | Notes |
  12246. * |---------------------|----------------|
  12247. * | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. If an unsafe value is encountered and the {@link ngSanitize $sanitize} module is present this will sanitize the value instead of throwing an error. |
  12248. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  12249. * | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't constitute an SCE context. |
  12250. * | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contents are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
  12251. * | `$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. |
  12252. *
  12253. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  12254. *
  12255. * Each element in these arrays must be one of the following:
  12256. *
  12257. * - **'self'**
  12258. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  12259. * domain** as the application document using the **same protocol**.
  12260. * - **String** (except the special value `'self'`)
  12261. * - The string is matched against the full *normalized / absolute URL* of the resource
  12262. * being tested (substring matches are not good enough.)
  12263. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  12264. * match themselves.
  12265. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  12266. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  12267. * in a whitelist.
  12268. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  12269. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  12270. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  12271. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  12272. * http://foo.example.com/templates/**).
  12273. * - **RegExp** (*see caveat below*)
  12274. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  12275. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  12276. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  12277. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  12278. * small number of cases. A `.` character in the regex used when matching the scheme or a
  12279. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  12280. * is highly recommended to use the string patterns and only fall back to regular expressions
  12281. * if they as a last resort.
  12282. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  12283. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  12284. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  12285. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  12286. * - If you are generating your JavaScript from some other templating engine (not
  12287. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  12288. * remember to escape your regular expression (and be aware that you might need more than
  12289. * one level of escaping depending on your templating engine and the way you interpolated
  12290. * the value.) Do make use of your platform's escaping mechanism as it might be good
  12291. * enough before coding your own. e.g. Ruby has
  12292. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  12293. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  12294. * Javascript lacks a similar built in function for escaping. Take a look at Google
  12295. * Closure library's [goog.string.regExpEscape(s)](
  12296. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  12297. *
  12298. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  12299. *
  12300. * ## Show me an example using SCE.
  12301. *
  12302. * <example module="mySceApp" deps="angular-sanitize.js">
  12303. * <file name="index.html">
  12304. * <div ng-controller="myAppController as myCtrl">
  12305. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  12306. * <b>User comments</b><br>
  12307. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  12308. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  12309. * exploit.
  12310. * <div class="well">
  12311. * <div ng-repeat="userComment in myCtrl.userComments">
  12312. * <b>{{userComment.name}}</b>:
  12313. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  12314. * <br>
  12315. * </div>
  12316. * </div>
  12317. * </div>
  12318. * </file>
  12319. *
  12320. * <file name="script.js">
  12321. * var mySceApp = angular.module('mySceApp', ['ngSanitize']);
  12322. *
  12323. * mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
  12324. * var self = this;
  12325. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  12326. * self.userComments = userComments;
  12327. * });
  12328. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  12329. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12330. * 'sanitization.&quot;">Hover over this text.</span>');
  12331. * });
  12332. * </file>
  12333. *
  12334. * <file name="test_data.json">
  12335. * [
  12336. * { "name": "Alice",
  12337. * "htmlComment":
  12338. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  12339. * },
  12340. * { "name": "Bob",
  12341. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  12342. * }
  12343. * ]
  12344. * </file>
  12345. *
  12346. * <file name="protractor.js" type="protractor">
  12347. * describe('SCE doc demo', function() {
  12348. * it('should sanitize untrusted values', function() {
  12349. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  12350. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  12351. * });
  12352. *
  12353. * it('should NOT sanitize explicitly trusted values', function() {
  12354. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  12355. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  12356. * 'sanitization.&quot;">Hover over this text.</span>');
  12357. * });
  12358. * });
  12359. * </file>
  12360. * </example>
  12361. *
  12362. *
  12363. *
  12364. * ## Can I disable SCE completely?
  12365. *
  12366. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  12367. * for little coding overhead. It will be much harder to take an SCE disabled application and
  12368. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  12369. * for cases where you have a lot of existing code that was written before SCE was introduced and
  12370. * you're migrating them a module at a time.
  12371. *
  12372. * That said, here's how you can completely disable SCE:
  12373. *
  12374. * ```
  12375. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  12376. * // Completely disable SCE. For demonstration purposes only!
  12377. * // Do not use in new projects.
  12378. * $sceProvider.enabled(false);
  12379. * });
  12380. * ```
  12381. *
  12382. */
  12383. /* jshint maxlen: 100 */
  12384. function $SceProvider() {
  12385. var enabled = true;
  12386. /**
  12387. * @ngdoc method
  12388. * @name $sceProvider#enabled
  12389. * @kind function
  12390. *
  12391. * @param {boolean=} value If provided, then enables/disables SCE.
  12392. * @return {boolean} true if SCE is enabled, false otherwise.
  12393. *
  12394. * @description
  12395. * Enables/disables SCE and returns the current value.
  12396. */
  12397. this.enabled = function (value) {
  12398. if (arguments.length) {
  12399. enabled = !!value;
  12400. }
  12401. return enabled;
  12402. };
  12403. /* Design notes on the default implementation for SCE.
  12404. *
  12405. * The API contract for the SCE delegate
  12406. * -------------------------------------
  12407. * The SCE delegate object must provide the following 3 methods:
  12408. *
  12409. * - trustAs(contextEnum, value)
  12410. * This method is used to tell the SCE service that the provided value is OK to use in the
  12411. * contexts specified by contextEnum. It must return an object that will be accepted by
  12412. * getTrusted() for a compatible contextEnum and return this value.
  12413. *
  12414. * - valueOf(value)
  12415. * For values that were not produced by trustAs(), return them as is. For values that were
  12416. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  12417. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  12418. * such a value.
  12419. *
  12420. * - getTrusted(contextEnum, value)
  12421. * This function should return the a value that is safe to use in the context specified by
  12422. * contextEnum or throw and exception otherwise.
  12423. *
  12424. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  12425. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  12426. * instance, an implementation could maintain a registry of all trusted objects by context. In
  12427. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  12428. * return the same object passed in if it was found in the registry under a compatible context or
  12429. * throw an exception otherwise. An implementation might only wrap values some of the time based
  12430. * on some criteria. getTrusted() might return a value and not throw an exception for special
  12431. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  12432. *
  12433. *
  12434. * A note on the inheritance model for SCE contexts
  12435. * ------------------------------------------------
  12436. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  12437. * is purely an implementation details.
  12438. *
  12439. * The contract is simply this:
  12440. *
  12441. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  12442. * will also succeed.
  12443. *
  12444. * Inheritance happens to capture this in a natural way. In some future, we
  12445. * may not use inheritance anymore. That is OK because no code outside of
  12446. * sce.js and sceSpecs.js would need to be aware of this detail.
  12447. */
  12448. this.$get = ['$parse', '$sniffer', '$sceDelegate', function(
  12449. $parse, $sniffer, $sceDelegate) {
  12450. // Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
  12451. // the "expression(javascript expression)" syntax which is insecure.
  12452. if (enabled && $sniffer.msie && $sniffer.msieDocumentMode < 8) {
  12453. throw $sceMinErr('iequirks',
  12454. 'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
  12455. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  12456. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  12457. }
  12458. var sce = shallowCopy(SCE_CONTEXTS);
  12459. /**
  12460. * @ngdoc method
  12461. * @name $sce#isEnabled
  12462. * @kind function
  12463. *
  12464. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  12465. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  12466. *
  12467. * @description
  12468. * Returns a boolean indicating if SCE is enabled.
  12469. */
  12470. sce.isEnabled = function () {
  12471. return enabled;
  12472. };
  12473. sce.trustAs = $sceDelegate.trustAs;
  12474. sce.getTrusted = $sceDelegate.getTrusted;
  12475. sce.valueOf = $sceDelegate.valueOf;
  12476. if (!enabled) {
  12477. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  12478. sce.valueOf = identity;
  12479. }
  12480. /**
  12481. * @ngdoc method
  12482. * @name $sce#parseAs
  12483. *
  12484. * @description
  12485. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  12486. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  12487. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  12488. * *result*)}
  12489. *
  12490. * @param {string} type The kind of SCE context in which this result will be used.
  12491. * @param {string} expression String expression to compile.
  12492. * @returns {function(context, locals)} a function which represents the compiled expression:
  12493. *
  12494. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12495. * are evaluated against (typically a scope object).
  12496. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12497. * `context`.
  12498. */
  12499. sce.parseAs = function sceParseAs(type, expr) {
  12500. var parsed = $parse(expr);
  12501. if (parsed.literal && parsed.constant) {
  12502. return parsed;
  12503. } else {
  12504. return function sceParseAsTrusted(self, locals) {
  12505. return sce.getTrusted(type, parsed(self, locals));
  12506. };
  12507. }
  12508. };
  12509. /**
  12510. * @ngdoc method
  12511. * @name $sce#trustAs
  12512. *
  12513. * @description
  12514. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  12515. * returns an object that is trusted by angular for use in specified strict contextual
  12516. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  12517. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  12518. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  12519. * escaping.
  12520. *
  12521. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  12522. * resource_url, html, js and css.
  12523. * @param {*} value The value that that should be considered trusted/safe.
  12524. * @returns {*} A value that can be used to stand in for the provided `value` in places
  12525. * where Angular expects a $sce.trustAs() return value.
  12526. */
  12527. /**
  12528. * @ngdoc method
  12529. * @name $sce#trustAsHtml
  12530. *
  12531. * @description
  12532. * Shorthand method. `$sce.trustAsHtml(value)` →
  12533. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  12534. *
  12535. * @param {*} value The value to trustAs.
  12536. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  12537. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  12538. * only accept expressions that are either literal constants or are the
  12539. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12540. */
  12541. /**
  12542. * @ngdoc method
  12543. * @name $sce#trustAsUrl
  12544. *
  12545. * @description
  12546. * Shorthand method. `$sce.trustAsUrl(value)` →
  12547. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  12548. *
  12549. * @param {*} value The value to trustAs.
  12550. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  12551. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  12552. * only accept expressions that are either literal constants or are the
  12553. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12554. */
  12555. /**
  12556. * @ngdoc method
  12557. * @name $sce#trustAsResourceUrl
  12558. *
  12559. * @description
  12560. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  12561. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  12562. *
  12563. * @param {*} value The value to trustAs.
  12564. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  12565. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  12566. * only accept expressions that are either literal constants or are the return
  12567. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12568. */
  12569. /**
  12570. * @ngdoc method
  12571. * @name $sce#trustAsJs
  12572. *
  12573. * @description
  12574. * Shorthand method. `$sce.trustAsJs(value)` →
  12575. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  12576. *
  12577. * @param {*} value The value to trustAs.
  12578. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  12579. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  12580. * only accept expressions that are either literal constants or are the
  12581. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  12582. */
  12583. /**
  12584. * @ngdoc method
  12585. * @name $sce#getTrusted
  12586. *
  12587. * @description
  12588. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  12589. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  12590. * originally supplied value if the queried context type is a supertype of the created type.
  12591. * If this condition isn't satisfied, throws an exception.
  12592. *
  12593. * @param {string} type The kind of context in which this value is to be used.
  12594. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  12595. * call.
  12596. * @returns {*} The value the was originally provided to
  12597. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  12598. * Otherwise, throws an exception.
  12599. */
  12600. /**
  12601. * @ngdoc method
  12602. * @name $sce#getTrustedHtml
  12603. *
  12604. * @description
  12605. * Shorthand method. `$sce.getTrustedHtml(value)` →
  12606. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  12607. *
  12608. * @param {*} value The value to pass to `$sce.getTrusted`.
  12609. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  12610. */
  12611. /**
  12612. * @ngdoc method
  12613. * @name $sce#getTrustedCss
  12614. *
  12615. * @description
  12616. * Shorthand method. `$sce.getTrustedCss(value)` →
  12617. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  12618. *
  12619. * @param {*} value The value to pass to `$sce.getTrusted`.
  12620. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  12621. */
  12622. /**
  12623. * @ngdoc method
  12624. * @name $sce#getTrustedUrl
  12625. *
  12626. * @description
  12627. * Shorthand method. `$sce.getTrustedUrl(value)` →
  12628. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  12629. *
  12630. * @param {*} value The value to pass to `$sce.getTrusted`.
  12631. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  12632. */
  12633. /**
  12634. * @ngdoc method
  12635. * @name $sce#getTrustedResourceUrl
  12636. *
  12637. * @description
  12638. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  12639. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  12640. *
  12641. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  12642. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  12643. */
  12644. /**
  12645. * @ngdoc method
  12646. * @name $sce#getTrustedJs
  12647. *
  12648. * @description
  12649. * Shorthand method. `$sce.getTrustedJs(value)` →
  12650. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  12651. *
  12652. * @param {*} value The value to pass to `$sce.getTrusted`.
  12653. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  12654. */
  12655. /**
  12656. * @ngdoc method
  12657. * @name $sce#parseAsHtml
  12658. *
  12659. * @description
  12660. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  12661. * {@link ng.$sce#parse `$sce.parseAs($sce.HTML, value)`}
  12662. *
  12663. * @param {string} expression String expression to compile.
  12664. * @returns {function(context, locals)} a function which represents the compiled expression:
  12665. *
  12666. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12667. * are evaluated against (typically a scope object).
  12668. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12669. * `context`.
  12670. */
  12671. /**
  12672. * @ngdoc method
  12673. * @name $sce#parseAsCss
  12674. *
  12675. * @description
  12676. * Shorthand method. `$sce.parseAsCss(value)` →
  12677. * {@link ng.$sce#parse `$sce.parseAs($sce.CSS, value)`}
  12678. *
  12679. * @param {string} expression String expression to compile.
  12680. * @returns {function(context, locals)} a function which represents the compiled expression:
  12681. *
  12682. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12683. * are evaluated against (typically a scope object).
  12684. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12685. * `context`.
  12686. */
  12687. /**
  12688. * @ngdoc method
  12689. * @name $sce#parseAsUrl
  12690. *
  12691. * @description
  12692. * Shorthand method. `$sce.parseAsUrl(value)` →
  12693. * {@link ng.$sce#parse `$sce.parseAs($sce.URL, value)`}
  12694. *
  12695. * @param {string} expression String expression to compile.
  12696. * @returns {function(context, locals)} a function which represents the compiled expression:
  12697. *
  12698. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12699. * are evaluated against (typically a scope object).
  12700. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12701. * `context`.
  12702. */
  12703. /**
  12704. * @ngdoc method
  12705. * @name $sce#parseAsResourceUrl
  12706. *
  12707. * @description
  12708. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  12709. * {@link ng.$sce#parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
  12710. *
  12711. * @param {string} expression String expression to compile.
  12712. * @returns {function(context, locals)} a function which represents the compiled expression:
  12713. *
  12714. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12715. * are evaluated against (typically a scope object).
  12716. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12717. * `context`.
  12718. */
  12719. /**
  12720. * @ngdoc method
  12721. * @name $sce#parseAsJs
  12722. *
  12723. * @description
  12724. * Shorthand method. `$sce.parseAsJs(value)` →
  12725. * {@link ng.$sce#parse `$sce.parseAs($sce.JS, value)`}
  12726. *
  12727. * @param {string} expression String expression to compile.
  12728. * @returns {function(context, locals)} a function which represents the compiled expression:
  12729. *
  12730. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12731. * are evaluated against (typically a scope object).
  12732. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12733. * `context`.
  12734. */
  12735. // Shorthand delegations.
  12736. var parse = sce.parseAs,
  12737. getTrusted = sce.getTrusted,
  12738. trustAs = sce.trustAs;
  12739. forEach(SCE_CONTEXTS, function (enumValue, name) {
  12740. var lName = lowercase(name);
  12741. sce[camelCase("parse_as_" + lName)] = function (expr) {
  12742. return parse(enumValue, expr);
  12743. };
  12744. sce[camelCase("get_trusted_" + lName)] = function (value) {
  12745. return getTrusted(enumValue, value);
  12746. };
  12747. sce[camelCase("trust_as_" + lName)] = function (value) {
  12748. return trustAs(enumValue, value);
  12749. };
  12750. });
  12751. return sce;
  12752. }];
  12753. }
  12754. /**
  12755. * !!! This is an undocumented "private" service !!!
  12756. *
  12757. * @name $sniffer
  12758. * @requires $window
  12759. * @requires $document
  12760. *
  12761. * @property {boolean} history Does the browser support html5 history api ?
  12762. * @property {boolean} hashchange Does the browser support hashchange event ?
  12763. * @property {boolean} transitions Does the browser support CSS transition events ?
  12764. * @property {boolean} animations Does the browser support CSS animation events ?
  12765. *
  12766. * @description
  12767. * This is very simple implementation of testing browser's features.
  12768. */
  12769. function $SnifferProvider() {
  12770. this.$get = ['$window', '$document', function($window, $document) {
  12771. var eventSupport = {},
  12772. android =
  12773. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  12774. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  12775. document = $document[0] || {},
  12776. documentMode = document.documentMode,
  12777. vendorPrefix,
  12778. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  12779. bodyStyle = document.body && document.body.style,
  12780. transitions = false,
  12781. animations = false,
  12782. match;
  12783. if (bodyStyle) {
  12784. for(var prop in bodyStyle) {
  12785. if(match = vendorRegex.exec(prop)) {
  12786. vendorPrefix = match[0];
  12787. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  12788. break;
  12789. }
  12790. }
  12791. if(!vendorPrefix) {
  12792. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  12793. }
  12794. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  12795. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  12796. if (android && (!transitions||!animations)) {
  12797. transitions = isString(document.body.style.webkitTransition);
  12798. animations = isString(document.body.style.webkitAnimation);
  12799. }
  12800. }
  12801. return {
  12802. // Android has history.pushState, but it does not update location correctly
  12803. // so let's not use the history API at all.
  12804. // http://code.google.com/p/android/issues/detail?id=17471
  12805. // https://github.com/angular/angular.js/issues/904
  12806. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  12807. // so let's not use the history API also
  12808. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  12809. // jshint -W018
  12810. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  12811. // jshint +W018
  12812. hashchange: 'onhashchange' in $window &&
  12813. // IE8 compatible mode lies
  12814. (!documentMode || documentMode > 7),
  12815. hasEvent: function(event) {
  12816. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  12817. // it. In particular the event is not fired when backspace or delete key are pressed or
  12818. // when cut operation is performed.
  12819. if (event == 'input' && msie == 9) return false;
  12820. if (isUndefined(eventSupport[event])) {
  12821. var divElm = document.createElement('div');
  12822. eventSupport[event] = 'on' + event in divElm;
  12823. }
  12824. return eventSupport[event];
  12825. },
  12826. csp: csp(),
  12827. vendorPrefix: vendorPrefix,
  12828. transitions : transitions,
  12829. animations : animations,
  12830. android: android,
  12831. msie : msie,
  12832. msieDocumentMode: documentMode
  12833. };
  12834. }];
  12835. }
  12836. function $TimeoutProvider() {
  12837. this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
  12838. function($rootScope, $browser, $q, $exceptionHandler) {
  12839. var deferreds = {};
  12840. /**
  12841. * @ngdoc service
  12842. * @name $timeout
  12843. *
  12844. * @description
  12845. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  12846. * block and delegates any exceptions to
  12847. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12848. *
  12849. * The return value of registering a timeout function is a promise, which will be resolved when
  12850. * the timeout is reached and the timeout function is executed.
  12851. *
  12852. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  12853. *
  12854. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  12855. * synchronously flush the queue of deferred functions.
  12856. *
  12857. * @param {function()} fn A function, whose execution should be delayed.
  12858. * @param {number=} [delay=0] Delay in milliseconds.
  12859. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  12860. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  12861. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  12862. * promise will be resolved with is the return value of the `fn` function.
  12863. *
  12864. */
  12865. function timeout(fn, delay, invokeApply) {
  12866. var deferred = $q.defer(),
  12867. promise = deferred.promise,
  12868. skipApply = (isDefined(invokeApply) && !invokeApply),
  12869. timeoutId;
  12870. timeoutId = $browser.defer(function() {
  12871. try {
  12872. deferred.resolve(fn());
  12873. } catch(e) {
  12874. deferred.reject(e);
  12875. $exceptionHandler(e);
  12876. }
  12877. finally {
  12878. delete deferreds[promise.$$timeoutId];
  12879. }
  12880. if (!skipApply) $rootScope.$apply();
  12881. }, delay);
  12882. promise.$$timeoutId = timeoutId;
  12883. deferreds[timeoutId] = deferred;
  12884. return promise;
  12885. }
  12886. /**
  12887. * @ngdoc method
  12888. * @name $timeout#cancel
  12889. *
  12890. * @description
  12891. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  12892. * resolved with a rejection.
  12893. *
  12894. * @param {Promise=} promise Promise returned by the `$timeout` function.
  12895. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  12896. * canceled.
  12897. */
  12898. timeout.cancel = function(promise) {
  12899. if (promise && promise.$$timeoutId in deferreds) {
  12900. deferreds[promise.$$timeoutId].reject('canceled');
  12901. delete deferreds[promise.$$timeoutId];
  12902. return $browser.defer.cancel(promise.$$timeoutId);
  12903. }
  12904. return false;
  12905. };
  12906. return timeout;
  12907. }];
  12908. }
  12909. // NOTE: The usage of window and document instead of $window and $document here is
  12910. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  12911. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  12912. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  12913. // doesn't know about mocked locations and resolves URLs to the real document - which is
  12914. // exactly the behavior needed here. There is little value is mocking these out for this
  12915. // service.
  12916. var urlParsingNode = document.createElement("a");
  12917. var originUrl = urlResolve(window.location.href, true);
  12918. /**
  12919. *
  12920. * Implementation Notes for non-IE browsers
  12921. * ----------------------------------------
  12922. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  12923. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  12924. * URL will be resolved into an absolute URL in the context of the application document.
  12925. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  12926. * properties are all populated to reflect the normalized URL. This approach has wide
  12927. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  12928. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12929. *
  12930. * Implementation Notes for IE
  12931. * ---------------------------
  12932. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  12933. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  12934. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  12935. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  12936. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  12937. * properties such as protocol, hostname, port, etc.
  12938. *
  12939. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  12940. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  12941. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  12942. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  12943. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  12944. * method and IE < 8 is unsupported.
  12945. *
  12946. * References:
  12947. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  12948. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  12949. * http://url.spec.whatwg.org/#urlutils
  12950. * https://github.com/angular/angular.js/pull/2902
  12951. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  12952. *
  12953. * @kind function
  12954. * @param {string} url The URL to be parsed.
  12955. * @description Normalizes and parses a URL.
  12956. * @returns {object} Returns the normalized URL as a dictionary.
  12957. *
  12958. * | member name | Description |
  12959. * |---------------|----------------|
  12960. * | href | A normalized version of the provided URL if it was not an absolute URL |
  12961. * | protocol | The protocol including the trailing colon |
  12962. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  12963. * | search | The search params, minus the question mark |
  12964. * | hash | The hash string, minus the hash symbol
  12965. * | hostname | The hostname
  12966. * | port | The port, without ":"
  12967. * | pathname | The pathname, beginning with "/"
  12968. *
  12969. */
  12970. function urlResolve(url, base) {
  12971. var href = url;
  12972. if (msie) {
  12973. // Normalize before parse. Refer Implementation Notes on why this is
  12974. // done in two steps on IE.
  12975. urlParsingNode.setAttribute("href", href);
  12976. href = urlParsingNode.href;
  12977. }
  12978. urlParsingNode.setAttribute('href', href);
  12979. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  12980. return {
  12981. href: urlParsingNode.href,
  12982. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  12983. host: urlParsingNode.host,
  12984. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  12985. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  12986. hostname: urlParsingNode.hostname,
  12987. port: urlParsingNode.port,
  12988. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  12989. ? urlParsingNode.pathname
  12990. : '/' + urlParsingNode.pathname
  12991. };
  12992. }
  12993. /**
  12994. * Parse a request URL and determine whether this is a same-origin request as the application document.
  12995. *
  12996. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  12997. * or a parsed URL object.
  12998. * @returns {boolean} Whether the request is for the same origin as the application document.
  12999. */
  13000. function urlIsSameOrigin(requestUrl) {
  13001. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  13002. return (parsed.protocol === originUrl.protocol &&
  13003. parsed.host === originUrl.host);
  13004. }
  13005. /**
  13006. * @ngdoc service
  13007. * @name $window
  13008. *
  13009. * @description
  13010. * A reference to the browser's `window` object. While `window`
  13011. * is globally available in JavaScript, it causes testability problems, because
  13012. * it is a global variable. In angular we always refer to it through the
  13013. * `$window` service, so it may be overridden, removed or mocked for testing.
  13014. *
  13015. * Expressions, like the one defined for the `ngClick` directive in the example
  13016. * below, are evaluated with respect to the current scope. Therefore, there is
  13017. * no risk of inadvertently coding in a dependency on a global value in such an
  13018. * expression.
  13019. *
  13020. * @example
  13021. <example module="windowExample">
  13022. <file name="index.html">
  13023. <script>
  13024. angular.module('windowExample', [])
  13025. .controller('ExampleController', ['$scope', '$window', function ($scope, $window) {
  13026. $scope.greeting = 'Hello, World!';
  13027. $scope.doGreeting = function(greeting) {
  13028. $window.alert(greeting);
  13029. };
  13030. }]);
  13031. </script>
  13032. <div ng-controller="ExampleController">
  13033. <input type="text" ng-model="greeting" />
  13034. <button ng-click="doGreeting(greeting)">ALERT</button>
  13035. </div>
  13036. </file>
  13037. <file name="protractor.js" type="protractor">
  13038. it('should display the greeting in the input box', function() {
  13039. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  13040. // If we click the button it will block the test runner
  13041. // element(':button').click();
  13042. });
  13043. </file>
  13044. </example>
  13045. */
  13046. function $WindowProvider(){
  13047. this.$get = valueFn(window);
  13048. }
  13049. /* global currencyFilter: true,
  13050. dateFilter: true,
  13051. filterFilter: true,
  13052. jsonFilter: true,
  13053. limitToFilter: true,
  13054. lowercaseFilter: true,
  13055. numberFilter: true,
  13056. orderByFilter: true,
  13057. uppercaseFilter: true,
  13058. */
  13059. /**
  13060. * @ngdoc provider
  13061. * @name $filterProvider
  13062. * @description
  13063. *
  13064. * Filters are just functions which transform input to an output. However filters need to be
  13065. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  13066. * annotated with dependencies and is responsible for creating a filter function.
  13067. *
  13068. * ```js
  13069. * // Filter registration
  13070. * function MyModule($provide, $filterProvider) {
  13071. * // create a service to demonstrate injection (not always needed)
  13072. * $provide.value('greet', function(name){
  13073. * return 'Hello ' + name + '!';
  13074. * });
  13075. *
  13076. * // register a filter factory which uses the
  13077. * // greet service to demonstrate DI.
  13078. * $filterProvider.register('greet', function(greet){
  13079. * // return the filter function which uses the greet service
  13080. * // to generate salutation
  13081. * return function(text) {
  13082. * // filters need to be forgiving so check input validity
  13083. * return text && greet(text) || text;
  13084. * };
  13085. * });
  13086. * }
  13087. * ```
  13088. *
  13089. * The filter function is registered with the `$injector` under the filter name suffix with
  13090. * `Filter`.
  13091. *
  13092. * ```js
  13093. * it('should be the same instance', inject(
  13094. * function($filterProvider) {
  13095. * $filterProvider.register('reverse', function(){
  13096. * return ...;
  13097. * });
  13098. * },
  13099. * function($filter, reverseFilter) {
  13100. * expect($filter('reverse')).toBe(reverseFilter);
  13101. * });
  13102. * ```
  13103. *
  13104. *
  13105. * For more information about how angular filters work, and how to create your own filters, see
  13106. * {@link guide/filter Filters} in the Angular Developer Guide.
  13107. */
  13108. /**
  13109. * @ngdoc method
  13110. * @name $filterProvider#register
  13111. * @description
  13112. * Register filter factory function.
  13113. *
  13114. * @param {String} name Name of the filter.
  13115. * @param {Function} fn The filter factory function which is injectable.
  13116. */
  13117. /**
  13118. * @ngdoc service
  13119. * @name $filter
  13120. * @kind function
  13121. * @description
  13122. * Filters are used for formatting data displayed to the user.
  13123. *
  13124. * The general syntax in templates is as follows:
  13125. *
  13126. * {{ expression [| filter_name[:parameter_value] ... ] }}
  13127. *
  13128. * @param {String} name Name of the filter function to retrieve
  13129. * @return {Function} the filter function
  13130. * @example
  13131. <example name="$filter" module="filterExample">
  13132. <file name="index.html">
  13133. <div ng-controller="MainCtrl">
  13134. <h3>{{ originalText }}</h3>
  13135. <h3>{{ filteredText }}</h3>
  13136. </div>
  13137. </file>
  13138. <file name="script.js">
  13139. angular.module('filterExample', [])
  13140. .controller('MainCtrl', function($scope, $filter) {
  13141. $scope.originalText = 'hello';
  13142. $scope.filteredText = $filter('uppercase')($scope.originalText);
  13143. });
  13144. </file>
  13145. </example>
  13146. */
  13147. $FilterProvider.$inject = ['$provide'];
  13148. function $FilterProvider($provide) {
  13149. var suffix = 'Filter';
  13150. /**
  13151. * @ngdoc method
  13152. * @name $controllerProvider#register
  13153. * @param {string|Object} name Name of the filter function, or an object map of filters where
  13154. * the keys are the filter names and the values are the filter factories.
  13155. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  13156. * of the registered filter instances.
  13157. */
  13158. function register(name, factory) {
  13159. if(isObject(name)) {
  13160. var filters = {};
  13161. forEach(name, function(filter, key) {
  13162. filters[key] = register(key, filter);
  13163. });
  13164. return filters;
  13165. } else {
  13166. return $provide.factory(name + suffix, factory);
  13167. }
  13168. }
  13169. this.register = register;
  13170. this.$get = ['$injector', function($injector) {
  13171. return function(name) {
  13172. return $injector.get(name + suffix);
  13173. };
  13174. }];
  13175. ////////////////////////////////////////
  13176. /* global
  13177. currencyFilter: false,
  13178. dateFilter: false,
  13179. filterFilter: false,
  13180. jsonFilter: false,
  13181. limitToFilter: false,
  13182. lowercaseFilter: false,
  13183. numberFilter: false,
  13184. orderByFilter: false,
  13185. uppercaseFilter: false,
  13186. */
  13187. register('currency', currencyFilter);
  13188. register('date', dateFilter);
  13189. register('filter', filterFilter);
  13190. register('json', jsonFilter);
  13191. register('limitTo', limitToFilter);
  13192. register('lowercase', lowercaseFilter);
  13193. register('number', numberFilter);
  13194. register('orderBy', orderByFilter);
  13195. register('uppercase', uppercaseFilter);
  13196. }
  13197. /**
  13198. * @ngdoc filter
  13199. * @name filter
  13200. * @kind function
  13201. *
  13202. * @description
  13203. * Selects a subset of items from `array` and returns it as a new array.
  13204. *
  13205. * @param {Array} array The source array.
  13206. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  13207. * `array`.
  13208. *
  13209. * Can be one of:
  13210. *
  13211. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  13212. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  13213. * will be returned. The predicate can be negated by prefixing the string with `!`.
  13214. *
  13215. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  13216. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  13217. * which have property `name` containing "M" and property `phone` containing "1". A special
  13218. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  13219. * property of the object. That's equivalent to the simple substring match with a `string`
  13220. * as described above.
  13221. *
  13222. * - `function(value)`: A predicate function can be used to write arbitrary filters. The function is
  13223. * called for each element of `array`. The final result is an array of those elements that
  13224. * the predicate returned true for.
  13225. *
  13226. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  13227. * determining if the expected value (from the filter expression) and actual value (from
  13228. * the object in the array) should be considered a match.
  13229. *
  13230. * Can be one of:
  13231. *
  13232. * - `function(actual, expected)`:
  13233. * The function will be given the object value and the predicate value to compare and
  13234. * should return true if the item should be included in filtered result.
  13235. *
  13236. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  13237. * this is essentially strict comparison of expected and actual.
  13238. *
  13239. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  13240. * insensitive way.
  13241. *
  13242. * @example
  13243. <example>
  13244. <file name="index.html">
  13245. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  13246. {name:'Mary', phone:'800-BIG-MARY'},
  13247. {name:'Mike', phone:'555-4321'},
  13248. {name:'Adam', phone:'555-5678'},
  13249. {name:'Julie', phone:'555-8765'},
  13250. {name:'Juliette', phone:'555-5678'}]"></div>
  13251. Search: <input ng-model="searchText">
  13252. <table id="searchTextResults">
  13253. <tr><th>Name</th><th>Phone</th></tr>
  13254. <tr ng-repeat="friend in friends | filter:searchText">
  13255. <td>{{friend.name}}</td>
  13256. <td>{{friend.phone}}</td>
  13257. </tr>
  13258. </table>
  13259. <hr>
  13260. Any: <input ng-model="search.$"> <br>
  13261. Name only <input ng-model="search.name"><br>
  13262. Phone only <input ng-model="search.phone"><br>
  13263. Equality <input type="checkbox" ng-model="strict"><br>
  13264. <table id="searchObjResults">
  13265. <tr><th>Name</th><th>Phone</th></tr>
  13266. <tr ng-repeat="friendObj in friends | filter:search:strict">
  13267. <td>{{friendObj.name}}</td>
  13268. <td>{{friendObj.phone}}</td>
  13269. </tr>
  13270. </table>
  13271. </file>
  13272. <file name="protractor.js" type="protractor">
  13273. var expectFriendNames = function(expectedNames, key) {
  13274. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  13275. arr.forEach(function(wd, i) {
  13276. expect(wd.getText()).toMatch(expectedNames[i]);
  13277. });
  13278. });
  13279. };
  13280. it('should search across all fields when filtering with a string', function() {
  13281. var searchText = element(by.model('searchText'));
  13282. searchText.clear();
  13283. searchText.sendKeys('m');
  13284. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  13285. searchText.clear();
  13286. searchText.sendKeys('76');
  13287. expectFriendNames(['John', 'Julie'], 'friend');
  13288. });
  13289. it('should search in specific fields when filtering with a predicate object', function() {
  13290. var searchAny = element(by.model('search.$'));
  13291. searchAny.clear();
  13292. searchAny.sendKeys('i');
  13293. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  13294. });
  13295. it('should use a equal comparison when comparator is true', function() {
  13296. var searchName = element(by.model('search.name'));
  13297. var strict = element(by.model('strict'));
  13298. searchName.clear();
  13299. searchName.sendKeys('Julie');
  13300. strict.click();
  13301. expectFriendNames(['Julie'], 'friendObj');
  13302. });
  13303. </file>
  13304. </example>
  13305. */
  13306. function filterFilter() {
  13307. return function(array, expression, comparator) {
  13308. if (!isArray(array)) return array;
  13309. var comparatorType = typeof(comparator),
  13310. predicates = [];
  13311. predicates.check = function(value) {
  13312. for (var j = 0; j < predicates.length; j++) {
  13313. if(!predicates[j](value)) {
  13314. return false;
  13315. }
  13316. }
  13317. return true;
  13318. };
  13319. if (comparatorType !== 'function') {
  13320. if (comparatorType === 'boolean' && comparator) {
  13321. comparator = function(obj, text) {
  13322. return angular.equals(obj, text);
  13323. };
  13324. } else {
  13325. comparator = function(obj, text) {
  13326. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  13327. for (var objKey in obj) {
  13328. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  13329. comparator(obj[objKey], text[objKey])) {
  13330. return true;
  13331. }
  13332. }
  13333. return false;
  13334. }
  13335. text = (''+text).toLowerCase();
  13336. return (''+obj).toLowerCase().indexOf(text) > -1;
  13337. };
  13338. }
  13339. }
  13340. var search = function(obj, text){
  13341. if (typeof text == 'string' && text.charAt(0) === '!') {
  13342. return !search(obj, text.substr(1));
  13343. }
  13344. switch (typeof obj) {
  13345. case "boolean":
  13346. case "number":
  13347. case "string":
  13348. return comparator(obj, text);
  13349. case "object":
  13350. switch (typeof text) {
  13351. case "object":
  13352. return comparator(obj, text);
  13353. default:
  13354. for ( var objKey in obj) {
  13355. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  13356. return true;
  13357. }
  13358. }
  13359. break;
  13360. }
  13361. return false;
  13362. case "array":
  13363. for ( var i = 0; i < obj.length; i++) {
  13364. if (search(obj[i], text)) {
  13365. return true;
  13366. }
  13367. }
  13368. return false;
  13369. default:
  13370. return false;
  13371. }
  13372. };
  13373. switch (typeof expression) {
  13374. case "boolean":
  13375. case "number":
  13376. case "string":
  13377. // Set up expression object and fall through
  13378. expression = {$:expression};
  13379. // jshint -W086
  13380. case "object":
  13381. // jshint +W086
  13382. for (var key in expression) {
  13383. (function(path) {
  13384. if (typeof expression[path] === 'undefined') return;
  13385. predicates.push(function(value) {
  13386. return search(path == '$' ? value : (value && value[path]), expression[path]);
  13387. });
  13388. })(key);
  13389. }
  13390. break;
  13391. case 'function':
  13392. predicates.push(expression);
  13393. break;
  13394. default:
  13395. return array;
  13396. }
  13397. var filtered = [];
  13398. for ( var j = 0; j < array.length; j++) {
  13399. var value = array[j];
  13400. if (predicates.check(value)) {
  13401. filtered.push(value);
  13402. }
  13403. }
  13404. return filtered;
  13405. };
  13406. }
  13407. /**
  13408. * @ngdoc filter
  13409. * @name currency
  13410. * @kind function
  13411. *
  13412. * @description
  13413. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  13414. * symbol for current locale is used.
  13415. *
  13416. * @param {number} amount Input to filter.
  13417. * @param {string=} symbol Currency symbol or identifier to be displayed.
  13418. * @returns {string} Formatted number.
  13419. *
  13420. *
  13421. * @example
  13422. <example module="currencyExample">
  13423. <file name="index.html">
  13424. <script>
  13425. angular.module('currencyExample', [])
  13426. .controller('ExampleController', ['$scope', function($scope) {
  13427. $scope.amount = 1234.56;
  13428. }]);
  13429. </script>
  13430. <div ng-controller="ExampleController">
  13431. <input type="number" ng-model="amount"> <br>
  13432. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  13433. custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
  13434. </div>
  13435. </file>
  13436. <file name="protractor.js" type="protractor">
  13437. it('should init with 1234.56', function() {
  13438. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  13439. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('USD$1,234.56');
  13440. });
  13441. it('should update', function() {
  13442. if (browser.params.browser == 'safari') {
  13443. // Safari does not understand the minus key. See
  13444. // https://github.com/angular/protractor/issues/481
  13445. return;
  13446. }
  13447. element(by.model('amount')).clear();
  13448. element(by.model('amount')).sendKeys('-1234');
  13449. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  13450. expect(element(by.binding('amount | currency:"USD$"')).getText()).toBe('(USD$1,234.00)');
  13451. });
  13452. </file>
  13453. </example>
  13454. */
  13455. currencyFilter.$inject = ['$locale'];
  13456. function currencyFilter($locale) {
  13457. var formats = $locale.NUMBER_FORMATS;
  13458. return function(amount, currencySymbol){
  13459. if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
  13460. return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
  13461. replace(/\u00A4/g, currencySymbol);
  13462. };
  13463. }
  13464. /**
  13465. * @ngdoc filter
  13466. * @name number
  13467. * @kind function
  13468. *
  13469. * @description
  13470. * Formats a number as text.
  13471. *
  13472. * If the input is not a number an empty string is returned.
  13473. *
  13474. * @param {number|string} number Number to format.
  13475. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  13476. * If this is not provided then the fraction size is computed from the current locale's number
  13477. * formatting pattern. In the case of the default locale, it will be 3.
  13478. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  13479. *
  13480. * @example
  13481. <example module="numberFilterExample">
  13482. <file name="index.html">
  13483. <script>
  13484. angular.module('numberFilterExample', [])
  13485. .controller('ExampleController', ['$scope', function($scope) {
  13486. $scope.val = 1234.56789;
  13487. }]);
  13488. </script>
  13489. <div ng-controller="ExampleController">
  13490. Enter number: <input ng-model='val'><br>
  13491. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  13492. No fractions: <span>{{val | number:0}}</span><br>
  13493. Negative number: <span>{{-val | number:4}}</span>
  13494. </div>
  13495. </file>
  13496. <file name="protractor.js" type="protractor">
  13497. it('should format numbers', function() {
  13498. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  13499. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  13500. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  13501. });
  13502. it('should update', function() {
  13503. element(by.model('val')).clear();
  13504. element(by.model('val')).sendKeys('3374.333');
  13505. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  13506. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  13507. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  13508. });
  13509. </file>
  13510. </example>
  13511. */
  13512. numberFilter.$inject = ['$locale'];
  13513. function numberFilter($locale) {
  13514. var formats = $locale.NUMBER_FORMATS;
  13515. return function(number, fractionSize) {
  13516. return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  13517. fractionSize);
  13518. };
  13519. }
  13520. var DECIMAL_SEP = '.';
  13521. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  13522. if (number == null || !isFinite(number) || isObject(number)) return '';
  13523. var isNegative = number < 0;
  13524. number = Math.abs(number);
  13525. var numStr = number + '',
  13526. formatedText = '',
  13527. parts = [];
  13528. var hasExponent = false;
  13529. if (numStr.indexOf('e') !== -1) {
  13530. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  13531. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  13532. numStr = '0';
  13533. number = 0;
  13534. } else {
  13535. formatedText = numStr;
  13536. hasExponent = true;
  13537. }
  13538. }
  13539. if (!hasExponent) {
  13540. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  13541. // determine fractionSize if it is not specified
  13542. if (isUndefined(fractionSize)) {
  13543. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  13544. }
  13545. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  13546. // inspired by:
  13547. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  13548. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  13549. var fraction = ('' + number).split(DECIMAL_SEP);
  13550. var whole = fraction[0];
  13551. fraction = fraction[1] || '';
  13552. var i, pos = 0,
  13553. lgroup = pattern.lgSize,
  13554. group = pattern.gSize;
  13555. if (whole.length >= (lgroup + group)) {
  13556. pos = whole.length - lgroup;
  13557. for (i = 0; i < pos; i++) {
  13558. if ((pos - i)%group === 0 && i !== 0) {
  13559. formatedText += groupSep;
  13560. }
  13561. formatedText += whole.charAt(i);
  13562. }
  13563. }
  13564. for (i = pos; i < whole.length; i++) {
  13565. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  13566. formatedText += groupSep;
  13567. }
  13568. formatedText += whole.charAt(i);
  13569. }
  13570. // format fraction part.
  13571. while(fraction.length < fractionSize) {
  13572. fraction += '0';
  13573. }
  13574. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  13575. } else {
  13576. if (fractionSize > 0 && number > -1 && number < 1) {
  13577. formatedText = number.toFixed(fractionSize);
  13578. }
  13579. }
  13580. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  13581. parts.push(formatedText);
  13582. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  13583. return parts.join('');
  13584. }
  13585. function padNumber(num, digits, trim) {
  13586. var neg = '';
  13587. if (num < 0) {
  13588. neg = '-';
  13589. num = -num;
  13590. }
  13591. num = '' + num;
  13592. while(num.length < digits) num = '0' + num;
  13593. if (trim)
  13594. num = num.substr(num.length - digits);
  13595. return neg + num;
  13596. }
  13597. function dateGetter(name, size, offset, trim) {
  13598. offset = offset || 0;
  13599. return function(date) {
  13600. var value = date['get' + name]();
  13601. if (offset > 0 || value > -offset)
  13602. value += offset;
  13603. if (value === 0 && offset == -12 ) value = 12;
  13604. return padNumber(value, size, trim);
  13605. };
  13606. }
  13607. function dateStrGetter(name, shortForm) {
  13608. return function(date, formats) {
  13609. var value = date['get' + name]();
  13610. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  13611. return formats[get][value];
  13612. };
  13613. }
  13614. function timeZoneGetter(date) {
  13615. var zone = -1 * date.getTimezoneOffset();
  13616. var paddedZone = (zone >= 0) ? "+" : "";
  13617. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  13618. padNumber(Math.abs(zone % 60), 2);
  13619. return paddedZone;
  13620. }
  13621. function ampmGetter(date, formats) {
  13622. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  13623. }
  13624. var DATE_FORMATS = {
  13625. yyyy: dateGetter('FullYear', 4),
  13626. yy: dateGetter('FullYear', 2, 0, true),
  13627. y: dateGetter('FullYear', 1),
  13628. MMMM: dateStrGetter('Month'),
  13629. MMM: dateStrGetter('Month', true),
  13630. MM: dateGetter('Month', 2, 1),
  13631. M: dateGetter('Month', 1, 1),
  13632. dd: dateGetter('Date', 2),
  13633. d: dateGetter('Date', 1),
  13634. HH: dateGetter('Hours', 2),
  13635. H: dateGetter('Hours', 1),
  13636. hh: dateGetter('Hours', 2, -12),
  13637. h: dateGetter('Hours', 1, -12),
  13638. mm: dateGetter('Minutes', 2),
  13639. m: dateGetter('Minutes', 1),
  13640. ss: dateGetter('Seconds', 2),
  13641. s: dateGetter('Seconds', 1),
  13642. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  13643. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  13644. sss: dateGetter('Milliseconds', 3),
  13645. EEEE: dateStrGetter('Day'),
  13646. EEE: dateStrGetter('Day', true),
  13647. a: ampmGetter,
  13648. Z: timeZoneGetter
  13649. };
  13650. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
  13651. NUMBER_STRING = /^\-?\d+$/;
  13652. /**
  13653. * @ngdoc filter
  13654. * @name date
  13655. * @kind function
  13656. *
  13657. * @description
  13658. * Formats `date` to a string based on the requested `format`.
  13659. *
  13660. * `format` string can be composed of the following elements:
  13661. *
  13662. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  13663. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  13664. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  13665. * * `'MMMM'`: Month in year (January-December)
  13666. * * `'MMM'`: Month in year (Jan-Dec)
  13667. * * `'MM'`: Month in year, padded (01-12)
  13668. * * `'M'`: Month in year (1-12)
  13669. * * `'dd'`: Day in month, padded (01-31)
  13670. * * `'d'`: Day in month (1-31)
  13671. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  13672. * * `'EEE'`: Day in Week, (Sun-Sat)
  13673. * * `'HH'`: Hour in day, padded (00-23)
  13674. * * `'H'`: Hour in day (0-23)
  13675. * * `'hh'`: Hour in am/pm, padded (01-12)
  13676. * * `'h'`: Hour in am/pm, (1-12)
  13677. * * `'mm'`: Minute in hour, padded (00-59)
  13678. * * `'m'`: Minute in hour (0-59)
  13679. * * `'ss'`: Second in minute, padded (00-59)
  13680. * * `'s'`: Second in minute (0-59)
  13681. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  13682. * * `'a'`: am/pm marker
  13683. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  13684. *
  13685. * `format` string can also be one of the following predefined
  13686. * {@link guide/i18n localizable formats}:
  13687. *
  13688. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  13689. * (e.g. Sep 3, 2010 12:05:08 pm)
  13690. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
  13691. * * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
  13692. * (e.g. Friday, September 3, 2010)
  13693. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  13694. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  13695. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  13696. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
  13697. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
  13698. *
  13699. * `format` string can contain literal values. These need to be quoted with single quotes (e.g.
  13700. * `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
  13701. * (e.g. `"h 'o''clock'"`).
  13702. *
  13703. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  13704. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
  13705. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  13706. * specified in the string input, the time is considered to be in the local timezone.
  13707. * @param {string=} format Formatting rules (see Description). If not specified,
  13708. * `mediumDate` is used.
  13709. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  13710. *
  13711. * @example
  13712. <example>
  13713. <file name="index.html">
  13714. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  13715. <span>{{1288323623006 | date:'medium'}}</span><br>
  13716. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  13717. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  13718. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  13719. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  13720. </file>
  13721. <file name="protractor.js" type="protractor">
  13722. it('should format date', function() {
  13723. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  13724. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  13725. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  13726. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  13727. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  13728. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  13729. });
  13730. </file>
  13731. </example>
  13732. */
  13733. dateFilter.$inject = ['$locale'];
  13734. function dateFilter($locale) {
  13735. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  13736. // 1 2 3 4 5 6 7 8 9 10 11
  13737. function jsonStringToDate(string) {
  13738. var match;
  13739. if (match = string.match(R_ISO8601_STR)) {
  13740. var date = new Date(0),
  13741. tzHour = 0,
  13742. tzMin = 0,
  13743. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  13744. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  13745. if (match[9]) {
  13746. tzHour = int(match[9] + match[10]);
  13747. tzMin = int(match[9] + match[11]);
  13748. }
  13749. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  13750. var h = int(match[4]||0) - tzHour;
  13751. var m = int(match[5]||0) - tzMin;
  13752. var s = int(match[6]||0);
  13753. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  13754. timeSetter.call(date, h, m, s, ms);
  13755. return date;
  13756. }
  13757. return string;
  13758. }
  13759. return function(date, format) {
  13760. var text = '',
  13761. parts = [],
  13762. fn, match;
  13763. format = format || 'mediumDate';
  13764. format = $locale.DATETIME_FORMATS[format] || format;
  13765. if (isString(date)) {
  13766. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  13767. }
  13768. if (isNumber(date)) {
  13769. date = new Date(date);
  13770. }
  13771. if (!isDate(date)) {
  13772. return date;
  13773. }
  13774. while(format) {
  13775. match = DATE_FORMATS_SPLIT.exec(format);
  13776. if (match) {
  13777. parts = concat(parts, match, 1);
  13778. format = parts.pop();
  13779. } else {
  13780. parts.push(format);
  13781. format = null;
  13782. }
  13783. }
  13784. forEach(parts, function(value){
  13785. fn = DATE_FORMATS[value];
  13786. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  13787. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  13788. });
  13789. return text;
  13790. };
  13791. }
  13792. /**
  13793. * @ngdoc filter
  13794. * @name json
  13795. * @kind function
  13796. *
  13797. * @description
  13798. * Allows you to convert a JavaScript object into JSON string.
  13799. *
  13800. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  13801. * the binding is automatically converted to JSON.
  13802. *
  13803. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  13804. * @returns {string} JSON string.
  13805. *
  13806. *
  13807. * @example
  13808. <example>
  13809. <file name="index.html">
  13810. <pre>{{ {'name':'value'} | json }}</pre>
  13811. </file>
  13812. <file name="protractor.js" type="protractor">
  13813. it('should jsonify filtered objects', function() {
  13814. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  13815. });
  13816. </file>
  13817. </example>
  13818. *
  13819. */
  13820. function jsonFilter() {
  13821. return function(object) {
  13822. return toJson(object, true);
  13823. };
  13824. }
  13825. /**
  13826. * @ngdoc filter
  13827. * @name lowercase
  13828. * @kind function
  13829. * @description
  13830. * Converts string to lowercase.
  13831. * @see angular.lowercase
  13832. */
  13833. var lowercaseFilter = valueFn(lowercase);
  13834. /**
  13835. * @ngdoc filter
  13836. * @name uppercase
  13837. * @kind function
  13838. * @description
  13839. * Converts string to uppercase.
  13840. * @see angular.uppercase
  13841. */
  13842. var uppercaseFilter = valueFn(uppercase);
  13843. /**
  13844. * @ngdoc filter
  13845. * @name limitTo
  13846. * @kind function
  13847. *
  13848. * @description
  13849. * Creates a new array or string containing only a specified number of elements. The elements
  13850. * are taken from either the beginning or the end of the source array or string, as specified by
  13851. * the value and sign (positive or negative) of `limit`.
  13852. *
  13853. * @param {Array|string} input Source array or string to be limited.
  13854. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  13855. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  13856. * If the number is negative, `limit` number of items from the end of the source array/string
  13857. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  13858. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  13859. * had less than `limit` elements.
  13860. *
  13861. * @example
  13862. <example module="limitToExample">
  13863. <file name="index.html">
  13864. <script>
  13865. angular.module('limitToExample', [])
  13866. .controller('ExampleController', ['$scope', function($scope) {
  13867. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  13868. $scope.letters = "abcdefghi";
  13869. $scope.numLimit = 3;
  13870. $scope.letterLimit = 3;
  13871. }]);
  13872. </script>
  13873. <div ng-controller="ExampleController">
  13874. Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
  13875. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  13876. Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
  13877. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  13878. </div>
  13879. </file>
  13880. <file name="protractor.js" type="protractor">
  13881. var numLimitInput = element(by.model('numLimit'));
  13882. var letterLimitInput = element(by.model('letterLimit'));
  13883. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  13884. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  13885. it('should limit the number array to first three items', function() {
  13886. expect(numLimitInput.getAttribute('value')).toBe('3');
  13887. expect(letterLimitInput.getAttribute('value')).toBe('3');
  13888. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  13889. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  13890. });
  13891. it('should update the output when -3 is entered', function() {
  13892. numLimitInput.clear();
  13893. numLimitInput.sendKeys('-3');
  13894. letterLimitInput.clear();
  13895. letterLimitInput.sendKeys('-3');
  13896. expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  13897. expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  13898. });
  13899. it('should not exceed the maximum size of input array', function() {
  13900. numLimitInput.clear();
  13901. numLimitInput.sendKeys('100');
  13902. letterLimitInput.clear();
  13903. letterLimitInput.sendKeys('100');
  13904. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  13905. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  13906. });
  13907. </file>
  13908. </example>
  13909. */
  13910. function limitToFilter(){
  13911. return function(input, limit) {
  13912. if (!isArray(input) && !isString(input)) return input;
  13913. if (Math.abs(Number(limit)) === Infinity) {
  13914. limit = Number(limit);
  13915. } else {
  13916. limit = int(limit);
  13917. }
  13918. if (isString(input)) {
  13919. //NaN check on limit
  13920. if (limit) {
  13921. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  13922. } else {
  13923. return "";
  13924. }
  13925. }
  13926. var out = [],
  13927. i, n;
  13928. // if abs(limit) exceeds maximum length, trim it
  13929. if (limit > input.length)
  13930. limit = input.length;
  13931. else if (limit < -input.length)
  13932. limit = -input.length;
  13933. if (limit > 0) {
  13934. i = 0;
  13935. n = limit;
  13936. } else {
  13937. i = input.length + limit;
  13938. n = input.length;
  13939. }
  13940. for (; i<n; i++) {
  13941. out.push(input[i]);
  13942. }
  13943. return out;
  13944. };
  13945. }
  13946. /**
  13947. * @ngdoc filter
  13948. * @name orderBy
  13949. * @kind function
  13950. *
  13951. * @description
  13952. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  13953. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  13954. * correctly, make sure they are actually being saved as numbers and not strings.
  13955. *
  13956. * @param {Array} array The array to sort.
  13957. * @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
  13958. * used by the comparator to determine the order of elements.
  13959. *
  13960. * Can be one of:
  13961. *
  13962. * - `function`: Getter function. The result of this function will be sorted using the
  13963. * `<`, `=`, `>` operator.
  13964. * - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
  13965. * to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
  13966. * ascending or descending sort order (for example, +name or -name).
  13967. * - `Array`: An array of function or string predicates. The first predicate in the array
  13968. * is used for sorting, but when two items are equivalent, the next predicate is used.
  13969. *
  13970. * @param {boolean=} reverse Reverse the order of the array.
  13971. * @returns {Array} Sorted copy of the source array.
  13972. *
  13973. * @example
  13974. <example module="orderByExample">
  13975. <file name="index.html">
  13976. <script>
  13977. angular.module('orderByExample', [])
  13978. .controller('ExampleController', ['$scope', function($scope) {
  13979. $scope.friends =
  13980. [{name:'John', phone:'555-1212', age:10},
  13981. {name:'Mary', phone:'555-9876', age:19},
  13982. {name:'Mike', phone:'555-4321', age:21},
  13983. {name:'Adam', phone:'555-5678', age:35},
  13984. {name:'Julie', phone:'555-8765', age:29}];
  13985. $scope.predicate = '-age';
  13986. }]);
  13987. </script>
  13988. <div ng-controller="ExampleController">
  13989. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  13990. <hr/>
  13991. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  13992. <table class="friend">
  13993. <tr>
  13994. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  13995. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  13996. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  13997. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  13998. </tr>
  13999. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  14000. <td>{{friend.name}}</td>
  14001. <td>{{friend.phone}}</td>
  14002. <td>{{friend.age}}</td>
  14003. </tr>
  14004. </table>
  14005. </div>
  14006. </file>
  14007. </example>
  14008. *
  14009. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  14010. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  14011. * desired parameters.
  14012. *
  14013. * Example:
  14014. *
  14015. * @example
  14016. <example module="orderByExample">
  14017. <file name="index.html">
  14018. <div ng-controller="ExampleController">
  14019. <table class="friend">
  14020. <tr>
  14021. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  14022. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  14023. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  14024. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  14025. </tr>
  14026. <tr ng-repeat="friend in friends">
  14027. <td>{{friend.name}}</td>
  14028. <td>{{friend.phone}}</td>
  14029. <td>{{friend.age}}</td>
  14030. </tr>
  14031. </table>
  14032. </div>
  14033. </file>
  14034. <file name="script.js">
  14035. angular.module('orderByExample', [])
  14036. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  14037. var orderBy = $filter('orderBy');
  14038. $scope.friends = [
  14039. { name: 'John', phone: '555-1212', age: 10 },
  14040. { name: 'Mary', phone: '555-9876', age: 19 },
  14041. { name: 'Mike', phone: '555-4321', age: 21 },
  14042. { name: 'Adam', phone: '555-5678', age: 35 },
  14043. { name: 'Julie', phone: '555-8765', age: 29 }
  14044. ];
  14045. $scope.order = function(predicate, reverse) {
  14046. $scope.friends = orderBy($scope.friends, predicate, reverse);
  14047. };
  14048. $scope.order('-age',false);
  14049. }]);
  14050. </file>
  14051. </example>
  14052. */
  14053. orderByFilter.$inject = ['$parse'];
  14054. function orderByFilter($parse){
  14055. return function(array, sortPredicate, reverseOrder) {
  14056. if (!isArray(array)) return array;
  14057. if (!sortPredicate) return array;
  14058. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  14059. sortPredicate = map(sortPredicate, function(predicate){
  14060. var descending = false, get = predicate || identity;
  14061. if (isString(predicate)) {
  14062. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  14063. descending = predicate.charAt(0) == '-';
  14064. predicate = predicate.substring(1);
  14065. }
  14066. get = $parse(predicate);
  14067. if (get.constant) {
  14068. var key = get();
  14069. return reverseComparator(function(a,b) {
  14070. return compare(a[key], b[key]);
  14071. }, descending);
  14072. }
  14073. }
  14074. return reverseComparator(function(a,b){
  14075. return compare(get(a),get(b));
  14076. }, descending);
  14077. });
  14078. var arrayCopy = [];
  14079. for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  14080. return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
  14081. function comparator(o1, o2){
  14082. for ( var i = 0; i < sortPredicate.length; i++) {
  14083. var comp = sortPredicate[i](o1, o2);
  14084. if (comp !== 0) return comp;
  14085. }
  14086. return 0;
  14087. }
  14088. function reverseComparator(comp, descending) {
  14089. return toBoolean(descending)
  14090. ? function(a,b){return comp(b,a);}
  14091. : comp;
  14092. }
  14093. function compare(v1, v2){
  14094. var t1 = typeof v1;
  14095. var t2 = typeof v2;
  14096. if (t1 == t2) {
  14097. if (isDate(v1) && isDate(v2)) {
  14098. v1 = v1.valueOf();
  14099. v2 = v2.valueOf();
  14100. }
  14101. if (t1 == "string") {
  14102. v1 = v1.toLowerCase();
  14103. v2 = v2.toLowerCase();
  14104. }
  14105. if (v1 === v2) return 0;
  14106. return v1 < v2 ? -1 : 1;
  14107. } else {
  14108. return t1 < t2 ? -1 : 1;
  14109. }
  14110. }
  14111. };
  14112. }
  14113. function ngDirective(directive) {
  14114. if (isFunction(directive)) {
  14115. directive = {
  14116. link: directive
  14117. };
  14118. }
  14119. directive.restrict = directive.restrict || 'AC';
  14120. return valueFn(directive);
  14121. }
  14122. /**
  14123. * @ngdoc directive
  14124. * @name a
  14125. * @restrict E
  14126. *
  14127. * @description
  14128. * Modifies the default behavior of the html A tag so that the default action is prevented when
  14129. * the href attribute is empty.
  14130. *
  14131. * This change permits the easy creation of action links with the `ngClick` directive
  14132. * without changing the location or causing page reloads, e.g.:
  14133. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  14134. */
  14135. var htmlAnchorDirective = valueFn({
  14136. restrict: 'E',
  14137. compile: function(element, attr) {
  14138. if (msie <= 8) {
  14139. // turn <a href ng-click="..">link</a> into a stylable link in IE
  14140. // but only if it doesn't have name attribute, in which case it's an anchor
  14141. if (!attr.href && !attr.name) {
  14142. attr.$set('href', '');
  14143. }
  14144. // add a comment node to anchors to workaround IE bug that causes element content to be reset
  14145. // to new attribute content if attribute is updated with value containing @ and element also
  14146. // contains value with @
  14147. // see issue #1949
  14148. element.append(document.createComment('IE fix'));
  14149. }
  14150. if (!attr.href && !attr.xlinkHref && !attr.name) {
  14151. return function(scope, element) {
  14152. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  14153. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  14154. 'xlink:href' : 'href';
  14155. element.on('click', function(event){
  14156. // if we have no href url, then don't navigate anywhere.
  14157. if (!element.attr(href)) {
  14158. event.preventDefault();
  14159. }
  14160. });
  14161. };
  14162. }
  14163. }
  14164. });
  14165. /**
  14166. * @ngdoc directive
  14167. * @name ngHref
  14168. * @restrict A
  14169. * @priority 99
  14170. *
  14171. * @description
  14172. * Using Angular markup like `{{hash}}` in an href attribute will
  14173. * make the link go to the wrong URL if the user clicks it before
  14174. * Angular has a chance to replace the `{{hash}}` markup with its
  14175. * value. Until Angular replaces the markup the link will be broken
  14176. * and will most likely return a 404 error.
  14177. *
  14178. * The `ngHref` directive solves this problem.
  14179. *
  14180. * The wrong way to write it:
  14181. * ```html
  14182. * <a href="http://www.gravatar.com/avatar/{{hash}}"/>
  14183. * ```
  14184. *
  14185. * The correct way to write it:
  14186. * ```html
  14187. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
  14188. * ```
  14189. *
  14190. * @element A
  14191. * @param {template} ngHref any string which can contain `{{}}` markup.
  14192. *
  14193. * @example
  14194. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  14195. * in links and their different behaviors:
  14196. <example>
  14197. <file name="index.html">
  14198. <input ng-model="value" /><br />
  14199. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  14200. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  14201. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  14202. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  14203. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  14204. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  14205. </file>
  14206. <file name="protractor.js" type="protractor">
  14207. it('should execute ng-click but not reload when href without value', function() {
  14208. element(by.id('link-1')).click();
  14209. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  14210. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  14211. });
  14212. it('should execute ng-click but not reload when href empty string', function() {
  14213. element(by.id('link-2')).click();
  14214. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  14215. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  14216. });
  14217. it('should execute ng-click and change url when ng-href specified', function() {
  14218. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  14219. element(by.id('link-3')).click();
  14220. // At this point, we navigate away from an Angular page, so we need
  14221. // to use browser.driver to get the base webdriver.
  14222. browser.wait(function() {
  14223. return browser.driver.getCurrentUrl().then(function(url) {
  14224. return url.match(/\/123$/);
  14225. });
  14226. }, 5000, 'page should navigate to /123');
  14227. });
  14228. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  14229. element(by.id('link-4')).click();
  14230. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  14231. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  14232. });
  14233. it('should execute ng-click but not reload when no href but name specified', function() {
  14234. element(by.id('link-5')).click();
  14235. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  14236. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  14237. });
  14238. it('should only change url when only ng-href', function() {
  14239. element(by.model('value')).clear();
  14240. element(by.model('value')).sendKeys('6');
  14241. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  14242. element(by.id('link-6')).click();
  14243. // At this point, we navigate away from an Angular page, so we need
  14244. // to use browser.driver to get the base webdriver.
  14245. browser.wait(function() {
  14246. return browser.driver.getCurrentUrl().then(function(url) {
  14247. return url.match(/\/6$/);
  14248. });
  14249. }, 5000, 'page should navigate to /6');
  14250. });
  14251. </file>
  14252. </example>
  14253. */
  14254. /**
  14255. * @ngdoc directive
  14256. * @name ngSrc
  14257. * @restrict A
  14258. * @priority 99
  14259. *
  14260. * @description
  14261. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  14262. * work right: The browser will fetch from the URL with the literal
  14263. * text `{{hash}}` until Angular replaces the expression inside
  14264. * `{{hash}}`. The `ngSrc` directive solves this problem.
  14265. *
  14266. * The buggy way to write it:
  14267. * ```html
  14268. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  14269. * ```
  14270. *
  14271. * The correct way to write it:
  14272. * ```html
  14273. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  14274. * ```
  14275. *
  14276. * @element IMG
  14277. * @param {template} ngSrc any string which can contain `{{}}` markup.
  14278. */
  14279. /**
  14280. * @ngdoc directive
  14281. * @name ngSrcset
  14282. * @restrict A
  14283. * @priority 99
  14284. *
  14285. * @description
  14286. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  14287. * work right: The browser will fetch from the URL with the literal
  14288. * text `{{hash}}` until Angular replaces the expression inside
  14289. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  14290. *
  14291. * The buggy way to write it:
  14292. * ```html
  14293. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14294. * ```
  14295. *
  14296. * The correct way to write it:
  14297. * ```html
  14298. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  14299. * ```
  14300. *
  14301. * @element IMG
  14302. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  14303. */
  14304. /**
  14305. * @ngdoc directive
  14306. * @name ngDisabled
  14307. * @restrict A
  14308. * @priority 100
  14309. *
  14310. * @description
  14311. *
  14312. * The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  14313. * ```html
  14314. * <div ng-init="scope = { isDisabled: false }">
  14315. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  14316. * </div>
  14317. * ```
  14318. *
  14319. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14320. * such as disabled. (Their presence means true and their absence means false.)
  14321. * If we put an Angular interpolation expression into such an attribute then the
  14322. * binding information would be lost when the browser removes the attribute.
  14323. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  14324. * This complementary directive is not removed by the browser and so provides
  14325. * a permanent reliable place to store the binding information.
  14326. *
  14327. * @example
  14328. <example>
  14329. <file name="index.html">
  14330. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  14331. <button ng-model="button" ng-disabled="checked">Button</button>
  14332. </file>
  14333. <file name="protractor.js" type="protractor">
  14334. it('should toggle button', function() {
  14335. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  14336. element(by.model('checked')).click();
  14337. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  14338. });
  14339. </file>
  14340. </example>
  14341. *
  14342. * @element INPUT
  14343. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  14344. * then special attribute "disabled" will be set on the element
  14345. */
  14346. /**
  14347. * @ngdoc directive
  14348. * @name ngChecked
  14349. * @restrict A
  14350. * @priority 100
  14351. *
  14352. * @description
  14353. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14354. * such as checked. (Their presence means true and their absence means false.)
  14355. * If we put an Angular interpolation expression into such an attribute then the
  14356. * binding information would be lost when the browser removes the attribute.
  14357. * The `ngChecked` directive solves this problem for the `checked` attribute.
  14358. * This complementary directive is not removed by the browser and so provides
  14359. * a permanent reliable place to store the binding information.
  14360. * @example
  14361. <example>
  14362. <file name="index.html">
  14363. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  14364. <input id="checkSlave" type="checkbox" ng-checked="master">
  14365. </file>
  14366. <file name="protractor.js" type="protractor">
  14367. it('should check both checkBoxes', function() {
  14368. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  14369. element(by.model('master')).click();
  14370. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  14371. });
  14372. </file>
  14373. </example>
  14374. *
  14375. * @element INPUT
  14376. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  14377. * then special attribute "checked" will be set on the element
  14378. */
  14379. /**
  14380. * @ngdoc directive
  14381. * @name ngReadonly
  14382. * @restrict A
  14383. * @priority 100
  14384. *
  14385. * @description
  14386. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14387. * such as readonly. (Their presence means true and their absence means false.)
  14388. * If we put an Angular interpolation expression into such an attribute then the
  14389. * binding information would be lost when the browser removes the attribute.
  14390. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  14391. * This complementary directive is not removed by the browser and so provides
  14392. * a permanent reliable place to store the binding information.
  14393. * @example
  14394. <example>
  14395. <file name="index.html">
  14396. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  14397. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  14398. </file>
  14399. <file name="protractor.js" type="protractor">
  14400. it('should toggle readonly attr', function() {
  14401. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  14402. element(by.model('checked')).click();
  14403. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  14404. });
  14405. </file>
  14406. </example>
  14407. *
  14408. * @element INPUT
  14409. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  14410. * then special attribute "readonly" will be set on the element
  14411. */
  14412. /**
  14413. * @ngdoc directive
  14414. * @name ngSelected
  14415. * @restrict A
  14416. * @priority 100
  14417. *
  14418. * @description
  14419. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14420. * such as selected. (Their presence means true and their absence means false.)
  14421. * If we put an Angular interpolation expression into such an attribute then the
  14422. * binding information would be lost when the browser removes the attribute.
  14423. * The `ngSelected` directive solves this problem for the `selected` attribute.
  14424. * This complementary directive is not removed by the browser and so provides
  14425. * a permanent reliable place to store the binding information.
  14426. *
  14427. * @example
  14428. <example>
  14429. <file name="index.html">
  14430. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  14431. <select>
  14432. <option>Hello!</option>
  14433. <option id="greet" ng-selected="selected">Greetings!</option>
  14434. </select>
  14435. </file>
  14436. <file name="protractor.js" type="protractor">
  14437. it('should select Greetings!', function() {
  14438. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  14439. element(by.model('selected')).click();
  14440. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  14441. });
  14442. </file>
  14443. </example>
  14444. *
  14445. * @element OPTION
  14446. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  14447. * then special attribute "selected" will be set on the element
  14448. */
  14449. /**
  14450. * @ngdoc directive
  14451. * @name ngOpen
  14452. * @restrict A
  14453. * @priority 100
  14454. *
  14455. * @description
  14456. * The HTML specification does not require browsers to preserve the values of boolean attributes
  14457. * such as open. (Their presence means true and their absence means false.)
  14458. * If we put an Angular interpolation expression into such an attribute then the
  14459. * binding information would be lost when the browser removes the attribute.
  14460. * The `ngOpen` directive solves this problem for the `open` attribute.
  14461. * This complementary directive is not removed by the browser and so provides
  14462. * a permanent reliable place to store the binding information.
  14463. * @example
  14464. <example>
  14465. <file name="index.html">
  14466. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  14467. <details id="details" ng-open="open">
  14468. <summary>Show/Hide me</summary>
  14469. </details>
  14470. </file>
  14471. <file name="protractor.js" type="protractor">
  14472. it('should toggle open', function() {
  14473. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  14474. element(by.model('open')).click();
  14475. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  14476. });
  14477. </file>
  14478. </example>
  14479. *
  14480. * @element DETAILS
  14481. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  14482. * then special attribute "open" will be set on the element
  14483. */
  14484. var ngAttributeAliasDirectives = {};
  14485. // boolean attrs are evaluated
  14486. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  14487. // binding to multiple is not supported
  14488. if (propName == "multiple") return;
  14489. var normalized = directiveNormalize('ng-' + attrName);
  14490. ngAttributeAliasDirectives[normalized] = function() {
  14491. return {
  14492. priority: 100,
  14493. link: function(scope, element, attr) {
  14494. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  14495. attr.$set(attrName, !!value);
  14496. });
  14497. }
  14498. };
  14499. };
  14500. });
  14501. // ng-src, ng-srcset, ng-href are interpolated
  14502. forEach(['src', 'srcset', 'href'], function(attrName) {
  14503. var normalized = directiveNormalize('ng-' + attrName);
  14504. ngAttributeAliasDirectives[normalized] = function() {
  14505. return {
  14506. priority: 99, // it needs to run after the attributes are interpolated
  14507. link: function(scope, element, attr) {
  14508. var propName = attrName,
  14509. name = attrName;
  14510. if (attrName === 'href' &&
  14511. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  14512. name = 'xlinkHref';
  14513. attr.$attr[name] = 'xlink:href';
  14514. propName = null;
  14515. }
  14516. attr.$observe(normalized, function(value) {
  14517. if (!value)
  14518. return;
  14519. attr.$set(name, value);
  14520. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  14521. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  14522. // to set the property as well to achieve the desired effect.
  14523. // we use attr[attrName] value since $set can sanitize the url.
  14524. if (msie && propName) element.prop(propName, attr[name]);
  14525. });
  14526. }
  14527. };
  14528. };
  14529. });
  14530. /* global -nullFormCtrl */
  14531. var nullFormCtrl = {
  14532. $addControl: noop,
  14533. $removeControl: noop,
  14534. $setValidity: noop,
  14535. $setDirty: noop,
  14536. $setPristine: noop
  14537. };
  14538. /**
  14539. * @ngdoc type
  14540. * @name form.FormController
  14541. *
  14542. * @property {boolean} $pristine True if user has not interacted with the form yet.
  14543. * @property {boolean} $dirty True if user has already interacted with the form.
  14544. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  14545. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  14546. *
  14547. * @property {Object} $error Is an object hash, containing references to all invalid controls or
  14548. * forms, where:
  14549. *
  14550. * - keys are validation tokens (error names),
  14551. * - values are arrays of controls or forms that are invalid for given error name.
  14552. *
  14553. *
  14554. * Built-in validation tokens:
  14555. *
  14556. * - `email`
  14557. * - `max`
  14558. * - `maxlength`
  14559. * - `min`
  14560. * - `minlength`
  14561. * - `number`
  14562. * - `pattern`
  14563. * - `required`
  14564. * - `url`
  14565. *
  14566. * @description
  14567. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  14568. * such as being valid/invalid or dirty/pristine.
  14569. *
  14570. * Each {@link ng.directive:form form} directive creates an instance
  14571. * of `FormController`.
  14572. *
  14573. */
  14574. //asks for $scope to fool the BC controller module
  14575. FormController.$inject = ['$element', '$attrs', '$scope', '$animate'];
  14576. function FormController(element, attrs, $scope, $animate) {
  14577. var form = this,
  14578. parentForm = element.parent().controller('form') || nullFormCtrl,
  14579. invalidCount = 0, // used to easily determine if we are valid
  14580. errors = form.$error = {},
  14581. controls = [];
  14582. // init state
  14583. form.$name = attrs.name || attrs.ngForm;
  14584. form.$dirty = false;
  14585. form.$pristine = true;
  14586. form.$valid = true;
  14587. form.$invalid = false;
  14588. parentForm.$addControl(form);
  14589. // Setup initial state of the control
  14590. element.addClass(PRISTINE_CLASS);
  14591. toggleValidCss(true);
  14592. // convenience method for easy toggling of classes
  14593. function toggleValidCss(isValid, validationErrorKey) {
  14594. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  14595. $animate.removeClass(element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  14596. $animate.addClass(element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  14597. }
  14598. /**
  14599. * @ngdoc method
  14600. * @name form.FormController#$addControl
  14601. *
  14602. * @description
  14603. * Register a control with the form.
  14604. *
  14605. * Input elements using ngModelController do this automatically when they are linked.
  14606. */
  14607. form.$addControl = function(control) {
  14608. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  14609. // and not added to the scope. Now we throw an error.
  14610. assertNotHasOwnProperty(control.$name, 'input');
  14611. controls.push(control);
  14612. if (control.$name) {
  14613. form[control.$name] = control;
  14614. }
  14615. };
  14616. /**
  14617. * @ngdoc method
  14618. * @name form.FormController#$removeControl
  14619. *
  14620. * @description
  14621. * Deregister a control from the form.
  14622. *
  14623. * Input elements using ngModelController do this automatically when they are destroyed.
  14624. */
  14625. form.$removeControl = function(control) {
  14626. if (control.$name && form[control.$name] === control) {
  14627. delete form[control.$name];
  14628. }
  14629. forEach(errors, function(queue, validationToken) {
  14630. form.$setValidity(validationToken, true, control);
  14631. });
  14632. arrayRemove(controls, control);
  14633. };
  14634. /**
  14635. * @ngdoc method
  14636. * @name form.FormController#$setValidity
  14637. *
  14638. * @description
  14639. * Sets the validity of a form control.
  14640. *
  14641. * This method will also propagate to parent forms.
  14642. */
  14643. form.$setValidity = function(validationToken, isValid, control) {
  14644. var queue = errors[validationToken];
  14645. if (isValid) {
  14646. if (queue) {
  14647. arrayRemove(queue, control);
  14648. if (!queue.length) {
  14649. invalidCount--;
  14650. if (!invalidCount) {
  14651. toggleValidCss(isValid);
  14652. form.$valid = true;
  14653. form.$invalid = false;
  14654. }
  14655. errors[validationToken] = false;
  14656. toggleValidCss(true, validationToken);
  14657. parentForm.$setValidity(validationToken, true, form);
  14658. }
  14659. }
  14660. } else {
  14661. if (!invalidCount) {
  14662. toggleValidCss(isValid);
  14663. }
  14664. if (queue) {
  14665. if (includes(queue, control)) return;
  14666. } else {
  14667. errors[validationToken] = queue = [];
  14668. invalidCount++;
  14669. toggleValidCss(false, validationToken);
  14670. parentForm.$setValidity(validationToken, false, form);
  14671. }
  14672. queue.push(control);
  14673. form.$valid = false;
  14674. form.$invalid = true;
  14675. }
  14676. };
  14677. /**
  14678. * @ngdoc method
  14679. * @name form.FormController#$setDirty
  14680. *
  14681. * @description
  14682. * Sets the form to a dirty state.
  14683. *
  14684. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  14685. * state (ng-dirty class). This method will also propagate to parent forms.
  14686. */
  14687. form.$setDirty = function() {
  14688. $animate.removeClass(element, PRISTINE_CLASS);
  14689. $animate.addClass(element, DIRTY_CLASS);
  14690. form.$dirty = true;
  14691. form.$pristine = false;
  14692. parentForm.$setDirty();
  14693. };
  14694. /**
  14695. * @ngdoc method
  14696. * @name form.FormController#$setPristine
  14697. *
  14698. * @description
  14699. * Sets the form to its pristine state.
  14700. *
  14701. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  14702. * state (ng-pristine class). This method will also propagate to all the controls contained
  14703. * in this form.
  14704. *
  14705. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  14706. * saving or resetting it.
  14707. */
  14708. form.$setPristine = function () {
  14709. $animate.removeClass(element, DIRTY_CLASS);
  14710. $animate.addClass(element, PRISTINE_CLASS);
  14711. form.$dirty = false;
  14712. form.$pristine = true;
  14713. forEach(controls, function(control) {
  14714. control.$setPristine();
  14715. });
  14716. };
  14717. }
  14718. /**
  14719. * @ngdoc directive
  14720. * @name ngForm
  14721. * @restrict EAC
  14722. *
  14723. * @description
  14724. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  14725. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  14726. * sub-group of controls needs to be determined.
  14727. *
  14728. * Note: the purpose of `ngForm` is to group controls,
  14729. * but not to be a replacement for the `<form>` tag with all of its capabilities
  14730. * (e.g. posting to the server, ...).
  14731. *
  14732. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  14733. * related scope, under this name.
  14734. *
  14735. */
  14736. /**
  14737. * @ngdoc directive
  14738. * @name form
  14739. * @restrict E
  14740. *
  14741. * @description
  14742. * Directive that instantiates
  14743. * {@link form.FormController FormController}.
  14744. *
  14745. * If the `name` attribute is specified, the form controller is published onto the current scope under
  14746. * this name.
  14747. *
  14748. * # Alias: {@link ng.directive:ngForm `ngForm`}
  14749. *
  14750. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  14751. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  14752. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  14753. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  14754. * using Angular validation directives in forms that are dynamically generated using the
  14755. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  14756. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  14757. * `ngForm` directive and nest these in an outer `form` element.
  14758. *
  14759. *
  14760. * # CSS classes
  14761. * - `ng-valid` is set if the form is valid.
  14762. * - `ng-invalid` is set if the form is invalid.
  14763. * - `ng-pristine` is set if the form is pristine.
  14764. * - `ng-dirty` is set if the form is dirty.
  14765. *
  14766. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  14767. *
  14768. *
  14769. * # Submitting a form and preventing the default action
  14770. *
  14771. * Since the role of forms in client-side Angular applications is different than in classical
  14772. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  14773. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  14774. * to handle the form submission in an application-specific way.
  14775. *
  14776. * For this reason, Angular prevents the default action (form submission to the server) unless the
  14777. * `<form>` element has an `action` attribute specified.
  14778. *
  14779. * You can use one of the following two ways to specify what javascript method should be called when
  14780. * a form is submitted:
  14781. *
  14782. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  14783. * - {@link ng.directive:ngClick ngClick} directive on the first
  14784. * button or input field of type submit (input[type=submit])
  14785. *
  14786. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  14787. * or {@link ng.directive:ngClick ngClick} directives.
  14788. * This is because of the following form submission rules in the HTML specification:
  14789. *
  14790. * - If a form has only one input field then hitting enter in this field triggers form submit
  14791. * (`ngSubmit`)
  14792. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  14793. * doesn't trigger submit
  14794. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  14795. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  14796. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  14797. *
  14798. * @param {string=} name Name of the form. If specified, the form controller will be published into
  14799. * related scope, under this name.
  14800. *
  14801. * ## Animation Hooks
  14802. *
  14803. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  14804. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  14805. * other validations that are performed within the form. Animations in ngForm are similar to how
  14806. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  14807. * as JS animations.
  14808. *
  14809. * The following example shows a simple way to utilize CSS transitions to style a form element
  14810. * that has been rendered as invalid after it has been validated:
  14811. *
  14812. * <pre>
  14813. * //be sure to include ngAnimate as a module to hook into more
  14814. * //advanced animations
  14815. * .my-form {
  14816. * transition:0.5s linear all;
  14817. * background: white;
  14818. * }
  14819. * .my-form.ng-invalid {
  14820. * background: red;
  14821. * color:white;
  14822. * }
  14823. * </pre>
  14824. *
  14825. * @example
  14826. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  14827. <file name="index.html">
  14828. <script>
  14829. angular.module('formExample', [])
  14830. .controller('FormController', ['$scope', function($scope) {
  14831. $scope.userType = 'guest';
  14832. }]);
  14833. </script>
  14834. <style>
  14835. .my-form {
  14836. -webkit-transition:all linear 0.5s;
  14837. transition:all linear 0.5s;
  14838. background: transparent;
  14839. }
  14840. .my-form.ng-invalid {
  14841. background: red;
  14842. }
  14843. </style>
  14844. <form name="myForm" ng-controller="FormController" class="my-form">
  14845. userType: <input name="input" ng-model="userType" required>
  14846. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  14847. <tt>userType = {{userType}}</tt><br>
  14848. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  14849. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  14850. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  14851. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  14852. </form>
  14853. </file>
  14854. <file name="protractor.js" type="protractor">
  14855. it('should initialize to model', function() {
  14856. var userType = element(by.binding('userType'));
  14857. var valid = element(by.binding('myForm.input.$valid'));
  14858. expect(userType.getText()).toContain('guest');
  14859. expect(valid.getText()).toContain('true');
  14860. });
  14861. it('should be invalid if empty', function() {
  14862. var userType = element(by.binding('userType'));
  14863. var valid = element(by.binding('myForm.input.$valid'));
  14864. var userInput = element(by.model('userType'));
  14865. userInput.clear();
  14866. userInput.sendKeys('');
  14867. expect(userType.getText()).toEqual('userType =');
  14868. expect(valid.getText()).toContain('false');
  14869. });
  14870. </file>
  14871. </example>
  14872. *
  14873. */
  14874. var formDirectiveFactory = function(isNgForm) {
  14875. return ['$timeout', function($timeout) {
  14876. var formDirective = {
  14877. name: 'form',
  14878. restrict: isNgForm ? 'EAC' : 'E',
  14879. controller: FormController,
  14880. compile: function() {
  14881. return {
  14882. pre: function(scope, formElement, attr, controller) {
  14883. if (!attr.action) {
  14884. // we can't use jq events because if a form is destroyed during submission the default
  14885. // action is not prevented. see #1238
  14886. //
  14887. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  14888. // page reload if the form was destroyed by submission of the form via a click handler
  14889. // on a button in the form. Looks like an IE9 specific bug.
  14890. var preventDefaultListener = function(event) {
  14891. event.preventDefault
  14892. ? event.preventDefault()
  14893. : event.returnValue = false; // IE
  14894. };
  14895. addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  14896. // unregister the preventDefault listener so that we don't not leak memory but in a
  14897. // way that will achieve the prevention of the default action.
  14898. formElement.on('$destroy', function() {
  14899. $timeout(function() {
  14900. removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
  14901. }, 0, false);
  14902. });
  14903. }
  14904. var parentFormCtrl = formElement.parent().controller('form'),
  14905. alias = attr.name || attr.ngForm;
  14906. if (alias) {
  14907. setter(scope, alias, controller, alias);
  14908. }
  14909. if (parentFormCtrl) {
  14910. formElement.on('$destroy', function() {
  14911. parentFormCtrl.$removeControl(controller);
  14912. if (alias) {
  14913. setter(scope, alias, undefined, alias);
  14914. }
  14915. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  14916. });
  14917. }
  14918. }
  14919. };
  14920. }
  14921. };
  14922. return formDirective;
  14923. }];
  14924. };
  14925. var formDirective = formDirectiveFactory();
  14926. var ngFormDirective = formDirectiveFactory(true);
  14927. /* global VALID_CLASS: true,
  14928. INVALID_CLASS: true,
  14929. PRISTINE_CLASS: true,
  14930. DIRTY_CLASS: true
  14931. */
  14932. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  14933. var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
  14934. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  14935. var inputType = {
  14936. /**
  14937. * @ngdoc input
  14938. * @name input[text]
  14939. *
  14940. * @description
  14941. * Standard HTML text input with angular data binding.
  14942. *
  14943. * @param {string} ngModel Assignable angular expression to data-bind to.
  14944. * @param {string=} name Property name of the form under which the control is published.
  14945. * @param {string=} required Adds `required` validation error key if the value is not entered.
  14946. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  14947. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  14948. * `required` when you want to data-bind to the `required` attribute.
  14949. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  14950. * minlength.
  14951. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  14952. * maxlength.
  14953. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  14954. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  14955. * patterns defined as scope expressions.
  14956. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  14957. * interaction with the input element.
  14958. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  14959. *
  14960. * @example
  14961. <example name="text-input-directive" module="textInputExample">
  14962. <file name="index.html">
  14963. <script>
  14964. angular.module('textInputExample', [])
  14965. .controller('ExampleController', ['$scope', function($scope) {
  14966. $scope.text = 'guest';
  14967. $scope.word = /^\s*\w*\s*$/;
  14968. }]);
  14969. </script>
  14970. <form name="myForm" ng-controller="ExampleController">
  14971. Single word: <input type="text" name="input" ng-model="text"
  14972. ng-pattern="word" required ng-trim="false">
  14973. <span class="error" ng-show="myForm.input.$error.required">
  14974. Required!</span>
  14975. <span class="error" ng-show="myForm.input.$error.pattern">
  14976. Single word only!</span>
  14977. <tt>text = {{text}}</tt><br/>
  14978. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  14979. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  14980. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  14981. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  14982. </form>
  14983. </file>
  14984. <file name="protractor.js" type="protractor">
  14985. var text = element(by.binding('text'));
  14986. var valid = element(by.binding('myForm.input.$valid'));
  14987. var input = element(by.model('text'));
  14988. it('should initialize to model', function() {
  14989. expect(text.getText()).toContain('guest');
  14990. expect(valid.getText()).toContain('true');
  14991. });
  14992. it('should be invalid if empty', function() {
  14993. input.clear();
  14994. input.sendKeys('');
  14995. expect(text.getText()).toEqual('text =');
  14996. expect(valid.getText()).toContain('false');
  14997. });
  14998. it('should be invalid if multi word', function() {
  14999. input.clear();
  15000. input.sendKeys('hello world');
  15001. expect(valid.getText()).toContain('false');
  15002. });
  15003. </file>
  15004. </example>
  15005. */
  15006. 'text': textInputType,
  15007. /**
  15008. * @ngdoc input
  15009. * @name input[number]
  15010. *
  15011. * @description
  15012. * Text input with number validation and transformation. Sets the `number` validation
  15013. * error if not a valid number.
  15014. *
  15015. * @param {string} ngModel Assignable angular expression to data-bind to.
  15016. * @param {string=} name Property name of the form under which the control is published.
  15017. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  15018. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  15019. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15020. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15021. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15022. * `required` when you want to data-bind to the `required` attribute.
  15023. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15024. * minlength.
  15025. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15026. * maxlength.
  15027. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15028. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15029. * patterns defined as scope expressions.
  15030. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15031. * interaction with the input element.
  15032. *
  15033. * @example
  15034. <example name="number-input-directive" module="numberExample">
  15035. <file name="index.html">
  15036. <script>
  15037. angular.module('numberExample', [])
  15038. .controller('ExampleController', ['$scope', function($scope) {
  15039. $scope.value = 12;
  15040. }]);
  15041. </script>
  15042. <form name="myForm" ng-controller="ExampleController">
  15043. Number: <input type="number" name="input" ng-model="value"
  15044. min="0" max="99" required>
  15045. <span class="error" ng-show="myForm.input.$error.required">
  15046. Required!</span>
  15047. <span class="error" ng-show="myForm.input.$error.number">
  15048. Not valid number!</span>
  15049. <tt>value = {{value}}</tt><br/>
  15050. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15051. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15052. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15053. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15054. </form>
  15055. </file>
  15056. <file name="protractor.js" type="protractor">
  15057. var value = element(by.binding('value'));
  15058. var valid = element(by.binding('myForm.input.$valid'));
  15059. var input = element(by.model('value'));
  15060. it('should initialize to model', function() {
  15061. expect(value.getText()).toContain('12');
  15062. expect(valid.getText()).toContain('true');
  15063. });
  15064. it('should be invalid if empty', function() {
  15065. input.clear();
  15066. input.sendKeys('');
  15067. expect(value.getText()).toEqual('value =');
  15068. expect(valid.getText()).toContain('false');
  15069. });
  15070. it('should be invalid if over max', function() {
  15071. input.clear();
  15072. input.sendKeys('123');
  15073. expect(value.getText()).toEqual('value =');
  15074. expect(valid.getText()).toContain('false');
  15075. });
  15076. </file>
  15077. </example>
  15078. */
  15079. 'number': numberInputType,
  15080. /**
  15081. * @ngdoc input
  15082. * @name input[url]
  15083. *
  15084. * @description
  15085. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  15086. * valid URL.
  15087. *
  15088. * @param {string} ngModel Assignable angular expression to data-bind to.
  15089. * @param {string=} name Property name of the form under which the control is published.
  15090. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15091. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15092. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15093. * `required` when you want to data-bind to the `required` attribute.
  15094. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15095. * minlength.
  15096. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15097. * maxlength.
  15098. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15099. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15100. * patterns defined as scope expressions.
  15101. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15102. * interaction with the input element.
  15103. *
  15104. * @example
  15105. <example name="url-input-directive" module="urlExample">
  15106. <file name="index.html">
  15107. <script>
  15108. angular.module('urlExample', [])
  15109. .controller('ExampleController', ['$scope', function($scope) {
  15110. $scope.text = 'http://google.com';
  15111. }]);
  15112. </script>
  15113. <form name="myForm" ng-controller="ExampleController">
  15114. URL: <input type="url" name="input" ng-model="text" required>
  15115. <span class="error" ng-show="myForm.input.$error.required">
  15116. Required!</span>
  15117. <span class="error" ng-show="myForm.input.$error.url">
  15118. Not valid url!</span>
  15119. <tt>text = {{text}}</tt><br/>
  15120. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15121. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15122. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15123. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15124. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  15125. </form>
  15126. </file>
  15127. <file name="protractor.js" type="protractor">
  15128. var text = element(by.binding('text'));
  15129. var valid = element(by.binding('myForm.input.$valid'));
  15130. var input = element(by.model('text'));
  15131. it('should initialize to model', function() {
  15132. expect(text.getText()).toContain('http://google.com');
  15133. expect(valid.getText()).toContain('true');
  15134. });
  15135. it('should be invalid if empty', function() {
  15136. input.clear();
  15137. input.sendKeys('');
  15138. expect(text.getText()).toEqual('text =');
  15139. expect(valid.getText()).toContain('false');
  15140. });
  15141. it('should be invalid if not url', function() {
  15142. input.clear();
  15143. input.sendKeys('box');
  15144. expect(valid.getText()).toContain('false');
  15145. });
  15146. </file>
  15147. </example>
  15148. */
  15149. 'url': urlInputType,
  15150. /**
  15151. * @ngdoc input
  15152. * @name input[email]
  15153. *
  15154. * @description
  15155. * Text input with email validation. Sets the `email` validation error key if not a valid email
  15156. * address.
  15157. *
  15158. * @param {string} ngModel Assignable angular expression to data-bind to.
  15159. * @param {string=} name Property name of the form under which the control is published.
  15160. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15161. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15162. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15163. * `required` when you want to data-bind to the `required` attribute.
  15164. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15165. * minlength.
  15166. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15167. * maxlength.
  15168. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15169. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15170. * patterns defined as scope expressions.
  15171. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15172. * interaction with the input element.
  15173. *
  15174. * @example
  15175. <example name="email-input-directive" module="emailExample">
  15176. <file name="index.html">
  15177. <script>
  15178. angular.module('emailExample', [])
  15179. .controller('ExampleController', ['$scope', function($scope) {
  15180. $scope.text = 'me@example.com';
  15181. }]);
  15182. </script>
  15183. <form name="myForm" ng-controller="ExampleController">
  15184. Email: <input type="email" name="input" ng-model="text" required>
  15185. <span class="error" ng-show="myForm.input.$error.required">
  15186. Required!</span>
  15187. <span class="error" ng-show="myForm.input.$error.email">
  15188. Not valid email!</span>
  15189. <tt>text = {{text}}</tt><br/>
  15190. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  15191. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  15192. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  15193. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  15194. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  15195. </form>
  15196. </file>
  15197. <file name="protractor.js" type="protractor">
  15198. var text = element(by.binding('text'));
  15199. var valid = element(by.binding('myForm.input.$valid'));
  15200. var input = element(by.model('text'));
  15201. it('should initialize to model', function() {
  15202. expect(text.getText()).toContain('me@example.com');
  15203. expect(valid.getText()).toContain('true');
  15204. });
  15205. it('should be invalid if empty', function() {
  15206. input.clear();
  15207. input.sendKeys('');
  15208. expect(text.getText()).toEqual('text =');
  15209. expect(valid.getText()).toContain('false');
  15210. });
  15211. it('should be invalid if not email', function() {
  15212. input.clear();
  15213. input.sendKeys('xxx');
  15214. expect(valid.getText()).toContain('false');
  15215. });
  15216. </file>
  15217. </example>
  15218. */
  15219. 'email': emailInputType,
  15220. /**
  15221. * @ngdoc input
  15222. * @name input[radio]
  15223. *
  15224. * @description
  15225. * HTML radio button.
  15226. *
  15227. * @param {string} ngModel Assignable angular expression to data-bind to.
  15228. * @param {string} value The value to which the expression should be set when selected.
  15229. * @param {string=} name Property name of the form under which the control is published.
  15230. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15231. * interaction with the input element.
  15232. * @param {string} ngValue Angular expression which sets the value to which the expression should
  15233. * be set when selected.
  15234. *
  15235. * @example
  15236. <example name="radio-input-directive" module="radioExample">
  15237. <file name="index.html">
  15238. <script>
  15239. angular.module('radioExample', [])
  15240. .controller('ExampleController', ['$scope', function($scope) {
  15241. $scope.color = 'blue';
  15242. $scope.specialValue = {
  15243. "id": "12345",
  15244. "value": "green"
  15245. };
  15246. }]);
  15247. </script>
  15248. <form name="myForm" ng-controller="ExampleController">
  15249. <input type="radio" ng-model="color" value="red"> Red <br/>
  15250. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  15251. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  15252. <tt>color = {{color | json}}</tt><br/>
  15253. </form>
  15254. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  15255. </file>
  15256. <file name="protractor.js" type="protractor">
  15257. it('should change state', function() {
  15258. var color = element(by.binding('color'));
  15259. expect(color.getText()).toContain('blue');
  15260. element.all(by.model('color')).get(0).click();
  15261. expect(color.getText()).toContain('red');
  15262. });
  15263. </file>
  15264. </example>
  15265. */
  15266. 'radio': radioInputType,
  15267. /**
  15268. * @ngdoc input
  15269. * @name input[checkbox]
  15270. *
  15271. * @description
  15272. * HTML checkbox.
  15273. *
  15274. * @param {string} ngModel Assignable angular expression to data-bind to.
  15275. * @param {string=} name Property name of the form under which the control is published.
  15276. * @param {string=} ngTrueValue The value to which the expression should be set when selected.
  15277. * @param {string=} ngFalseValue The value to which the expression should be set when not selected.
  15278. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15279. * interaction with the input element.
  15280. *
  15281. * @example
  15282. <example name="checkbox-input-directive" module="checkboxExample">
  15283. <file name="index.html">
  15284. <script>
  15285. angular.module('checkboxExample', [])
  15286. .controller('ExampleController', ['$scope', function($scope) {
  15287. $scope.value1 = true;
  15288. $scope.value2 = 'YES'
  15289. }]);
  15290. </script>
  15291. <form name="myForm" ng-controller="ExampleController">
  15292. Value1: <input type="checkbox" ng-model="value1"> <br/>
  15293. Value2: <input type="checkbox" ng-model="value2"
  15294. ng-true-value="YES" ng-false-value="NO"> <br/>
  15295. <tt>value1 = {{value1}}</tt><br/>
  15296. <tt>value2 = {{value2}}</tt><br/>
  15297. </form>
  15298. </file>
  15299. <file name="protractor.js" type="protractor">
  15300. it('should change state', function() {
  15301. var value1 = element(by.binding('value1'));
  15302. var value2 = element(by.binding('value2'));
  15303. expect(value1.getText()).toContain('true');
  15304. expect(value2.getText()).toContain('YES');
  15305. element(by.model('value1')).click();
  15306. element(by.model('value2')).click();
  15307. expect(value1.getText()).toContain('false');
  15308. expect(value2.getText()).toContain('NO');
  15309. });
  15310. </file>
  15311. </example>
  15312. */
  15313. 'checkbox': checkboxInputType,
  15314. 'hidden': noop,
  15315. 'button': noop,
  15316. 'submit': noop,
  15317. 'reset': noop,
  15318. 'file': noop
  15319. };
  15320. // A helper function to call $setValidity and return the value / undefined,
  15321. // a pattern that is repeated a lot in the input validation logic.
  15322. function validate(ctrl, validatorName, validity, value){
  15323. ctrl.$setValidity(validatorName, validity);
  15324. return validity ? value : undefined;
  15325. }
  15326. function testFlags(validity, flags) {
  15327. var i, flag;
  15328. if (flags) {
  15329. for (i=0; i<flags.length; ++i) {
  15330. flag = flags[i];
  15331. if (validity[flag]) {
  15332. return true;
  15333. }
  15334. }
  15335. }
  15336. return false;
  15337. }
  15338. // Pass validity so that behaviour can be mocked easier.
  15339. function addNativeHtml5Validators(ctrl, validatorName, badFlags, ignoreFlags, validity) {
  15340. if (isObject(validity)) {
  15341. ctrl.$$hasNativeValidators = true;
  15342. var validator = function(value) {
  15343. // Don't overwrite previous validation, don't consider valueMissing to apply (ng-required can
  15344. // perform the required validation)
  15345. if (!ctrl.$error[validatorName] &&
  15346. !testFlags(validity, ignoreFlags) &&
  15347. testFlags(validity, badFlags)) {
  15348. ctrl.$setValidity(validatorName, false);
  15349. return;
  15350. }
  15351. return value;
  15352. };
  15353. ctrl.$parsers.push(validator);
  15354. }
  15355. }
  15356. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15357. var validity = element.prop(VALIDITY_STATE_PROPERTY);
  15358. var placeholder = element[0].placeholder, noevent = {};
  15359. ctrl.$$validityState = validity;
  15360. // In composition mode, users are still inputing intermediate text buffer,
  15361. // hold the listener until composition is done.
  15362. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  15363. if (!$sniffer.android) {
  15364. var composing = false;
  15365. element.on('compositionstart', function(data) {
  15366. composing = true;
  15367. });
  15368. element.on('compositionend', function() {
  15369. composing = false;
  15370. listener();
  15371. });
  15372. }
  15373. var listener = function(ev) {
  15374. if (composing) return;
  15375. var value = element.val();
  15376. // IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
  15377. // We don't want to dirty the value when this happens, so we abort here. Unfortunately,
  15378. // IE also sends input events for other non-input-related things, (such as focusing on a
  15379. // form control), so this change is not entirely enough to solve this.
  15380. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
  15381. placeholder = element[0].placeholder;
  15382. return;
  15383. }
  15384. // By default we will trim the value
  15385. // If the attribute ng-trim exists we will avoid trimming
  15386. // e.g. <input ng-model="foo" ng-trim="false">
  15387. if (toBoolean(attr.ngTrim || 'T')) {
  15388. value = trim(value);
  15389. }
  15390. // If a control is suffering from bad input, browsers discard its value, so it may be
  15391. // necessary to revalidate even if the control's value is the same empty value twice in
  15392. // a row.
  15393. var revalidate = validity && ctrl.$$hasNativeValidators;
  15394. if (ctrl.$viewValue !== value || (value === '' && revalidate)) {
  15395. if (scope.$$phase) {
  15396. ctrl.$setViewValue(value);
  15397. } else {
  15398. scope.$apply(function() {
  15399. ctrl.$setViewValue(value);
  15400. });
  15401. }
  15402. }
  15403. };
  15404. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  15405. // input event on backspace, delete or cut
  15406. if ($sniffer.hasEvent('input')) {
  15407. element.on('input', listener);
  15408. } else {
  15409. var timeout;
  15410. var deferListener = function() {
  15411. if (!timeout) {
  15412. timeout = $browser.defer(function() {
  15413. listener();
  15414. timeout = null;
  15415. });
  15416. }
  15417. };
  15418. element.on('keydown', function(event) {
  15419. var key = event.keyCode;
  15420. // ignore
  15421. // command modifiers arrows
  15422. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  15423. deferListener();
  15424. });
  15425. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  15426. if ($sniffer.hasEvent('paste')) {
  15427. element.on('paste cut', deferListener);
  15428. }
  15429. }
  15430. // if user paste into input using mouse on older browser
  15431. // or form autocomplete on newer browser, we need "change" event to catch it
  15432. element.on('change', listener);
  15433. ctrl.$render = function() {
  15434. element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
  15435. };
  15436. // pattern validator
  15437. var pattern = attr.ngPattern,
  15438. patternValidator,
  15439. match;
  15440. if (pattern) {
  15441. var validateRegex = function(regexp, value) {
  15442. return validate(ctrl, 'pattern', ctrl.$isEmpty(value) || regexp.test(value), value);
  15443. };
  15444. match = pattern.match(/^\/(.*)\/([gim]*)$/);
  15445. if (match) {
  15446. pattern = new RegExp(match[1], match[2]);
  15447. patternValidator = function(value) {
  15448. return validateRegex(pattern, value);
  15449. };
  15450. } else {
  15451. patternValidator = function(value) {
  15452. var patternObj = scope.$eval(pattern);
  15453. if (!patternObj || !patternObj.test) {
  15454. throw minErr('ngPattern')('noregexp',
  15455. 'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
  15456. patternObj, startingTag(element));
  15457. }
  15458. return validateRegex(patternObj, value);
  15459. };
  15460. }
  15461. ctrl.$formatters.push(patternValidator);
  15462. ctrl.$parsers.push(patternValidator);
  15463. }
  15464. // min length validator
  15465. if (attr.ngMinlength) {
  15466. var minlength = int(attr.ngMinlength);
  15467. var minLengthValidator = function(value) {
  15468. return validate(ctrl, 'minlength', ctrl.$isEmpty(value) || value.length >= minlength, value);
  15469. };
  15470. ctrl.$parsers.push(minLengthValidator);
  15471. ctrl.$formatters.push(minLengthValidator);
  15472. }
  15473. // max length validator
  15474. if (attr.ngMaxlength) {
  15475. var maxlength = int(attr.ngMaxlength);
  15476. var maxLengthValidator = function(value) {
  15477. return validate(ctrl, 'maxlength', ctrl.$isEmpty(value) || value.length <= maxlength, value);
  15478. };
  15479. ctrl.$parsers.push(maxLengthValidator);
  15480. ctrl.$formatters.push(maxLengthValidator);
  15481. }
  15482. }
  15483. var numberBadFlags = ['badInput'];
  15484. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15485. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15486. ctrl.$parsers.push(function(value) {
  15487. var empty = ctrl.$isEmpty(value);
  15488. if (empty || NUMBER_REGEXP.test(value)) {
  15489. ctrl.$setValidity('number', true);
  15490. return value === '' ? null : (empty ? value : parseFloat(value));
  15491. } else {
  15492. ctrl.$setValidity('number', false);
  15493. return undefined;
  15494. }
  15495. });
  15496. addNativeHtml5Validators(ctrl, 'number', numberBadFlags, null, ctrl.$$validityState);
  15497. ctrl.$formatters.push(function(value) {
  15498. return ctrl.$isEmpty(value) ? '' : '' + value;
  15499. });
  15500. if (attr.min) {
  15501. var minValidator = function(value) {
  15502. var min = parseFloat(attr.min);
  15503. return validate(ctrl, 'min', ctrl.$isEmpty(value) || value >= min, value);
  15504. };
  15505. ctrl.$parsers.push(minValidator);
  15506. ctrl.$formatters.push(minValidator);
  15507. }
  15508. if (attr.max) {
  15509. var maxValidator = function(value) {
  15510. var max = parseFloat(attr.max);
  15511. return validate(ctrl, 'max', ctrl.$isEmpty(value) || value <= max, value);
  15512. };
  15513. ctrl.$parsers.push(maxValidator);
  15514. ctrl.$formatters.push(maxValidator);
  15515. }
  15516. ctrl.$formatters.push(function(value) {
  15517. return validate(ctrl, 'number', ctrl.$isEmpty(value) || isNumber(value), value);
  15518. });
  15519. }
  15520. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15521. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15522. var urlValidator = function(value) {
  15523. return validate(ctrl, 'url', ctrl.$isEmpty(value) || URL_REGEXP.test(value), value);
  15524. };
  15525. ctrl.$formatters.push(urlValidator);
  15526. ctrl.$parsers.push(urlValidator);
  15527. }
  15528. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  15529. textInputType(scope, element, attr, ctrl, $sniffer, $browser);
  15530. var emailValidator = function(value) {
  15531. return validate(ctrl, 'email', ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value), value);
  15532. };
  15533. ctrl.$formatters.push(emailValidator);
  15534. ctrl.$parsers.push(emailValidator);
  15535. }
  15536. function radioInputType(scope, element, attr, ctrl) {
  15537. // make the name unique, if not defined
  15538. if (isUndefined(attr.name)) {
  15539. element.attr('name', nextUid());
  15540. }
  15541. element.on('click', function() {
  15542. if (element[0].checked) {
  15543. scope.$apply(function() {
  15544. ctrl.$setViewValue(attr.value);
  15545. });
  15546. }
  15547. });
  15548. ctrl.$render = function() {
  15549. var value = attr.value;
  15550. element[0].checked = (value == ctrl.$viewValue);
  15551. };
  15552. attr.$observe('value', ctrl.$render);
  15553. }
  15554. function checkboxInputType(scope, element, attr, ctrl) {
  15555. var trueValue = attr.ngTrueValue,
  15556. falseValue = attr.ngFalseValue;
  15557. if (!isString(trueValue)) trueValue = true;
  15558. if (!isString(falseValue)) falseValue = false;
  15559. element.on('click', function() {
  15560. scope.$apply(function() {
  15561. ctrl.$setViewValue(element[0].checked);
  15562. });
  15563. });
  15564. ctrl.$render = function() {
  15565. element[0].checked = ctrl.$viewValue;
  15566. };
  15567. // Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
  15568. ctrl.$isEmpty = function(value) {
  15569. return value !== trueValue;
  15570. };
  15571. ctrl.$formatters.push(function(value) {
  15572. return value === trueValue;
  15573. });
  15574. ctrl.$parsers.push(function(value) {
  15575. return value ? trueValue : falseValue;
  15576. });
  15577. }
  15578. /**
  15579. * @ngdoc directive
  15580. * @name textarea
  15581. * @restrict E
  15582. *
  15583. * @description
  15584. * HTML textarea element control with angular data-binding. The data-binding and validation
  15585. * properties of this element are exactly the same as those of the
  15586. * {@link ng.directive:input input element}.
  15587. *
  15588. * @param {string} ngModel Assignable angular expression to data-bind to.
  15589. * @param {string=} name Property name of the form under which the control is published.
  15590. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15591. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  15592. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  15593. * `required` when you want to data-bind to the `required` attribute.
  15594. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15595. * minlength.
  15596. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15597. * maxlength.
  15598. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15599. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15600. * patterns defined as scope expressions.
  15601. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15602. * interaction with the input element.
  15603. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  15604. */
  15605. /**
  15606. * @ngdoc directive
  15607. * @name input
  15608. * @restrict E
  15609. *
  15610. * @description
  15611. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  15612. * and polyfills the HTML5 validation behavior for older browsers.
  15613. *
  15614. * @param {string} ngModel Assignable angular expression to data-bind to.
  15615. * @param {string=} name Property name of the form under which the control is published.
  15616. * @param {string=} required Sets `required` validation error key if the value is not entered.
  15617. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  15618. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  15619. * minlength.
  15620. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  15621. * maxlength.
  15622. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  15623. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  15624. * patterns defined as scope expressions.
  15625. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  15626. * interaction with the input element.
  15627. *
  15628. * @example
  15629. <example name="input-directive" module="inputExample">
  15630. <file name="index.html">
  15631. <script>
  15632. angular.module('inputExample', [])
  15633. .controller('ExampleController', ['$scope', function($scope) {
  15634. $scope.user = {name: 'guest', last: 'visitor'};
  15635. }]);
  15636. </script>
  15637. <div ng-controller="ExampleController">
  15638. <form name="myForm">
  15639. User name: <input type="text" name="userName" ng-model="user.name" required>
  15640. <span class="error" ng-show="myForm.userName.$error.required">
  15641. Required!</span><br>
  15642. Last name: <input type="text" name="lastName" ng-model="user.last"
  15643. ng-minlength="3" ng-maxlength="10">
  15644. <span class="error" ng-show="myForm.lastName.$error.minlength">
  15645. Too short!</span>
  15646. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  15647. Too long!</span><br>
  15648. </form>
  15649. <hr>
  15650. <tt>user = {{user}}</tt><br/>
  15651. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  15652. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  15653. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  15654. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  15655. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  15656. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  15657. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  15658. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  15659. </div>
  15660. </file>
  15661. <file name="protractor.js" type="protractor">
  15662. var user = element(by.binding('{{user}}'));
  15663. var userNameValid = element(by.binding('myForm.userName.$valid'));
  15664. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  15665. var lastNameError = element(by.binding('myForm.lastName.$error'));
  15666. var formValid = element(by.binding('myForm.$valid'));
  15667. var userNameInput = element(by.model('user.name'));
  15668. var userLastInput = element(by.model('user.last'));
  15669. it('should initialize to model', function() {
  15670. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  15671. expect(userNameValid.getText()).toContain('true');
  15672. expect(formValid.getText()).toContain('true');
  15673. });
  15674. it('should be invalid if empty when required', function() {
  15675. userNameInput.clear();
  15676. userNameInput.sendKeys('');
  15677. expect(user.getText()).toContain('{"last":"visitor"}');
  15678. expect(userNameValid.getText()).toContain('false');
  15679. expect(formValid.getText()).toContain('false');
  15680. });
  15681. it('should be valid if empty when min length is set', function() {
  15682. userLastInput.clear();
  15683. userLastInput.sendKeys('');
  15684. expect(user.getText()).toContain('{"name":"guest","last":""}');
  15685. expect(lastNameValid.getText()).toContain('true');
  15686. expect(formValid.getText()).toContain('true');
  15687. });
  15688. it('should be invalid if less than required min length', function() {
  15689. userLastInput.clear();
  15690. userLastInput.sendKeys('xx');
  15691. expect(user.getText()).toContain('{"name":"guest"}');
  15692. expect(lastNameValid.getText()).toContain('false');
  15693. expect(lastNameError.getText()).toContain('minlength');
  15694. expect(formValid.getText()).toContain('false');
  15695. });
  15696. it('should be invalid if longer than max length', function() {
  15697. userLastInput.clear();
  15698. userLastInput.sendKeys('some ridiculously long name');
  15699. expect(user.getText()).toContain('{"name":"guest"}');
  15700. expect(lastNameValid.getText()).toContain('false');
  15701. expect(lastNameError.getText()).toContain('maxlength');
  15702. expect(formValid.getText()).toContain('false');
  15703. });
  15704. </file>
  15705. </example>
  15706. */
  15707. var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
  15708. return {
  15709. restrict: 'E',
  15710. require: '?ngModel',
  15711. link: function(scope, element, attr, ctrl) {
  15712. if (ctrl) {
  15713. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
  15714. $browser);
  15715. }
  15716. }
  15717. };
  15718. }];
  15719. var VALID_CLASS = 'ng-valid',
  15720. INVALID_CLASS = 'ng-invalid',
  15721. PRISTINE_CLASS = 'ng-pristine',
  15722. DIRTY_CLASS = 'ng-dirty';
  15723. /**
  15724. * @ngdoc type
  15725. * @name ngModel.NgModelController
  15726. *
  15727. * @property {string} $viewValue Actual string value in the view.
  15728. * @property {*} $modelValue The value in the model, that the control is bound to.
  15729. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  15730. the control reads value from the DOM. Each function is called, in turn, passing the value
  15731. through to the next. The last return value is used to populate the model.
  15732. Used to sanitize / convert the value as well as validation. For validation,
  15733. the parsers should update the validity state using
  15734. {@link ngModel.NgModelController#$setValidity $setValidity()},
  15735. and return `undefined` for invalid values.
  15736. *
  15737. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  15738. the model value changes. Each function is called, in turn, passing the value through to the
  15739. next. Used to format / convert values for display in the control and validation.
  15740. * ```js
  15741. * function formatter(value) {
  15742. * if (value) {
  15743. * return value.toUpperCase();
  15744. * }
  15745. * }
  15746. * ngModel.$formatters.push(formatter);
  15747. * ```
  15748. *
  15749. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  15750. * view value has changed. It is called with no arguments, and its return value is ignored.
  15751. * This can be used in place of additional $watches against the model value.
  15752. *
  15753. * @property {Object} $error An object hash with all errors as keys.
  15754. *
  15755. * @property {boolean} $pristine True if user has not interacted with the control yet.
  15756. * @property {boolean} $dirty True if user has already interacted with the control.
  15757. * @property {boolean} $valid True if there is no error.
  15758. * @property {boolean} $invalid True if at least one error on the control.
  15759. *
  15760. * @description
  15761. *
  15762. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  15763. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  15764. * purposefully does not contain any logic which deals with DOM rendering or listening to
  15765. * DOM events. Such DOM related logic should be provided by other directives which make use of
  15766. * `NgModelController` for data-binding.
  15767. *
  15768. * ## Custom Control Example
  15769. * This example shows how to use `NgModelController` with a custom control to achieve
  15770. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  15771. * collaborate together to achieve the desired result.
  15772. *
  15773. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  15774. * contents be edited in place by the user. This will not work on older browsers.
  15775. *
  15776. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  15777. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  15778. * However, as we are using `$sce` the model can still decide to to provide unsafe content if it marks
  15779. * that content using the `$sce` service.
  15780. *
  15781. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  15782. <file name="style.css">
  15783. [contenteditable] {
  15784. border: 1px solid black;
  15785. background-color: white;
  15786. min-height: 20px;
  15787. }
  15788. .ng-invalid {
  15789. border: 1px solid red;
  15790. }
  15791. </file>
  15792. <file name="script.js">
  15793. angular.module('customControl', ['ngSanitize']).
  15794. directive('contenteditable', ['$sce', function($sce) {
  15795. return {
  15796. restrict: 'A', // only activate on element attribute
  15797. require: '?ngModel', // get a hold of NgModelController
  15798. link: function(scope, element, attrs, ngModel) {
  15799. if(!ngModel) return; // do nothing if no ng-model
  15800. // Specify how UI should be updated
  15801. ngModel.$render = function() {
  15802. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  15803. };
  15804. // Listen for change events to enable binding
  15805. element.on('blur keyup change', function() {
  15806. scope.$apply(read);
  15807. });
  15808. read(); // initialize
  15809. // Write data to the model
  15810. function read() {
  15811. var html = element.html();
  15812. // When we clear the content editable the browser leaves a <br> behind
  15813. // If strip-br attribute is provided then we strip this out
  15814. if( attrs.stripBr && html == '<br>' ) {
  15815. html = '';
  15816. }
  15817. ngModel.$setViewValue(html);
  15818. }
  15819. }
  15820. };
  15821. }]);
  15822. </file>
  15823. <file name="index.html">
  15824. <form name="myForm">
  15825. <div contenteditable
  15826. name="myWidget" ng-model="userContent"
  15827. strip-br="true"
  15828. required>Change me!</div>
  15829. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  15830. <hr>
  15831. <textarea ng-model="userContent"></textarea>
  15832. </form>
  15833. </file>
  15834. <file name="protractor.js" type="protractor">
  15835. it('should data-bind and become invalid', function() {
  15836. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  15837. // SafariDriver can't handle contenteditable
  15838. // and Firefox driver can't clear contenteditables very well
  15839. return;
  15840. }
  15841. var contentEditable = element(by.css('[contenteditable]'));
  15842. var content = 'Change me!';
  15843. expect(contentEditable.getText()).toEqual(content);
  15844. contentEditable.clear();
  15845. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  15846. expect(contentEditable.getText()).toEqual('');
  15847. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  15848. });
  15849. </file>
  15850. * </example>
  15851. *
  15852. *
  15853. */
  15854. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate',
  15855. function($scope, $exceptionHandler, $attr, $element, $parse, $animate) {
  15856. this.$viewValue = Number.NaN;
  15857. this.$modelValue = Number.NaN;
  15858. this.$parsers = [];
  15859. this.$formatters = [];
  15860. this.$viewChangeListeners = [];
  15861. this.$pristine = true;
  15862. this.$dirty = false;
  15863. this.$valid = true;
  15864. this.$invalid = false;
  15865. this.$name = $attr.name;
  15866. var ngModelGet = $parse($attr.ngModel),
  15867. ngModelSet = ngModelGet.assign;
  15868. if (!ngModelSet) {
  15869. throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  15870. $attr.ngModel, startingTag($element));
  15871. }
  15872. /**
  15873. * @ngdoc method
  15874. * @name ngModel.NgModelController#$render
  15875. *
  15876. * @description
  15877. * Called when the view needs to be updated. It is expected that the user of the ng-model
  15878. * directive will implement this method.
  15879. */
  15880. this.$render = noop;
  15881. /**
  15882. * @ngdoc method
  15883. * @name ngModel.NgModelController#$isEmpty
  15884. *
  15885. * @description
  15886. * This is called when we need to determine if the value of the input is empty.
  15887. *
  15888. * For instance, the required directive does this to work out if the input has data or not.
  15889. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  15890. *
  15891. * You can override this for input directives whose concept of being empty is different to the
  15892. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  15893. * implies empty.
  15894. *
  15895. * @param {*} value Reference to check.
  15896. * @returns {boolean} True if `value` is empty.
  15897. */
  15898. this.$isEmpty = function(value) {
  15899. return isUndefined(value) || value === '' || value === null || value !== value;
  15900. };
  15901. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  15902. invalidCount = 0, // used to easily determine if we are valid
  15903. $error = this.$error = {}; // keep invalid keys here
  15904. // Setup initial state of the control
  15905. $element.addClass(PRISTINE_CLASS);
  15906. toggleValidCss(true);
  15907. // convenience method for easy toggling of classes
  15908. function toggleValidCss(isValid, validationErrorKey) {
  15909. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  15910. $animate.removeClass($element, (isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey);
  15911. $animate.addClass($element, (isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
  15912. }
  15913. /**
  15914. * @ngdoc method
  15915. * @name ngModel.NgModelController#$setValidity
  15916. *
  15917. * @description
  15918. * Change the validity state, and notifies the form when the control changes validity. (i.e. it
  15919. * does not notify form if given validator is already marked as invalid).
  15920. *
  15921. * This method should be called by validators - i.e. the parser or formatter functions.
  15922. *
  15923. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  15924. * to `$error[validationErrorKey]=!isValid` so that it is available for data-binding.
  15925. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  15926. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  15927. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  15928. * @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
  15929. */
  15930. this.$setValidity = function(validationErrorKey, isValid) {
  15931. // Purposeful use of ! here to cast isValid to boolean in case it is undefined
  15932. // jshint -W018
  15933. if ($error[validationErrorKey] === !isValid) return;
  15934. // jshint +W018
  15935. if (isValid) {
  15936. if ($error[validationErrorKey]) invalidCount--;
  15937. if (!invalidCount) {
  15938. toggleValidCss(true);
  15939. this.$valid = true;
  15940. this.$invalid = false;
  15941. }
  15942. } else {
  15943. toggleValidCss(false);
  15944. this.$invalid = true;
  15945. this.$valid = false;
  15946. invalidCount++;
  15947. }
  15948. $error[validationErrorKey] = !isValid;
  15949. toggleValidCss(isValid, validationErrorKey);
  15950. parentForm.$setValidity(validationErrorKey, isValid, this);
  15951. };
  15952. /**
  15953. * @ngdoc method
  15954. * @name ngModel.NgModelController#$setPristine
  15955. *
  15956. * @description
  15957. * Sets the control to its pristine state.
  15958. *
  15959. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  15960. * state (ng-pristine class).
  15961. */
  15962. this.$setPristine = function () {
  15963. this.$dirty = false;
  15964. this.$pristine = true;
  15965. $animate.removeClass($element, DIRTY_CLASS);
  15966. $animate.addClass($element, PRISTINE_CLASS);
  15967. };
  15968. /**
  15969. * @ngdoc method
  15970. * @name ngModel.NgModelController#$setViewValue
  15971. *
  15972. * @description
  15973. * Update the view value.
  15974. *
  15975. * This method should be called when the view value changes, typically from within a DOM event handler.
  15976. * For example {@link ng.directive:input input} and
  15977. * {@link ng.directive:select select} directives call it.
  15978. *
  15979. * It will update the $viewValue, then pass this value through each of the functions in `$parsers`,
  15980. * which includes any validators. The value that comes out of this `$parsers` pipeline, be applied to
  15981. * `$modelValue` and the **expression** specified in the `ng-model` attribute.
  15982. *
  15983. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  15984. *
  15985. * Note that calling this function does not trigger a `$digest`.
  15986. *
  15987. * @param {string} value Value from the view.
  15988. */
  15989. this.$setViewValue = function(value) {
  15990. this.$viewValue = value;
  15991. // change to dirty
  15992. if (this.$pristine) {
  15993. this.$dirty = true;
  15994. this.$pristine = false;
  15995. $animate.removeClass($element, PRISTINE_CLASS);
  15996. $animate.addClass($element, DIRTY_CLASS);
  15997. parentForm.$setDirty();
  15998. }
  15999. forEach(this.$parsers, function(fn) {
  16000. value = fn(value);
  16001. });
  16002. if (this.$modelValue !== value) {
  16003. this.$modelValue = value;
  16004. ngModelSet($scope, value);
  16005. forEach(this.$viewChangeListeners, function(listener) {
  16006. try {
  16007. listener();
  16008. } catch(e) {
  16009. $exceptionHandler(e);
  16010. }
  16011. });
  16012. }
  16013. };
  16014. // model -> value
  16015. var ctrl = this;
  16016. $scope.$watch(function ngModelWatch() {
  16017. var value = ngModelGet($scope);
  16018. // if scope model value and ngModel value are out of sync
  16019. if (ctrl.$modelValue !== value) {
  16020. var formatters = ctrl.$formatters,
  16021. idx = formatters.length;
  16022. ctrl.$modelValue = value;
  16023. while(idx--) {
  16024. value = formatters[idx](value);
  16025. }
  16026. if (ctrl.$viewValue !== value) {
  16027. ctrl.$viewValue = value;
  16028. ctrl.$render();
  16029. }
  16030. }
  16031. return value;
  16032. });
  16033. }];
  16034. /**
  16035. * @ngdoc directive
  16036. * @name ngModel
  16037. *
  16038. * @element input
  16039. *
  16040. * @description
  16041. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  16042. * property on the scope using {@link ngModel.NgModelController NgModelController},
  16043. * which is created and exposed by this directive.
  16044. *
  16045. * `ngModel` is responsible for:
  16046. *
  16047. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  16048. * require.
  16049. * - Providing validation behavior (i.e. required, number, email, url).
  16050. * - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
  16051. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`) including animations.
  16052. * - Registering the control with its parent {@link ng.directive:form form}.
  16053. *
  16054. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  16055. * current scope. If the property doesn't already exist on this scope, it will be created
  16056. * implicitly and added to the scope.
  16057. *
  16058. * For best practices on using `ngModel`, see:
  16059. *
  16060. * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes]
  16061. *
  16062. * For basic examples, how to use `ngModel`, see:
  16063. *
  16064. * - {@link ng.directive:input input}
  16065. * - {@link input[text] text}
  16066. * - {@link input[checkbox] checkbox}
  16067. * - {@link input[radio] radio}
  16068. * - {@link input[number] number}
  16069. * - {@link input[email] email}
  16070. * - {@link input[url] url}
  16071. * - {@link ng.directive:select select}
  16072. * - {@link ng.directive:textarea textarea}
  16073. *
  16074. * # CSS classes
  16075. * The following CSS classes are added and removed on the associated input/select/textarea element
  16076. * depending on the validity of the model.
  16077. *
  16078. * - `ng-valid` is set if the model is valid.
  16079. * - `ng-invalid` is set if the model is invalid.
  16080. * - `ng-pristine` is set if the model is pristine.
  16081. * - `ng-dirty` is set if the model is dirty.
  16082. *
  16083. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16084. *
  16085. * ## Animation Hooks
  16086. *
  16087. * Animations within models are triggered when any of the associated CSS classes are added and removed
  16088. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  16089. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  16090. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  16091. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  16092. *
  16093. * The following example shows a simple way to utilize CSS transitions to style an input element
  16094. * that has been rendered as invalid after it has been validated:
  16095. *
  16096. * <pre>
  16097. * //be sure to include ngAnimate as a module to hook into more
  16098. * //advanced animations
  16099. * .my-input {
  16100. * transition:0.5s linear all;
  16101. * background: white;
  16102. * }
  16103. * .my-input.ng-invalid {
  16104. * background: red;
  16105. * color:white;
  16106. * }
  16107. * </pre>
  16108. *
  16109. * @example
  16110. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  16111. <file name="index.html">
  16112. <script>
  16113. angular.module('inputExample', [])
  16114. .controller('ExampleController', ['$scope', function($scope) {
  16115. $scope.val = '1';
  16116. }]);
  16117. </script>
  16118. <style>
  16119. .my-input {
  16120. -webkit-transition:all linear 0.5s;
  16121. transition:all linear 0.5s;
  16122. background: transparent;
  16123. }
  16124. .my-input.ng-invalid {
  16125. color:white;
  16126. background: red;
  16127. }
  16128. </style>
  16129. Update input to see transitions when valid/invalid.
  16130. Integer is a valid value.
  16131. <form name="testForm" ng-controller="ExampleController">
  16132. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  16133. </form>
  16134. </file>
  16135. * </example>
  16136. */
  16137. var ngModelDirective = function() {
  16138. return {
  16139. require: ['ngModel', '^?form'],
  16140. controller: NgModelController,
  16141. link: function(scope, element, attr, ctrls) {
  16142. // notify others, especially parent forms
  16143. var modelCtrl = ctrls[0],
  16144. formCtrl = ctrls[1] || nullFormCtrl;
  16145. formCtrl.$addControl(modelCtrl);
  16146. scope.$on('$destroy', function() {
  16147. formCtrl.$removeControl(modelCtrl);
  16148. });
  16149. }
  16150. };
  16151. };
  16152. /**
  16153. * @ngdoc directive
  16154. * @name ngChange
  16155. *
  16156. * @description
  16157. * Evaluate the given expression when the user changes the input.
  16158. * The expression is evaluated immediately, unlike the JavaScript onchange event
  16159. * which only triggers at the end of a change (usually, when the user leaves the
  16160. * form element or presses the return key).
  16161. * The expression is not evaluated when the value change is coming from the model.
  16162. *
  16163. * Note, this directive requires `ngModel` to be present.
  16164. *
  16165. * @element input
  16166. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  16167. * in input value.
  16168. *
  16169. * @example
  16170. * <example name="ngChange-directive" module="changeExample">
  16171. * <file name="index.html">
  16172. * <script>
  16173. * angular.module('changeExample', [])
  16174. * .controller('ExampleController', ['$scope', function($scope) {
  16175. * $scope.counter = 0;
  16176. * $scope.change = function() {
  16177. * $scope.counter++;
  16178. * };
  16179. * }]);
  16180. * </script>
  16181. * <div ng-controller="ExampleController">
  16182. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  16183. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  16184. * <label for="ng-change-example2">Confirmed</label><br />
  16185. * <tt>debug = {{confirmed}}</tt><br/>
  16186. * <tt>counter = {{counter}}</tt><br/>
  16187. * </div>
  16188. * </file>
  16189. * <file name="protractor.js" type="protractor">
  16190. * var counter = element(by.binding('counter'));
  16191. * var debug = element(by.binding('confirmed'));
  16192. *
  16193. * it('should evaluate the expression if changing from view', function() {
  16194. * expect(counter.getText()).toContain('0');
  16195. *
  16196. * element(by.id('ng-change-example1')).click();
  16197. *
  16198. * expect(counter.getText()).toContain('1');
  16199. * expect(debug.getText()).toContain('true');
  16200. * });
  16201. *
  16202. * it('should not evaluate the expression if changing from model', function() {
  16203. * element(by.id('ng-change-example2')).click();
  16204. * expect(counter.getText()).toContain('0');
  16205. * expect(debug.getText()).toContain('true');
  16206. * });
  16207. * </file>
  16208. * </example>
  16209. */
  16210. var ngChangeDirective = valueFn({
  16211. require: 'ngModel',
  16212. link: function(scope, element, attr, ctrl) {
  16213. ctrl.$viewChangeListeners.push(function() {
  16214. scope.$eval(attr.ngChange);
  16215. });
  16216. }
  16217. });
  16218. var requiredDirective = function() {
  16219. return {
  16220. require: '?ngModel',
  16221. link: function(scope, elm, attr, ctrl) {
  16222. if (!ctrl) return;
  16223. attr.required = true; // force truthy in case we are on non input element
  16224. var validator = function(value) {
  16225. if (attr.required && ctrl.$isEmpty(value)) {
  16226. ctrl.$setValidity('required', false);
  16227. return;
  16228. } else {
  16229. ctrl.$setValidity('required', true);
  16230. return value;
  16231. }
  16232. };
  16233. ctrl.$formatters.push(validator);
  16234. ctrl.$parsers.unshift(validator);
  16235. attr.$observe('required', function() {
  16236. validator(ctrl.$viewValue);
  16237. });
  16238. }
  16239. };
  16240. };
  16241. /**
  16242. * @ngdoc directive
  16243. * @name ngList
  16244. *
  16245. * @description
  16246. * Text input that converts between a delimited string and an array of strings. The delimiter
  16247. * can be a fixed string (by default a comma) or a regular expression.
  16248. *
  16249. * @element input
  16250. * @param {string=} ngList optional delimiter that should be used to split the value. If
  16251. * specified in form `/something/` then the value will be converted into a regular expression.
  16252. *
  16253. * @example
  16254. <example name="ngList-directive" module="listExample">
  16255. <file name="index.html">
  16256. <script>
  16257. angular.module('listExample', [])
  16258. .controller('ExampleController', ['$scope', function($scope) {
  16259. $scope.names = ['igor', 'misko', 'vojta'];
  16260. }]);
  16261. </script>
  16262. <form name="myForm" ng-controller="ExampleController">
  16263. List: <input name="namesInput" ng-model="names" ng-list required>
  16264. <span class="error" ng-show="myForm.namesInput.$error.required">
  16265. Required!</span>
  16266. <br>
  16267. <tt>names = {{names}}</tt><br/>
  16268. <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  16269. <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  16270. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16271. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16272. </form>
  16273. </file>
  16274. <file name="protractor.js" type="protractor">
  16275. var listInput = element(by.model('names'));
  16276. var names = element(by.binding('{{names}}'));
  16277. var valid = element(by.binding('myForm.namesInput.$valid'));
  16278. var error = element(by.css('span.error'));
  16279. it('should initialize to model', function() {
  16280. expect(names.getText()).toContain('["igor","misko","vojta"]');
  16281. expect(valid.getText()).toContain('true');
  16282. expect(error.getCssValue('display')).toBe('none');
  16283. });
  16284. it('should be invalid if empty', function() {
  16285. listInput.clear();
  16286. listInput.sendKeys('');
  16287. expect(names.getText()).toContain('');
  16288. expect(valid.getText()).toContain('false');
  16289. expect(error.getCssValue('display')).not.toBe('none'); });
  16290. </file>
  16291. </example>
  16292. */
  16293. var ngListDirective = function() {
  16294. return {
  16295. require: 'ngModel',
  16296. link: function(scope, element, attr, ctrl) {
  16297. var match = /\/(.*)\//.exec(attr.ngList),
  16298. separator = match && new RegExp(match[1]) || attr.ngList || ',';
  16299. var parse = function(viewValue) {
  16300. // If the viewValue is invalid (say required but empty) it will be `undefined`
  16301. if (isUndefined(viewValue)) return;
  16302. var list = [];
  16303. if (viewValue) {
  16304. forEach(viewValue.split(separator), function(value) {
  16305. if (value) list.push(trim(value));
  16306. });
  16307. }
  16308. return list;
  16309. };
  16310. ctrl.$parsers.push(parse);
  16311. ctrl.$formatters.push(function(value) {
  16312. if (isArray(value)) {
  16313. return value.join(', ');
  16314. }
  16315. return undefined;
  16316. });
  16317. // Override the standard $isEmpty because an empty array means the input is empty.
  16318. ctrl.$isEmpty = function(value) {
  16319. return !value || !value.length;
  16320. };
  16321. }
  16322. };
  16323. };
  16324. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  16325. /**
  16326. * @ngdoc directive
  16327. * @name ngValue
  16328. *
  16329. * @description
  16330. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  16331. * that when the element is selected, the `ngModel` of that element is set to the
  16332. * bound value.
  16333. *
  16334. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  16335. * shown below.
  16336. *
  16337. * @element input
  16338. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  16339. * of the `input` element
  16340. *
  16341. * @example
  16342. <example name="ngValue-directive" module="valueExample">
  16343. <file name="index.html">
  16344. <script>
  16345. angular.module('valueExample', [])
  16346. .controller('ExampleController', ['$scope', function($scope) {
  16347. $scope.names = ['pizza', 'unicorns', 'robots'];
  16348. $scope.my = { favorite: 'unicorns' };
  16349. }]);
  16350. </script>
  16351. <form ng-controller="ExampleController">
  16352. <h2>Which is your favorite?</h2>
  16353. <label ng-repeat="name in names" for="{{name}}">
  16354. {{name}}
  16355. <input type="radio"
  16356. ng-model="my.favorite"
  16357. ng-value="name"
  16358. id="{{name}}"
  16359. name="favorite">
  16360. </label>
  16361. <div>You chose {{my.favorite}}</div>
  16362. </form>
  16363. </file>
  16364. <file name="protractor.js" type="protractor">
  16365. var favorite = element(by.binding('my.favorite'));
  16366. it('should initialize to model', function() {
  16367. expect(favorite.getText()).toContain('unicorns');
  16368. });
  16369. it('should bind the values to the inputs', function() {
  16370. element.all(by.model('my.favorite')).get(0).click();
  16371. expect(favorite.getText()).toContain('pizza');
  16372. });
  16373. </file>
  16374. </example>
  16375. */
  16376. var ngValueDirective = function() {
  16377. return {
  16378. priority: 100,
  16379. compile: function(tpl, tplAttr) {
  16380. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  16381. return function ngValueConstantLink(scope, elm, attr) {
  16382. attr.$set('value', scope.$eval(attr.ngValue));
  16383. };
  16384. } else {
  16385. return function ngValueLink(scope, elm, attr) {
  16386. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  16387. attr.$set('value', value);
  16388. });
  16389. };
  16390. }
  16391. }
  16392. };
  16393. };
  16394. /**
  16395. * @ngdoc directive
  16396. * @name ngBind
  16397. * @restrict AC
  16398. *
  16399. * @description
  16400. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  16401. * with the value of a given expression, and to update the text content when the value of that
  16402. * expression changes.
  16403. *
  16404. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  16405. * `{{ expression }}` which is similar but less verbose.
  16406. *
  16407. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  16408. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  16409. * element attribute, it makes the bindings invisible to the user while the page is loading.
  16410. *
  16411. * An alternative solution to this problem would be using the
  16412. * {@link ng.directive:ngCloak ngCloak} directive.
  16413. *
  16414. *
  16415. * @element ANY
  16416. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  16417. *
  16418. * @example
  16419. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  16420. <example module="bindExample">
  16421. <file name="index.html">
  16422. <script>
  16423. angular.module('bindExample', [])
  16424. .controller('ExampleController', ['$scope', function($scope) {
  16425. $scope.name = 'Whirled';
  16426. }]);
  16427. </script>
  16428. <div ng-controller="ExampleController">
  16429. Enter name: <input type="text" ng-model="name"><br>
  16430. Hello <span ng-bind="name"></span>!
  16431. </div>
  16432. </file>
  16433. <file name="protractor.js" type="protractor">
  16434. it('should check ng-bind', function() {
  16435. var nameInput = element(by.model('name'));
  16436. expect(element(by.binding('name')).getText()).toBe('Whirled');
  16437. nameInput.clear();
  16438. nameInput.sendKeys('world');
  16439. expect(element(by.binding('name')).getText()).toBe('world');
  16440. });
  16441. </file>
  16442. </example>
  16443. */
  16444. var ngBindDirective = ngDirective({
  16445. compile: function(templateElement) {
  16446. templateElement.addClass('ng-binding');
  16447. return function (scope, element, attr) {
  16448. element.data('$binding', attr.ngBind);
  16449. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  16450. // We are purposefully using == here rather than === because we want to
  16451. // catch when value is "null or undefined"
  16452. // jshint -W041
  16453. element.text(value == undefined ? '' : value);
  16454. });
  16455. };
  16456. }
  16457. });
  16458. /**
  16459. * @ngdoc directive
  16460. * @name ngBindTemplate
  16461. *
  16462. * @description
  16463. * The `ngBindTemplate` directive specifies that the element
  16464. * text content should be replaced with the interpolation of the template
  16465. * in the `ngBindTemplate` attribute.
  16466. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  16467. * expressions. This directive is needed since some HTML elements
  16468. * (such as TITLE and OPTION) cannot contain SPAN elements.
  16469. *
  16470. * @element ANY
  16471. * @param {string} ngBindTemplate template of form
  16472. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  16473. *
  16474. * @example
  16475. * Try it here: enter text in text box and watch the greeting change.
  16476. <example module="bindExample">
  16477. <file name="index.html">
  16478. <script>
  16479. angular.module('bindExample', [])
  16480. .controller('ExampleController', ['$scope', function ($scope) {
  16481. $scope.salutation = 'Hello';
  16482. $scope.name = 'World';
  16483. }]);
  16484. </script>
  16485. <div ng-controller="ExampleController">
  16486. Salutation: <input type="text" ng-model="salutation"><br>
  16487. Name: <input type="text" ng-model="name"><br>
  16488. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  16489. </div>
  16490. </file>
  16491. <file name="protractor.js" type="protractor">
  16492. it('should check ng-bind', function() {
  16493. var salutationElem = element(by.binding('salutation'));
  16494. var salutationInput = element(by.model('salutation'));
  16495. var nameInput = element(by.model('name'));
  16496. expect(salutationElem.getText()).toBe('Hello World!');
  16497. salutationInput.clear();
  16498. salutationInput.sendKeys('Greetings');
  16499. nameInput.clear();
  16500. nameInput.sendKeys('user');
  16501. expect(salutationElem.getText()).toBe('Greetings user!');
  16502. });
  16503. </file>
  16504. </example>
  16505. */
  16506. var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
  16507. return function(scope, element, attr) {
  16508. // TODO: move this to scenario runner
  16509. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  16510. element.addClass('ng-binding').data('$binding', interpolateFn);
  16511. attr.$observe('ngBindTemplate', function(value) {
  16512. element.text(value);
  16513. });
  16514. };
  16515. }];
  16516. /**
  16517. * @ngdoc directive
  16518. * @name ngBindHtml
  16519. *
  16520. * @description
  16521. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  16522. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  16523. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  16524. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  16525. * core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to
  16526. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  16527. * under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
  16528. *
  16529. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  16530. * will have an exception (instead of an exploit.)
  16531. *
  16532. * @element ANY
  16533. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  16534. *
  16535. * @example
  16536. Try it here: enter text in text box and watch the greeting change.
  16537. <example module="bindHtmlExample" deps="angular-sanitize.js">
  16538. <file name="index.html">
  16539. <div ng-controller="ExampleController">
  16540. <p ng-bind-html="myHTML"></p>
  16541. </div>
  16542. </file>
  16543. <file name="script.js">
  16544. angular.module('bindHtmlExample', ['ngSanitize'])
  16545. .controller('ExampleController', ['$scope', function($scope) {
  16546. $scope.myHTML =
  16547. 'I am an <code>HTML</code>string with ' +
  16548. '<a href="#">links!</a> and other <em>stuff</em>';
  16549. }]);
  16550. </file>
  16551. <file name="protractor.js" type="protractor">
  16552. it('should check ng-bind-html', function() {
  16553. expect(element(by.binding('myHTML')).getText()).toBe(
  16554. 'I am an HTMLstring with links! and other stuff');
  16555. });
  16556. </file>
  16557. </example>
  16558. */
  16559. var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
  16560. return {
  16561. compile: function (tElement) {
  16562. tElement.addClass('ng-binding');
  16563. return function (scope, element, attr) {
  16564. element.data('$binding', attr.ngBindHtml);
  16565. var parsed = $parse(attr.ngBindHtml);
  16566. function getStringValue() {
  16567. return (parsed(scope) || '').toString();
  16568. }
  16569. scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
  16570. element.html($sce.getTrustedHtml(parsed(scope)) || '');
  16571. });
  16572. };
  16573. }
  16574. };
  16575. }];
  16576. function classDirective(name, selector) {
  16577. name = 'ngClass' + name;
  16578. return ['$animate', function($animate) {
  16579. return {
  16580. restrict: 'AC',
  16581. link: function(scope, element, attr) {
  16582. var oldVal;
  16583. scope.$watch(attr[name], ngClassWatchAction, true);
  16584. attr.$observe('class', function(value) {
  16585. ngClassWatchAction(scope.$eval(attr[name]));
  16586. });
  16587. if (name !== 'ngClass') {
  16588. scope.$watch('$index', function($index, old$index) {
  16589. // jshint bitwise: false
  16590. var mod = $index & 1;
  16591. if (mod !== (old$index & 1)) {
  16592. var classes = arrayClasses(scope.$eval(attr[name]));
  16593. mod === selector ?
  16594. addClasses(classes) :
  16595. removeClasses(classes);
  16596. }
  16597. });
  16598. }
  16599. function addClasses(classes) {
  16600. var newClasses = digestClassCounts(classes, 1);
  16601. attr.$addClass(newClasses);
  16602. }
  16603. function removeClasses(classes) {
  16604. var newClasses = digestClassCounts(classes, -1);
  16605. attr.$removeClass(newClasses);
  16606. }
  16607. function digestClassCounts (classes, count) {
  16608. var classCounts = element.data('$classCounts') || {};
  16609. var classesToUpdate = [];
  16610. forEach(classes, function (className) {
  16611. if (count > 0 || classCounts[className]) {
  16612. classCounts[className] = (classCounts[className] || 0) + count;
  16613. if (classCounts[className] === +(count > 0)) {
  16614. classesToUpdate.push(className);
  16615. }
  16616. }
  16617. });
  16618. element.data('$classCounts', classCounts);
  16619. return classesToUpdate.join(' ');
  16620. }
  16621. function updateClasses (oldClasses, newClasses) {
  16622. var toAdd = arrayDifference(newClasses, oldClasses);
  16623. var toRemove = arrayDifference(oldClasses, newClasses);
  16624. toRemove = digestClassCounts(toRemove, -1);
  16625. toAdd = digestClassCounts(toAdd, 1);
  16626. if (toAdd.length === 0) {
  16627. $animate.removeClass(element, toRemove);
  16628. } else if (toRemove.length === 0) {
  16629. $animate.addClass(element, toAdd);
  16630. } else {
  16631. $animate.setClass(element, toAdd, toRemove);
  16632. }
  16633. }
  16634. function ngClassWatchAction(newVal) {
  16635. if (selector === true || scope.$index % 2 === selector) {
  16636. var newClasses = arrayClasses(newVal || []);
  16637. if (!oldVal) {
  16638. addClasses(newClasses);
  16639. } else if (!equals(newVal,oldVal)) {
  16640. var oldClasses = arrayClasses(oldVal);
  16641. updateClasses(oldClasses, newClasses);
  16642. }
  16643. }
  16644. oldVal = shallowCopy(newVal);
  16645. }
  16646. }
  16647. };
  16648. function arrayDifference(tokens1, tokens2) {
  16649. var values = [];
  16650. outer:
  16651. for(var i = 0; i < tokens1.length; i++) {
  16652. var token = tokens1[i];
  16653. for(var j = 0; j < tokens2.length; j++) {
  16654. if(token == tokens2[j]) continue outer;
  16655. }
  16656. values.push(token);
  16657. }
  16658. return values;
  16659. }
  16660. function arrayClasses (classVal) {
  16661. if (isArray(classVal)) {
  16662. return classVal;
  16663. } else if (isString(classVal)) {
  16664. return classVal.split(' ');
  16665. } else if (isObject(classVal)) {
  16666. var classes = [], i = 0;
  16667. forEach(classVal, function(v, k) {
  16668. if (v) {
  16669. classes = classes.concat(k.split(' '));
  16670. }
  16671. });
  16672. return classes;
  16673. }
  16674. return classVal;
  16675. }
  16676. }];
  16677. }
  16678. /**
  16679. * @ngdoc directive
  16680. * @name ngClass
  16681. * @restrict AC
  16682. *
  16683. * @description
  16684. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  16685. * an expression that represents all classes to be added.
  16686. *
  16687. * The directive operates in three different ways, depending on which of three types the expression
  16688. * evaluates to:
  16689. *
  16690. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  16691. * names.
  16692. *
  16693. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  16694. * one or more space-delimited class names.
  16695. *
  16696. * 3. If the expression evaluates to an object, then for each key-value pair of the
  16697. * object with a truthy value the corresponding key is used as a class name.
  16698. *
  16699. * The directive won't add duplicate classes if a particular class was already set.
  16700. *
  16701. * When the expression changes, the previously added classes are removed and only then the
  16702. * new classes are added.
  16703. *
  16704. * @animations
  16705. * add - happens just before the class is applied to the element
  16706. * remove - happens just before the class is removed from the element
  16707. *
  16708. * @element ANY
  16709. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  16710. * of the evaluation can be a string representing space delimited class
  16711. * names, an array, or a map of class names to boolean values. In the case of a map, the
  16712. * names of the properties whose values are truthy will be added as css classes to the
  16713. * element.
  16714. *
  16715. * @example Example that demonstrates basic bindings via ngClass directive.
  16716. <example>
  16717. <file name="index.html">
  16718. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  16719. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  16720. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  16721. <input type="checkbox" ng-model="error"> error (apply "red" class)
  16722. <hr>
  16723. <p ng-class="style">Using String Syntax</p>
  16724. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  16725. <hr>
  16726. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  16727. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  16728. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  16729. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  16730. </file>
  16731. <file name="style.css">
  16732. .strike {
  16733. text-decoration: line-through;
  16734. }
  16735. .bold {
  16736. font-weight: bold;
  16737. }
  16738. .red {
  16739. color: red;
  16740. }
  16741. </file>
  16742. <file name="protractor.js" type="protractor">
  16743. var ps = element.all(by.css('p'));
  16744. it('should let you toggle the class', function() {
  16745. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  16746. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  16747. element(by.model('important')).click();
  16748. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  16749. element(by.model('error')).click();
  16750. expect(ps.first().getAttribute('class')).toMatch(/red/);
  16751. });
  16752. it('should let you toggle string example', function() {
  16753. expect(ps.get(1).getAttribute('class')).toBe('');
  16754. element(by.model('style')).clear();
  16755. element(by.model('style')).sendKeys('red');
  16756. expect(ps.get(1).getAttribute('class')).toBe('red');
  16757. });
  16758. it('array example should have 3 classes', function() {
  16759. expect(ps.last().getAttribute('class')).toBe('');
  16760. element(by.model('style1')).sendKeys('bold');
  16761. element(by.model('style2')).sendKeys('strike');
  16762. element(by.model('style3')).sendKeys('red');
  16763. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  16764. });
  16765. </file>
  16766. </example>
  16767. ## Animations
  16768. The example below demonstrates how to perform animations using ngClass.
  16769. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  16770. <file name="index.html">
  16771. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  16772. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  16773. <br>
  16774. <span class="base-class" ng-class="myVar">Sample Text</span>
  16775. </file>
  16776. <file name="style.css">
  16777. .base-class {
  16778. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16779. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  16780. }
  16781. .base-class.my-class {
  16782. color: red;
  16783. font-size:3em;
  16784. }
  16785. </file>
  16786. <file name="protractor.js" type="protractor">
  16787. it('should check ng-class', function() {
  16788. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16789. toMatch(/my-class/);
  16790. element(by.id('setbtn')).click();
  16791. expect(element(by.css('.base-class')).getAttribute('class')).
  16792. toMatch(/my-class/);
  16793. element(by.id('clearbtn')).click();
  16794. expect(element(by.css('.base-class')).getAttribute('class')).not.
  16795. toMatch(/my-class/);
  16796. });
  16797. </file>
  16798. </example>
  16799. ## ngClass and pre-existing CSS3 Transitions/Animations
  16800. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  16801. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  16802. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  16803. to view the step by step details of {@link ngAnimate.$animate#addclass $animate.addClass} and
  16804. {@link ngAnimate.$animate#removeclass $animate.removeClass}.
  16805. */
  16806. var ngClassDirective = classDirective('', true);
  16807. /**
  16808. * @ngdoc directive
  16809. * @name ngClassOdd
  16810. * @restrict AC
  16811. *
  16812. * @description
  16813. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  16814. * {@link ng.directive:ngClass ngClass}, except they work in
  16815. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  16816. *
  16817. * This directive can be applied only within the scope of an
  16818. * {@link ng.directive:ngRepeat ngRepeat}.
  16819. *
  16820. * @element ANY
  16821. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  16822. * of the evaluation can be a string representing space delimited class names or an array.
  16823. *
  16824. * @example
  16825. <example>
  16826. <file name="index.html">
  16827. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  16828. <li ng-repeat="name in names">
  16829. <span ng-class-odd="'odd'" ng-class-even="'even'">
  16830. {{name}}
  16831. </span>
  16832. </li>
  16833. </ol>
  16834. </file>
  16835. <file name="style.css">
  16836. .odd {
  16837. color: red;
  16838. }
  16839. .even {
  16840. color: blue;
  16841. }
  16842. </file>
  16843. <file name="protractor.js" type="protractor">
  16844. it('should check ng-class-odd and ng-class-even', function() {
  16845. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  16846. toMatch(/odd/);
  16847. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  16848. toMatch(/even/);
  16849. });
  16850. </file>
  16851. </example>
  16852. */
  16853. var ngClassOddDirective = classDirective('Odd', 0);
  16854. /**
  16855. * @ngdoc directive
  16856. * @name ngClassEven
  16857. * @restrict AC
  16858. *
  16859. * @description
  16860. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  16861. * {@link ng.directive:ngClass ngClass}, except they work in
  16862. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  16863. *
  16864. * This directive can be applied only within the scope of an
  16865. * {@link ng.directive:ngRepeat ngRepeat}.
  16866. *
  16867. * @element ANY
  16868. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  16869. * result of the evaluation can be a string representing space delimited class names or an array.
  16870. *
  16871. * @example
  16872. <example>
  16873. <file name="index.html">
  16874. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  16875. <li ng-repeat="name in names">
  16876. <span ng-class-odd="'odd'" ng-class-even="'even'">
  16877. {{name}} &nbsp; &nbsp; &nbsp;
  16878. </span>
  16879. </li>
  16880. </ol>
  16881. </file>
  16882. <file name="style.css">
  16883. .odd {
  16884. color: red;
  16885. }
  16886. .even {
  16887. color: blue;
  16888. }
  16889. </file>
  16890. <file name="protractor.js" type="protractor">
  16891. it('should check ng-class-odd and ng-class-even', function() {
  16892. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  16893. toMatch(/odd/);
  16894. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  16895. toMatch(/even/);
  16896. });
  16897. </file>
  16898. </example>
  16899. */
  16900. var ngClassEvenDirective = classDirective('Even', 1);
  16901. /**
  16902. * @ngdoc directive
  16903. * @name ngCloak
  16904. * @restrict AC
  16905. *
  16906. * @description
  16907. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  16908. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  16909. * directive to avoid the undesirable flicker effect caused by the html template display.
  16910. *
  16911. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  16912. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  16913. * of the browser view.
  16914. *
  16915. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  16916. * `angular.min.js`.
  16917. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  16918. *
  16919. * ```css
  16920. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  16921. * display: none !important;
  16922. * }
  16923. * ```
  16924. *
  16925. * When this css rule is loaded by the browser, all html elements (including their children) that
  16926. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  16927. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  16928. * the compiled element visible.
  16929. *
  16930. * For the best result, the `angular.js` script must be loaded in the head section of the html
  16931. * document; alternatively, the css rule above must be included in the external stylesheet of the
  16932. * application.
  16933. *
  16934. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  16935. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  16936. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  16937. *
  16938. * @element ANY
  16939. *
  16940. * @example
  16941. <example>
  16942. <file name="index.html">
  16943. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  16944. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  16945. </file>
  16946. <file name="protractor.js" type="protractor">
  16947. it('should remove the template directive and css class', function() {
  16948. expect($('#template1').getAttribute('ng-cloak')).
  16949. toBeNull();
  16950. expect($('#template2').getAttribute('ng-cloak')).
  16951. toBeNull();
  16952. });
  16953. </file>
  16954. </example>
  16955. *
  16956. */
  16957. var ngCloakDirective = ngDirective({
  16958. compile: function(element, attr) {
  16959. attr.$set('ngCloak', undefined);
  16960. element.removeClass('ng-cloak');
  16961. }
  16962. });
  16963. /**
  16964. * @ngdoc directive
  16965. * @name ngController
  16966. *
  16967. * @description
  16968. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  16969. * supports the principles behind the Model-View-Controller design pattern.
  16970. *
  16971. * MVC components in angular:
  16972. *
  16973. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  16974. * are accessed through bindings.
  16975. * * View — The template (HTML with data bindings) that is rendered into the View.
  16976. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  16977. * logic behind the application to decorate the scope with functions and values
  16978. *
  16979. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  16980. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  16981. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  16982. * and executed twice.
  16983. *
  16984. * @element ANY
  16985. * @scope
  16986. * @param {expression} ngController Name of a globally accessible constructor function or an
  16987. * {@link guide/expression expression} that on the current scope evaluates to a
  16988. * constructor function. The controller instance can be published into a scope property
  16989. * by specifying `as propertyName`.
  16990. *
  16991. * @example
  16992. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  16993. * greeting are methods declared on the controller (see source tab). These methods can
  16994. * easily be called from the angular markup. Any changes to the data are automatically reflected
  16995. * in the View without the need for a manual update.
  16996. *
  16997. * Two different declaration styles are included below:
  16998. *
  16999. * * one binds methods and properties directly onto the controller using `this`:
  17000. * `ng-controller="SettingsController1 as settings"`
  17001. * * one injects `$scope` into the controller:
  17002. * `ng-controller="SettingsController2"`
  17003. *
  17004. * The second option is more common in the Angular community, and is generally used in boilerplates
  17005. * and in this guide. However, there are advantages to binding properties directly to the controller
  17006. * and avoiding scope.
  17007. *
  17008. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  17009. * multiple controllers apply to an element.
  17010. * * If you are writing your controllers as classes you have easier access to the properties and
  17011. * methods, which will appear on the scope, from inside the controller code.
  17012. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  17013. * inheritance masking primitives.
  17014. *
  17015. * This example demonstrates the `controller as` syntax.
  17016. *
  17017. * <example name="ngControllerAs" module="controllerAsExample">
  17018. * <file name="index.html">
  17019. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  17020. * Name: <input type="text" ng-model="settings.name"/>
  17021. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  17022. * Contact:
  17023. * <ul>
  17024. * <li ng-repeat="contact in settings.contacts">
  17025. * <select ng-model="contact.type">
  17026. * <option>phone</option>
  17027. * <option>email</option>
  17028. * </select>
  17029. * <input type="text" ng-model="contact.value"/>
  17030. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  17031. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  17032. * </li>
  17033. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  17034. * </ul>
  17035. * </div>
  17036. * </file>
  17037. * <file name="app.js">
  17038. * angular.module('controllerAsExample', [])
  17039. * .controller('SettingsController1', SettingsController1);
  17040. *
  17041. * function SettingsController1() {
  17042. * this.name = "John Smith";
  17043. * this.contacts = [
  17044. * {type: 'phone', value: '408 555 1212'},
  17045. * {type: 'email', value: 'john.smith@example.org'} ];
  17046. * }
  17047. *
  17048. * SettingsController1.prototype.greet = function() {
  17049. * alert(this.name);
  17050. * };
  17051. *
  17052. * SettingsController1.prototype.addContact = function() {
  17053. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  17054. * };
  17055. *
  17056. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  17057. * var index = this.contacts.indexOf(contactToRemove);
  17058. * this.contacts.splice(index, 1);
  17059. * };
  17060. *
  17061. * SettingsController1.prototype.clearContact = function(contact) {
  17062. * contact.type = 'phone';
  17063. * contact.value = '';
  17064. * };
  17065. * </file>
  17066. * <file name="protractor.js" type="protractor">
  17067. * it('should check controller as', function() {
  17068. * var container = element(by.id('ctrl-as-exmpl'));
  17069. * expect(container.element(by.model('settings.name'))
  17070. * .getAttribute('value')).toBe('John Smith');
  17071. *
  17072. * var firstRepeat =
  17073. * container.element(by.repeater('contact in settings.contacts').row(0));
  17074. * var secondRepeat =
  17075. * container.element(by.repeater('contact in settings.contacts').row(1));
  17076. *
  17077. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17078. * .toBe('408 555 1212');
  17079. *
  17080. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  17081. * .toBe('john.smith@example.org');
  17082. *
  17083. * firstRepeat.element(by.linkText('clear')).click();
  17084. *
  17085. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17086. * .toBe('');
  17087. *
  17088. * container.element(by.linkText('add')).click();
  17089. *
  17090. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  17091. * .element(by.model('contact.value'))
  17092. * .getAttribute('value'))
  17093. * .toBe('yourname@example.org');
  17094. * });
  17095. * </file>
  17096. * </example>
  17097. *
  17098. * This example demonstrates the "attach to `$scope`" style of controller.
  17099. *
  17100. * <example name="ngController" module="controllerExample">
  17101. * <file name="index.html">
  17102. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  17103. * Name: <input type="text" ng-model="name"/>
  17104. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  17105. * Contact:
  17106. * <ul>
  17107. * <li ng-repeat="contact in contacts">
  17108. * <select ng-model="contact.type">
  17109. * <option>phone</option>
  17110. * <option>email</option>
  17111. * </select>
  17112. * <input type="text" ng-model="contact.value"/>
  17113. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  17114. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  17115. * </li>
  17116. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  17117. * </ul>
  17118. * </div>
  17119. * </file>
  17120. * <file name="app.js">
  17121. * angular.module('controllerExample', [])
  17122. * .controller('SettingsController2', ['$scope', SettingsController2]);
  17123. *
  17124. * function SettingsController2($scope) {
  17125. * $scope.name = "John Smith";
  17126. * $scope.contacts = [
  17127. * {type:'phone', value:'408 555 1212'},
  17128. * {type:'email', value:'john.smith@example.org'} ];
  17129. *
  17130. * $scope.greet = function() {
  17131. * alert($scope.name);
  17132. * };
  17133. *
  17134. * $scope.addContact = function() {
  17135. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  17136. * };
  17137. *
  17138. * $scope.removeContact = function(contactToRemove) {
  17139. * var index = $scope.contacts.indexOf(contactToRemove);
  17140. * $scope.contacts.splice(index, 1);
  17141. * };
  17142. *
  17143. * $scope.clearContact = function(contact) {
  17144. * contact.type = 'phone';
  17145. * contact.value = '';
  17146. * };
  17147. * }
  17148. * </file>
  17149. * <file name="protractor.js" type="protractor">
  17150. * it('should check controller', function() {
  17151. * var container = element(by.id('ctrl-exmpl'));
  17152. *
  17153. * expect(container.element(by.model('name'))
  17154. * .getAttribute('value')).toBe('John Smith');
  17155. *
  17156. * var firstRepeat =
  17157. * container.element(by.repeater('contact in contacts').row(0));
  17158. * var secondRepeat =
  17159. * container.element(by.repeater('contact in contacts').row(1));
  17160. *
  17161. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17162. * .toBe('408 555 1212');
  17163. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  17164. * .toBe('john.smith@example.org');
  17165. *
  17166. * firstRepeat.element(by.linkText('clear')).click();
  17167. *
  17168. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  17169. * .toBe('');
  17170. *
  17171. * container.element(by.linkText('add')).click();
  17172. *
  17173. * expect(container.element(by.repeater('contact in contacts').row(2))
  17174. * .element(by.model('contact.value'))
  17175. * .getAttribute('value'))
  17176. * .toBe('yourname@example.org');
  17177. * });
  17178. * </file>
  17179. *</example>
  17180. */
  17181. var ngControllerDirective = [function() {
  17182. return {
  17183. scope: true,
  17184. controller: '@',
  17185. priority: 500
  17186. };
  17187. }];
  17188. /**
  17189. * @ngdoc directive
  17190. * @name ngCsp
  17191. *
  17192. * @element html
  17193. * @description
  17194. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  17195. *
  17196. * This is necessary when developing things like Google Chrome Extensions.
  17197. *
  17198. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  17199. * For Angular to be CSP compatible there are only two things that we need to do differently:
  17200. *
  17201. * - don't use `Function` constructor to generate optimized value getters
  17202. * - don't inject custom stylesheet into the document
  17203. *
  17204. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  17205. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  17206. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  17207. * be raised.
  17208. *
  17209. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  17210. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  17211. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  17212. *
  17213. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  17214. * autodetection however triggers a CSP error to be logged in the console:
  17215. *
  17216. * ```
  17217. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  17218. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  17219. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  17220. * ```
  17221. *
  17222. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  17223. * directive on the root element of the application or on the `angular.js` script tag, whichever
  17224. * appears first in the html document.
  17225. *
  17226. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  17227. *
  17228. * @example
  17229. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  17230. ```html
  17231. <!doctype html>
  17232. <html ng-app ng-csp>
  17233. ...
  17234. ...
  17235. </html>
  17236. ```
  17237. */
  17238. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  17239. // bootstrap the system (before $parse is instantiated), for this reason we just have
  17240. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  17241. /**
  17242. * @ngdoc directive
  17243. * @name ngClick
  17244. *
  17245. * @description
  17246. * The ngClick directive allows you to specify custom behavior when
  17247. * an element is clicked.
  17248. *
  17249. * @element ANY
  17250. * @priority 0
  17251. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  17252. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  17253. *
  17254. * @example
  17255. <example>
  17256. <file name="index.html">
  17257. <button ng-click="count = count + 1" ng-init="count=0">
  17258. Increment
  17259. </button>
  17260. count: {{count}}
  17261. </file>
  17262. <file name="protractor.js" type="protractor">
  17263. it('should check ng-click', function() {
  17264. expect(element(by.binding('count')).getText()).toMatch('0');
  17265. element(by.css('button')).click();
  17266. expect(element(by.binding('count')).getText()).toMatch('1');
  17267. });
  17268. </file>
  17269. </example>
  17270. */
  17271. /*
  17272. * A directive that allows creation of custom onclick handlers that are defined as angular
  17273. * expressions and are compiled and executed within the current scope.
  17274. *
  17275. * Events that are handled via these handler are always configured not to propagate further.
  17276. */
  17277. var ngEventDirectives = {};
  17278. forEach(
  17279. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  17280. function(name) {
  17281. var directiveName = directiveNormalize('ng-' + name);
  17282. ngEventDirectives[directiveName] = ['$parse', function($parse) {
  17283. return {
  17284. compile: function($element, attr) {
  17285. var fn = $parse(attr[directiveName]);
  17286. return function ngEventHandler(scope, element) {
  17287. element.on(lowercase(name), function(event) {
  17288. scope.$apply(function() {
  17289. fn(scope, {$event:event});
  17290. });
  17291. });
  17292. };
  17293. }
  17294. };
  17295. }];
  17296. }
  17297. );
  17298. /**
  17299. * @ngdoc directive
  17300. * @name ngDblclick
  17301. *
  17302. * @description
  17303. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  17304. *
  17305. * @element ANY
  17306. * @priority 0
  17307. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  17308. * a dblclick. (The Event object is available as `$event`)
  17309. *
  17310. * @example
  17311. <example>
  17312. <file name="index.html">
  17313. <button ng-dblclick="count = count + 1" ng-init="count=0">
  17314. Increment (on double click)
  17315. </button>
  17316. count: {{count}}
  17317. </file>
  17318. </example>
  17319. */
  17320. /**
  17321. * @ngdoc directive
  17322. * @name ngMousedown
  17323. *
  17324. * @description
  17325. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  17326. *
  17327. * @element ANY
  17328. * @priority 0
  17329. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  17330. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  17331. *
  17332. * @example
  17333. <example>
  17334. <file name="index.html">
  17335. <button ng-mousedown="count = count + 1" ng-init="count=0">
  17336. Increment (on mouse down)
  17337. </button>
  17338. count: {{count}}
  17339. </file>
  17340. </example>
  17341. */
  17342. /**
  17343. * @ngdoc directive
  17344. * @name ngMouseup
  17345. *
  17346. * @description
  17347. * Specify custom behavior on mouseup event.
  17348. *
  17349. * @element ANY
  17350. * @priority 0
  17351. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  17352. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  17353. *
  17354. * @example
  17355. <example>
  17356. <file name="index.html">
  17357. <button ng-mouseup="count = count + 1" ng-init="count=0">
  17358. Increment (on mouse up)
  17359. </button>
  17360. count: {{count}}
  17361. </file>
  17362. </example>
  17363. */
  17364. /**
  17365. * @ngdoc directive
  17366. * @name ngMouseover
  17367. *
  17368. * @description
  17369. * Specify custom behavior on mouseover event.
  17370. *
  17371. * @element ANY
  17372. * @priority 0
  17373. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  17374. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  17375. *
  17376. * @example
  17377. <example>
  17378. <file name="index.html">
  17379. <button ng-mouseover="count = count + 1" ng-init="count=0">
  17380. Increment (when mouse is over)
  17381. </button>
  17382. count: {{count}}
  17383. </file>
  17384. </example>
  17385. */
  17386. /**
  17387. * @ngdoc directive
  17388. * @name ngMouseenter
  17389. *
  17390. * @description
  17391. * Specify custom behavior on mouseenter event.
  17392. *
  17393. * @element ANY
  17394. * @priority 0
  17395. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  17396. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  17397. *
  17398. * @example
  17399. <example>
  17400. <file name="index.html">
  17401. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  17402. Increment (when mouse enters)
  17403. </button>
  17404. count: {{count}}
  17405. </file>
  17406. </example>
  17407. */
  17408. /**
  17409. * @ngdoc directive
  17410. * @name ngMouseleave
  17411. *
  17412. * @description
  17413. * Specify custom behavior on mouseleave event.
  17414. *
  17415. * @element ANY
  17416. * @priority 0
  17417. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  17418. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  17419. *
  17420. * @example
  17421. <example>
  17422. <file name="index.html">
  17423. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  17424. Increment (when mouse leaves)
  17425. </button>
  17426. count: {{count}}
  17427. </file>
  17428. </example>
  17429. */
  17430. /**
  17431. * @ngdoc directive
  17432. * @name ngMousemove
  17433. *
  17434. * @description
  17435. * Specify custom behavior on mousemove event.
  17436. *
  17437. * @element ANY
  17438. * @priority 0
  17439. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  17440. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  17441. *
  17442. * @example
  17443. <example>
  17444. <file name="index.html">
  17445. <button ng-mousemove="count = count + 1" ng-init="count=0">
  17446. Increment (when mouse moves)
  17447. </button>
  17448. count: {{count}}
  17449. </file>
  17450. </example>
  17451. */
  17452. /**
  17453. * @ngdoc directive
  17454. * @name ngKeydown
  17455. *
  17456. * @description
  17457. * Specify custom behavior on keydown event.
  17458. *
  17459. * @element ANY
  17460. * @priority 0
  17461. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  17462. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17463. *
  17464. * @example
  17465. <example>
  17466. <file name="index.html">
  17467. <input ng-keydown="count = count + 1" ng-init="count=0">
  17468. key down count: {{count}}
  17469. </file>
  17470. </example>
  17471. */
  17472. /**
  17473. * @ngdoc directive
  17474. * @name ngKeyup
  17475. *
  17476. * @description
  17477. * Specify custom behavior on keyup event.
  17478. *
  17479. * @element ANY
  17480. * @priority 0
  17481. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  17482. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  17483. *
  17484. * @example
  17485. <example>
  17486. <file name="index.html">
  17487. <p>Typing in the input box below updates the key count</p>
  17488. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  17489. <p>Typing in the input box below updates the keycode</p>
  17490. <input ng-keyup="event=$event">
  17491. <p>event keyCode: {{ event.keyCode }}</p>
  17492. <p>event altKey: {{ event.altKey }}</p>
  17493. </file>
  17494. </example>
  17495. */
  17496. /**
  17497. * @ngdoc directive
  17498. * @name ngKeypress
  17499. *
  17500. * @description
  17501. * Specify custom behavior on keypress event.
  17502. *
  17503. * @element ANY
  17504. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  17505. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  17506. * and can be interrogated for keyCode, altKey, etc.)
  17507. *
  17508. * @example
  17509. <example>
  17510. <file name="index.html">
  17511. <input ng-keypress="count = count + 1" ng-init="count=0">
  17512. key press count: {{count}}
  17513. </file>
  17514. </example>
  17515. */
  17516. /**
  17517. * @ngdoc directive
  17518. * @name ngSubmit
  17519. *
  17520. * @description
  17521. * Enables binding angular expressions to onsubmit events.
  17522. *
  17523. * Additionally it prevents the default action (which for form means sending the request to the
  17524. * server and reloading the current page), but only if the form does not contain `action`,
  17525. * `data-action`, or `x-action` attributes.
  17526. *
  17527. * @element form
  17528. * @priority 0
  17529. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  17530. * ({@link guide/expression#-event- Event object is available as `$event`})
  17531. *
  17532. * @example
  17533. <example module="submitExample">
  17534. <file name="index.html">
  17535. <script>
  17536. angular.module('submitExample', [])
  17537. .controller('ExampleController', ['$scope', function($scope) {
  17538. $scope.list = [];
  17539. $scope.text = 'hello';
  17540. $scope.submit = function() {
  17541. if ($scope.text) {
  17542. $scope.list.push(this.text);
  17543. $scope.text = '';
  17544. }
  17545. };
  17546. }]);
  17547. </script>
  17548. <form ng-submit="submit()" ng-controller="ExampleController">
  17549. Enter text and hit enter:
  17550. <input type="text" ng-model="text" name="text" />
  17551. <input type="submit" id="submit" value="Submit" />
  17552. <pre>list={{list}}</pre>
  17553. </form>
  17554. </file>
  17555. <file name="protractor.js" type="protractor">
  17556. it('should check ng-submit', function() {
  17557. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17558. element(by.css('#submit')).click();
  17559. expect(element(by.binding('list')).getText()).toContain('hello');
  17560. expect(element(by.model('text')).getAttribute('value')).toBe('');
  17561. });
  17562. it('should ignore empty strings', function() {
  17563. expect(element(by.binding('list')).getText()).toBe('list=[]');
  17564. element(by.css('#submit')).click();
  17565. element(by.css('#submit')).click();
  17566. expect(element(by.binding('list')).getText()).toContain('hello');
  17567. });
  17568. </file>
  17569. </example>
  17570. */
  17571. /**
  17572. * @ngdoc directive
  17573. * @name ngFocus
  17574. *
  17575. * @description
  17576. * Specify custom behavior on focus event.
  17577. *
  17578. * @element window, input, select, textarea, a
  17579. * @priority 0
  17580. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  17581. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  17582. *
  17583. * @example
  17584. * See {@link ng.directive:ngClick ngClick}
  17585. */
  17586. /**
  17587. * @ngdoc directive
  17588. * @name ngBlur
  17589. *
  17590. * @description
  17591. * Specify custom behavior on blur event.
  17592. *
  17593. * @element window, input, select, textarea, a
  17594. * @priority 0
  17595. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  17596. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  17597. *
  17598. * @example
  17599. * See {@link ng.directive:ngClick ngClick}
  17600. */
  17601. /**
  17602. * @ngdoc directive
  17603. * @name ngCopy
  17604. *
  17605. * @description
  17606. * Specify custom behavior on copy event.
  17607. *
  17608. * @element window, input, select, textarea, a
  17609. * @priority 0
  17610. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  17611. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  17612. *
  17613. * @example
  17614. <example>
  17615. <file name="index.html">
  17616. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  17617. copied: {{copied}}
  17618. </file>
  17619. </example>
  17620. */
  17621. /**
  17622. * @ngdoc directive
  17623. * @name ngCut
  17624. *
  17625. * @description
  17626. * Specify custom behavior on cut event.
  17627. *
  17628. * @element window, input, select, textarea, a
  17629. * @priority 0
  17630. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  17631. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  17632. *
  17633. * @example
  17634. <example>
  17635. <file name="index.html">
  17636. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  17637. cut: {{cut}}
  17638. </file>
  17639. </example>
  17640. */
  17641. /**
  17642. * @ngdoc directive
  17643. * @name ngPaste
  17644. *
  17645. * @description
  17646. * Specify custom behavior on paste event.
  17647. *
  17648. * @element window, input, select, textarea, a
  17649. * @priority 0
  17650. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  17651. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  17652. *
  17653. * @example
  17654. <example>
  17655. <file name="index.html">
  17656. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  17657. pasted: {{paste}}
  17658. </file>
  17659. </example>
  17660. */
  17661. /**
  17662. * @ngdoc directive
  17663. * @name ngIf
  17664. * @restrict A
  17665. *
  17666. * @description
  17667. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  17668. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  17669. * value then the element is removed from the DOM, otherwise a clone of the
  17670. * element is reinserted into the DOM.
  17671. *
  17672. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  17673. * element in the DOM rather than changing its visibility via the `display` css property. A common
  17674. * case when this difference is significant is when using css selectors that rely on an element's
  17675. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  17676. *
  17677. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  17678. * is created when the element is restored. The scope created within `ngIf` inherits from
  17679. * its parent scope using
  17680. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance).
  17681. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  17682. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  17683. * variable within the child scope will override (hide) the value in the parent scope.
  17684. *
  17685. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  17686. * is if an element's class attribute is directly modified after it's compiled, using something like
  17687. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  17688. * the added class will be lost because the original compiled state is used to regenerate the element.
  17689. *
  17690. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  17691. * and `leave` effects.
  17692. *
  17693. * @animations
  17694. * enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
  17695. * leave - happens just before the ngIf contents are removed from the DOM
  17696. *
  17697. * @element ANY
  17698. * @scope
  17699. * @priority 600
  17700. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  17701. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  17702. * element is added to the DOM tree.
  17703. *
  17704. * @example
  17705. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  17706. <file name="index.html">
  17707. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  17708. Show when checked:
  17709. <span ng-if="checked" class="animate-if">
  17710. I'm removed when the checkbox is unchecked.
  17711. </span>
  17712. </file>
  17713. <file name="animations.css">
  17714. .animate-if {
  17715. background:white;
  17716. border:1px solid black;
  17717. padding:10px;
  17718. }
  17719. .animate-if.ng-enter, .animate-if.ng-leave {
  17720. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17721. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17722. }
  17723. .animate-if.ng-enter,
  17724. .animate-if.ng-leave.ng-leave-active {
  17725. opacity:0;
  17726. }
  17727. .animate-if.ng-leave,
  17728. .animate-if.ng-enter.ng-enter-active {
  17729. opacity:1;
  17730. }
  17731. </file>
  17732. </example>
  17733. */
  17734. var ngIfDirective = ['$animate', function($animate) {
  17735. return {
  17736. transclude: 'element',
  17737. priority: 600,
  17738. terminal: true,
  17739. restrict: 'A',
  17740. $$tlb: true,
  17741. link: function ($scope, $element, $attr, ctrl, $transclude) {
  17742. var block, childScope, previousElements;
  17743. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  17744. if (toBoolean(value)) {
  17745. if (!childScope) {
  17746. childScope = $scope.$new();
  17747. $transclude(childScope, function (clone) {
  17748. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  17749. // Note: We only need the first/last node of the cloned nodes.
  17750. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  17751. // by a directive with templateUrl when its template arrives.
  17752. block = {
  17753. clone: clone
  17754. };
  17755. $animate.enter(clone, $element.parent(), $element);
  17756. });
  17757. }
  17758. } else {
  17759. if(previousElements) {
  17760. previousElements.remove();
  17761. previousElements = null;
  17762. }
  17763. if(childScope) {
  17764. childScope.$destroy();
  17765. childScope = null;
  17766. }
  17767. if(block) {
  17768. previousElements = getBlockElements(block.clone);
  17769. $animate.leave(previousElements, function() {
  17770. previousElements = null;
  17771. });
  17772. block = null;
  17773. }
  17774. }
  17775. });
  17776. }
  17777. };
  17778. }];
  17779. /**
  17780. * @ngdoc directive
  17781. * @name ngInclude
  17782. * @restrict ECA
  17783. *
  17784. * @description
  17785. * Fetches, compiles and includes an external HTML fragment.
  17786. *
  17787. * By default, the template URL is restricted to the same domain and protocol as the
  17788. * application document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  17789. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  17790. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  17791. * [wrap them](ng.$sce#trustAsResourceUrl) as trusted values. Refer to Angular's {@link
  17792. * ng.$sce Strict Contextual Escaping}.
  17793. *
  17794. * In addition, the browser's
  17795. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  17796. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  17797. * policy may further restrict whether the template is successfully loaded.
  17798. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  17799. * access on some browsers.
  17800. *
  17801. * @animations
  17802. * enter - animation is used to bring new content into the browser.
  17803. * leave - animation is used to animate existing content away.
  17804. *
  17805. * The enter and leave animation occur concurrently.
  17806. *
  17807. * @scope
  17808. * @priority 400
  17809. *
  17810. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  17811. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  17812. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  17813. *
  17814. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  17815. * $anchorScroll} to scroll the viewport after the content is loaded.
  17816. *
  17817. * - If the attribute is not set, disable scrolling.
  17818. * - If the attribute is set without value, enable scrolling.
  17819. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  17820. *
  17821. * @example
  17822. <example module="includeExample" deps="angular-animate.js" animations="true">
  17823. <file name="index.html">
  17824. <div ng-controller="ExampleController">
  17825. <select ng-model="template" ng-options="t.name for t in templates">
  17826. <option value="">(blank)</option>
  17827. </select>
  17828. url of the template: <tt>{{template.url}}</tt>
  17829. <hr/>
  17830. <div class="slide-animate-container">
  17831. <div class="slide-animate" ng-include="template.url"></div>
  17832. </div>
  17833. </div>
  17834. </file>
  17835. <file name="script.js">
  17836. angular.module('includeExample', ['ngAnimate'])
  17837. .controller('ExampleController', ['$scope', function($scope) {
  17838. $scope.templates =
  17839. [ { name: 'template1.html', url: 'template1.html'},
  17840. { name: 'template2.html', url: 'template2.html'} ];
  17841. $scope.template = $scope.templates[0];
  17842. }]);
  17843. </file>
  17844. <file name="template1.html">
  17845. Content of template1.html
  17846. </file>
  17847. <file name="template2.html">
  17848. Content of template2.html
  17849. </file>
  17850. <file name="animations.css">
  17851. .slide-animate-container {
  17852. position:relative;
  17853. background:white;
  17854. border:1px solid black;
  17855. height:40px;
  17856. overflow:hidden;
  17857. }
  17858. .slide-animate {
  17859. padding:10px;
  17860. }
  17861. .slide-animate.ng-enter, .slide-animate.ng-leave {
  17862. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17863. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  17864. position:absolute;
  17865. top:0;
  17866. left:0;
  17867. right:0;
  17868. bottom:0;
  17869. display:block;
  17870. padding:10px;
  17871. }
  17872. .slide-animate.ng-enter {
  17873. top:-50px;
  17874. }
  17875. .slide-animate.ng-enter.ng-enter-active {
  17876. top:0;
  17877. }
  17878. .slide-animate.ng-leave {
  17879. top:0;
  17880. }
  17881. .slide-animate.ng-leave.ng-leave-active {
  17882. top:50px;
  17883. }
  17884. </file>
  17885. <file name="protractor.js" type="protractor">
  17886. var templateSelect = element(by.model('template'));
  17887. var includeElem = element(by.css('[ng-include]'));
  17888. it('should load template1.html', function() {
  17889. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  17890. });
  17891. it('should load template2.html', function() {
  17892. if (browser.params.browser == 'firefox') {
  17893. // Firefox can't handle using selects
  17894. // See https://github.com/angular/protractor/issues/480
  17895. return;
  17896. }
  17897. templateSelect.click();
  17898. templateSelect.all(by.css('option')).get(2).click();
  17899. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  17900. });
  17901. it('should change to blank', function() {
  17902. if (browser.params.browser == 'firefox') {
  17903. // Firefox can't handle using selects
  17904. return;
  17905. }
  17906. templateSelect.click();
  17907. templateSelect.all(by.css('option')).get(0).click();
  17908. expect(includeElem.isPresent()).toBe(false);
  17909. });
  17910. </file>
  17911. </example>
  17912. */
  17913. /**
  17914. * @ngdoc event
  17915. * @name ngInclude#$includeContentRequested
  17916. * @eventType emit on the scope ngInclude was declared in
  17917. * @description
  17918. * Emitted every time the ngInclude content is requested.
  17919. */
  17920. /**
  17921. * @ngdoc event
  17922. * @name ngInclude#$includeContentLoaded
  17923. * @eventType emit on the current ngInclude scope
  17924. * @description
  17925. * Emitted every time the ngInclude content is reloaded.
  17926. */
  17927. var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$animate', '$sce',
  17928. function($http, $templateCache, $anchorScroll, $animate, $sce) {
  17929. return {
  17930. restrict: 'ECA',
  17931. priority: 400,
  17932. terminal: true,
  17933. transclude: 'element',
  17934. controller: angular.noop,
  17935. compile: function(element, attr) {
  17936. var srcExp = attr.ngInclude || attr.src,
  17937. onloadExp = attr.onload || '',
  17938. autoScrollExp = attr.autoscroll;
  17939. return function(scope, $element, $attr, ctrl, $transclude) {
  17940. var changeCounter = 0,
  17941. currentScope,
  17942. previousElement,
  17943. currentElement;
  17944. var cleanupLastIncludeContent = function() {
  17945. if(previousElement) {
  17946. previousElement.remove();
  17947. previousElement = null;
  17948. }
  17949. if(currentScope) {
  17950. currentScope.$destroy();
  17951. currentScope = null;
  17952. }
  17953. if(currentElement) {
  17954. $animate.leave(currentElement, function() {
  17955. previousElement = null;
  17956. });
  17957. previousElement = currentElement;
  17958. currentElement = null;
  17959. }
  17960. };
  17961. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  17962. var afterAnimation = function() {
  17963. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  17964. $anchorScroll();
  17965. }
  17966. };
  17967. var thisChangeId = ++changeCounter;
  17968. if (src) {
  17969. $http.get(src, {cache: $templateCache}).success(function(response) {
  17970. if (thisChangeId !== changeCounter) return;
  17971. var newScope = scope.$new();
  17972. ctrl.template = response;
  17973. // Note: This will also link all children of ng-include that were contained in the original
  17974. // html. If that content contains controllers, ... they could pollute/change the scope.
  17975. // However, using ng-include on an element with additional content does not make sense...
  17976. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  17977. // function is called before linking the content, which would apply child
  17978. // directives to non existing elements.
  17979. var clone = $transclude(newScope, function(clone) {
  17980. cleanupLastIncludeContent();
  17981. $animate.enter(clone, null, $element, afterAnimation);
  17982. });
  17983. currentScope = newScope;
  17984. currentElement = clone;
  17985. currentScope.$emit('$includeContentLoaded');
  17986. scope.$eval(onloadExp);
  17987. }).error(function() {
  17988. if (thisChangeId === changeCounter) cleanupLastIncludeContent();
  17989. });
  17990. scope.$emit('$includeContentRequested');
  17991. } else {
  17992. cleanupLastIncludeContent();
  17993. ctrl.template = null;
  17994. }
  17995. });
  17996. };
  17997. }
  17998. };
  17999. }];
  18000. // This directive is called during the $transclude call of the first `ngInclude` directive.
  18001. // It will replace and compile the content of the element with the loaded template.
  18002. // We need this directive so that the element content is already filled when
  18003. // the link function of another directive on the same element as ngInclude
  18004. // is called.
  18005. var ngIncludeFillContentDirective = ['$compile',
  18006. function($compile) {
  18007. return {
  18008. restrict: 'ECA',
  18009. priority: -400,
  18010. require: 'ngInclude',
  18011. link: function(scope, $element, $attr, ctrl) {
  18012. $element.html(ctrl.template);
  18013. $compile($element.contents())(scope);
  18014. }
  18015. };
  18016. }];
  18017. /**
  18018. * @ngdoc directive
  18019. * @name ngInit
  18020. * @restrict AC
  18021. *
  18022. * @description
  18023. * The `ngInit` directive allows you to evaluate an expression in the
  18024. * current scope.
  18025. *
  18026. * <div class="alert alert-error">
  18027. * The only appropriate use of `ngInit` is for aliasing special properties of
  18028. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  18029. * should use {@link guide/controller controllers} rather than `ngInit`
  18030. * to initialize values on a scope.
  18031. * </div>
  18032. * <div class="alert alert-warning">
  18033. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  18034. * sure you have parenthesis for correct precedence:
  18035. * <pre class="prettyprint">
  18036. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  18037. * </pre>
  18038. * </div>
  18039. *
  18040. * @priority 450
  18041. *
  18042. * @element ANY
  18043. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  18044. *
  18045. * @example
  18046. <example module="initExample">
  18047. <file name="index.html">
  18048. <script>
  18049. angular.module('initExample', [])
  18050. .controller('ExampleController', ['$scope', function($scope) {
  18051. $scope.list = [['a', 'b'], ['c', 'd']];
  18052. }]);
  18053. </script>
  18054. <div ng-controller="ExampleController">
  18055. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  18056. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  18057. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  18058. </div>
  18059. </div>
  18060. </div>
  18061. </file>
  18062. <file name="protractor.js" type="protractor">
  18063. it('should alias index positions', function() {
  18064. var elements = element.all(by.css('.example-init'));
  18065. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  18066. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  18067. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  18068. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  18069. });
  18070. </file>
  18071. </example>
  18072. */
  18073. var ngInitDirective = ngDirective({
  18074. priority: 450,
  18075. compile: function() {
  18076. return {
  18077. pre: function(scope, element, attrs) {
  18078. scope.$eval(attrs.ngInit);
  18079. }
  18080. };
  18081. }
  18082. });
  18083. /**
  18084. * @ngdoc directive
  18085. * @name ngNonBindable
  18086. * @restrict AC
  18087. * @priority 1000
  18088. *
  18089. * @description
  18090. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  18091. * DOM element. This is useful if the element contains what appears to be Angular directives and
  18092. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  18093. * displays snippets of code, for instance.
  18094. *
  18095. * @element ANY
  18096. *
  18097. * @example
  18098. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  18099. * but the one wrapped in `ngNonBindable` is left alone.
  18100. *
  18101. * @example
  18102. <example>
  18103. <file name="index.html">
  18104. <div>Normal: {{1 + 2}}</div>
  18105. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  18106. </file>
  18107. <file name="protractor.js" type="protractor">
  18108. it('should check ng-non-bindable', function() {
  18109. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  18110. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  18111. });
  18112. </file>
  18113. </example>
  18114. */
  18115. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  18116. /**
  18117. * @ngdoc directive
  18118. * @name ngPluralize
  18119. * @restrict EA
  18120. *
  18121. * @description
  18122. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  18123. * These rules are bundled with angular.js, but can be overridden
  18124. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  18125. * by specifying the mappings between
  18126. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  18127. * and the strings to be displayed.
  18128. *
  18129. * # Plural categories and explicit number rules
  18130. * There are two
  18131. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  18132. * in Angular's default en-US locale: "one" and "other".
  18133. *
  18134. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  18135. * any number that is not 1), an explicit number rule can only match one number. For example, the
  18136. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  18137. * and explicit number rules throughout the rest of this documentation.
  18138. *
  18139. * # Configuring ngPluralize
  18140. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  18141. * You can also provide an optional attribute, `offset`.
  18142. *
  18143. * The value of the `count` attribute can be either a string or an {@link guide/expression
  18144. * Angular expression}; these are evaluated on the current scope for its bound value.
  18145. *
  18146. * The `when` attribute specifies the mappings between plural categories and the actual
  18147. * string to be displayed. The value of the attribute should be a JSON object.
  18148. *
  18149. * The following example shows how to configure ngPluralize:
  18150. *
  18151. * ```html
  18152. * <ng-pluralize count="personCount"
  18153. when="{'0': 'Nobody is viewing.',
  18154. * 'one': '1 person is viewing.',
  18155. * 'other': '{} people are viewing.'}">
  18156. * </ng-pluralize>
  18157. *```
  18158. *
  18159. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  18160. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  18161. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  18162. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  18163. * show "a dozen people are viewing".
  18164. *
  18165. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  18166. * into pluralized strings. In the previous example, Angular will replace `{}` with
  18167. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  18168. * for <span ng-non-bindable>{{numberExpression}}</span>.
  18169. *
  18170. * # Configuring ngPluralize with offset
  18171. * The `offset` attribute allows further customization of pluralized text, which can result in
  18172. * a better user experience. For example, instead of the message "4 people are viewing this document",
  18173. * you might display "John, Kate and 2 others are viewing this document".
  18174. * The offset attribute allows you to offset a number by any desired value.
  18175. * Let's take a look at an example:
  18176. *
  18177. * ```html
  18178. * <ng-pluralize count="personCount" offset=2
  18179. * when="{'0': 'Nobody is viewing.',
  18180. * '1': '{{person1}} is viewing.',
  18181. * '2': '{{person1}} and {{person2}} are viewing.',
  18182. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18183. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18184. * </ng-pluralize>
  18185. * ```
  18186. *
  18187. * Notice that we are still using two plural categories(one, other), but we added
  18188. * three explicit number rules 0, 1 and 2.
  18189. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  18190. * When three people view the document, no explicit number rule is found, so
  18191. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  18192. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  18193. * is shown.
  18194. *
  18195. * Note that when you specify offsets, you must provide explicit number rules for
  18196. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  18197. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  18198. * plural categories "one" and "other".
  18199. *
  18200. * @param {string|expression} count The variable to be bound to.
  18201. * @param {string} when The mapping between plural category to its corresponding strings.
  18202. * @param {number=} offset Offset to deduct from the total number.
  18203. *
  18204. * @example
  18205. <example module="pluralizeExample">
  18206. <file name="index.html">
  18207. <script>
  18208. angular.module('pluralizeExample', [])
  18209. .controller('ExampleController', ['$scope', function($scope) {
  18210. $scope.person1 = 'Igor';
  18211. $scope.person2 = 'Misko';
  18212. $scope.personCount = 1;
  18213. }]);
  18214. </script>
  18215. <div ng-controller="ExampleController">
  18216. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  18217. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  18218. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  18219. <!--- Example with simple pluralization rules for en locale --->
  18220. Without Offset:
  18221. <ng-pluralize count="personCount"
  18222. when="{'0': 'Nobody is viewing.',
  18223. 'one': '1 person is viewing.',
  18224. 'other': '{} people are viewing.'}">
  18225. </ng-pluralize><br>
  18226. <!--- Example with offset --->
  18227. With Offset(2):
  18228. <ng-pluralize count="personCount" offset=2
  18229. when="{'0': 'Nobody is viewing.',
  18230. '1': '{{person1}} is viewing.',
  18231. '2': '{{person1}} and {{person2}} are viewing.',
  18232. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  18233. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  18234. </ng-pluralize>
  18235. </div>
  18236. </file>
  18237. <file name="protractor.js" type="protractor">
  18238. it('should show correct pluralized string', function() {
  18239. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  18240. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18241. var countInput = element(by.model('personCount'));
  18242. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  18243. expect(withOffset.getText()).toEqual('Igor is viewing.');
  18244. countInput.clear();
  18245. countInput.sendKeys('0');
  18246. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  18247. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  18248. countInput.clear();
  18249. countInput.sendKeys('2');
  18250. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  18251. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  18252. countInput.clear();
  18253. countInput.sendKeys('3');
  18254. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  18255. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  18256. countInput.clear();
  18257. countInput.sendKeys('4');
  18258. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  18259. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  18260. });
  18261. it('should show data-bound names', function() {
  18262. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  18263. var personCount = element(by.model('personCount'));
  18264. var person1 = element(by.model('person1'));
  18265. var person2 = element(by.model('person2'));
  18266. personCount.clear();
  18267. personCount.sendKeys('4');
  18268. person1.clear();
  18269. person1.sendKeys('Di');
  18270. person2.clear();
  18271. person2.sendKeys('Vojta');
  18272. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  18273. });
  18274. </file>
  18275. </example>
  18276. */
  18277. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  18278. var BRACE = /{}/g;
  18279. return {
  18280. restrict: 'EA',
  18281. link: function(scope, element, attr) {
  18282. var numberExp = attr.count,
  18283. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  18284. offset = attr.offset || 0,
  18285. whens = scope.$eval(whenExp) || {},
  18286. whensExpFns = {},
  18287. startSymbol = $interpolate.startSymbol(),
  18288. endSymbol = $interpolate.endSymbol(),
  18289. isWhen = /^when(Minus)?(.+)$/;
  18290. forEach(attr, function(expression, attributeName) {
  18291. if (isWhen.test(attributeName)) {
  18292. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  18293. element.attr(attr.$attr[attributeName]);
  18294. }
  18295. });
  18296. forEach(whens, function(expression, key) {
  18297. whensExpFns[key] =
  18298. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  18299. offset + endSymbol));
  18300. });
  18301. scope.$watch(function ngPluralizeWatch() {
  18302. var value = parseFloat(scope.$eval(numberExp));
  18303. if (!isNaN(value)) {
  18304. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  18305. //check it against pluralization rules in $locale service
  18306. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  18307. return whensExpFns[value](scope, element, true);
  18308. } else {
  18309. return '';
  18310. }
  18311. }, function ngPluralizeWatchAction(newVal) {
  18312. element.text(newVal);
  18313. });
  18314. }
  18315. };
  18316. }];
  18317. /**
  18318. * @ngdoc directive
  18319. * @name ngRepeat
  18320. *
  18321. * @description
  18322. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  18323. * instance gets its own scope, where the given loop variable is set to the current collection item,
  18324. * and `$index` is set to the item index or key.
  18325. *
  18326. * Special properties are exposed on the local scope of each template instance, including:
  18327. *
  18328. * | Variable | Type | Details |
  18329. * |-----------|-----------------|-----------------------------------------------------------------------------|
  18330. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  18331. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  18332. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  18333. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  18334. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  18335. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  18336. *
  18337. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  18338. * This may be useful when, for instance, nesting ngRepeats.
  18339. *
  18340. * # Special repeat start and end points
  18341. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  18342. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  18343. * 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)
  18344. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  18345. *
  18346. * The example below makes use of this feature:
  18347. * ```html
  18348. * <header ng-repeat-start="item in items">
  18349. * Header {{ item }}
  18350. * </header>
  18351. * <div class="body">
  18352. * Body {{ item }}
  18353. * </div>
  18354. * <footer ng-repeat-end>
  18355. * Footer {{ item }}
  18356. * </footer>
  18357. * ```
  18358. *
  18359. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  18360. * ```html
  18361. * <header>
  18362. * Header A
  18363. * </header>
  18364. * <div class="body">
  18365. * Body A
  18366. * </div>
  18367. * <footer>
  18368. * Footer A
  18369. * </footer>
  18370. * <header>
  18371. * Header B
  18372. * </header>
  18373. * <div class="body">
  18374. * Body B
  18375. * </div>
  18376. * <footer>
  18377. * Footer B
  18378. * </footer>
  18379. * ```
  18380. *
  18381. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  18382. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  18383. *
  18384. * @animations
  18385. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  18386. *
  18387. * **.leave** - when an item is removed from the list or when an item is filtered out
  18388. *
  18389. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  18390. *
  18391. * @element ANY
  18392. * @scope
  18393. * @priority 1000
  18394. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  18395. * formats are currently supported:
  18396. *
  18397. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  18398. * is a scope expression giving the collection to enumerate.
  18399. *
  18400. * For example: `album in artist.albums`.
  18401. *
  18402. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  18403. * and `expression` is the scope expression giving the collection to enumerate.
  18404. *
  18405. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  18406. *
  18407. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  18408. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  18409. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  18410. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  18411. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  18412. * before specifying a tracking expression.
  18413. *
  18414. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  18415. * will be associated by item identity in the array.
  18416. *
  18417. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  18418. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  18419. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  18420. * element in the same way in the DOM.
  18421. *
  18422. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  18423. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  18424. * property is same.
  18425. *
  18426. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  18427. * to items in conjunction with a tracking expression.
  18428. *
  18429. * @example
  18430. * This example initializes the scope to a list of names and
  18431. * then uses `ngRepeat` to display every person:
  18432. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18433. <file name="index.html">
  18434. <div ng-init="friends = [
  18435. {name:'John', age:25, gender:'boy'},
  18436. {name:'Jessie', age:30, gender:'girl'},
  18437. {name:'Johanna', age:28, gender:'girl'},
  18438. {name:'Joy', age:15, gender:'girl'},
  18439. {name:'Mary', age:28, gender:'girl'},
  18440. {name:'Peter', age:95, gender:'boy'},
  18441. {name:'Sebastian', age:50, gender:'boy'},
  18442. {name:'Erika', age:27, gender:'girl'},
  18443. {name:'Patrick', age:40, gender:'boy'},
  18444. {name:'Samantha', age:60, gender:'girl'}
  18445. ]">
  18446. I have {{friends.length}} friends. They are:
  18447. <input type="search" ng-model="q" placeholder="filter friends..." />
  18448. <ul class="example-animate-container">
  18449. <li class="animate-repeat" ng-repeat="friend in friends | filter:q">
  18450. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  18451. </li>
  18452. </ul>
  18453. </div>
  18454. </file>
  18455. <file name="animations.css">
  18456. .example-animate-container {
  18457. background:white;
  18458. border:1px solid black;
  18459. list-style:none;
  18460. margin:0;
  18461. padding:0 10px;
  18462. }
  18463. .animate-repeat {
  18464. line-height:40px;
  18465. list-style:none;
  18466. box-sizing:border-box;
  18467. }
  18468. .animate-repeat.ng-move,
  18469. .animate-repeat.ng-enter,
  18470. .animate-repeat.ng-leave {
  18471. -webkit-transition:all linear 0.5s;
  18472. transition:all linear 0.5s;
  18473. }
  18474. .animate-repeat.ng-leave.ng-leave-active,
  18475. .animate-repeat.ng-move,
  18476. .animate-repeat.ng-enter {
  18477. opacity:0;
  18478. max-height:0;
  18479. }
  18480. .animate-repeat.ng-leave,
  18481. .animate-repeat.ng-move.ng-move-active,
  18482. .animate-repeat.ng-enter.ng-enter-active {
  18483. opacity:1;
  18484. max-height:40px;
  18485. }
  18486. </file>
  18487. <file name="protractor.js" type="protractor">
  18488. var friends = element.all(by.repeater('friend in friends'));
  18489. it('should render initial data set', function() {
  18490. expect(friends.count()).toBe(10);
  18491. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  18492. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  18493. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  18494. expect(element(by.binding('friends.length')).getText())
  18495. .toMatch("I have 10 friends. They are:");
  18496. });
  18497. it('should update repeater when filter predicate changes', function() {
  18498. expect(friends.count()).toBe(10);
  18499. element(by.model('q')).sendKeys('ma');
  18500. expect(friends.count()).toBe(2);
  18501. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  18502. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  18503. });
  18504. </file>
  18505. </example>
  18506. */
  18507. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  18508. var NG_REMOVED = '$$NG_REMOVED';
  18509. var ngRepeatMinErr = minErr('ngRepeat');
  18510. return {
  18511. transclude: 'element',
  18512. priority: 1000,
  18513. terminal: true,
  18514. $$tlb: true,
  18515. link: function($scope, $element, $attr, ctrl, $transclude){
  18516. var expression = $attr.ngRepeat;
  18517. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+track\s+by\s+([\s\S]+?))?\s*$/),
  18518. trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
  18519. lhs, rhs, valueIdentifier, keyIdentifier,
  18520. hashFnLocals = {$id: hashKey};
  18521. if (!match) {
  18522. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  18523. expression);
  18524. }
  18525. lhs = match[1];
  18526. rhs = match[2];
  18527. trackByExp = match[3];
  18528. if (trackByExp) {
  18529. trackByExpGetter = $parse(trackByExp);
  18530. trackByIdExpFn = function(key, value, index) {
  18531. // assign key, value, and $index to the locals so that they can be used in hash functions
  18532. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  18533. hashFnLocals[valueIdentifier] = value;
  18534. hashFnLocals.$index = index;
  18535. return trackByExpGetter($scope, hashFnLocals);
  18536. };
  18537. } else {
  18538. trackByIdArrayFn = function(key, value) {
  18539. return hashKey(value);
  18540. };
  18541. trackByIdObjFn = function(key) {
  18542. return key;
  18543. };
  18544. }
  18545. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  18546. if (!match) {
  18547. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  18548. lhs);
  18549. }
  18550. valueIdentifier = match[3] || match[1];
  18551. keyIdentifier = match[2];
  18552. // Store a list of elements from previous run. This is a hash where key is the item from the
  18553. // iterator, and the value is objects with following properties.
  18554. // - scope: bound scope
  18555. // - element: previous element.
  18556. // - index: position
  18557. var lastBlockMap = {};
  18558. //watch props
  18559. $scope.$watchCollection(rhs, function ngRepeatAction(collection){
  18560. var index, length,
  18561. previousNode = $element[0], // current position of the node
  18562. nextNode,
  18563. // Same as lastBlockMap but it has the current state. It will become the
  18564. // lastBlockMap on the next iteration.
  18565. nextBlockMap = {},
  18566. arrayLength,
  18567. childScope,
  18568. key, value, // key/value of iteration
  18569. trackById,
  18570. trackByIdFn,
  18571. collectionKeys,
  18572. block, // last object information {scope, element, id}
  18573. nextBlockOrder = [],
  18574. elementsToRemove;
  18575. if (isArrayLike(collection)) {
  18576. collectionKeys = collection;
  18577. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  18578. } else {
  18579. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  18580. // if object, extract keys, sort them and use to determine order of iteration over obj props
  18581. collectionKeys = [];
  18582. for (key in collection) {
  18583. if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
  18584. collectionKeys.push(key);
  18585. }
  18586. }
  18587. collectionKeys.sort();
  18588. }
  18589. arrayLength = collectionKeys.length;
  18590. // locate existing items
  18591. length = nextBlockOrder.length = collectionKeys.length;
  18592. for(index = 0; index < length; index++) {
  18593. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18594. value = collection[key];
  18595. trackById = trackByIdFn(key, value, index);
  18596. assertNotHasOwnProperty(trackById, '`track by` id');
  18597. if(lastBlockMap.hasOwnProperty(trackById)) {
  18598. block = lastBlockMap[trackById];
  18599. delete lastBlockMap[trackById];
  18600. nextBlockMap[trackById] = block;
  18601. nextBlockOrder[index] = block;
  18602. } else if (nextBlockMap.hasOwnProperty(trackById)) {
  18603. // restore lastBlockMap
  18604. forEach(nextBlockOrder, function(block) {
  18605. if (block && block.scope) lastBlockMap[block.id] = block;
  18606. });
  18607. // This is a duplicate and we need to throw an error
  18608. throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
  18609. expression, trackById);
  18610. } else {
  18611. // new never before seen block
  18612. nextBlockOrder[index] = { id: trackById };
  18613. nextBlockMap[trackById] = false;
  18614. }
  18615. }
  18616. // remove existing items
  18617. for (key in lastBlockMap) {
  18618. // lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
  18619. if (lastBlockMap.hasOwnProperty(key)) {
  18620. block = lastBlockMap[key];
  18621. elementsToRemove = getBlockElements(block.clone);
  18622. $animate.leave(elementsToRemove);
  18623. forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
  18624. block.scope.$destroy();
  18625. }
  18626. }
  18627. // we are not using forEach for perf reasons (trying to avoid #call)
  18628. for (index = 0, length = collectionKeys.length; index < length; index++) {
  18629. key = (collection === collectionKeys) ? index : collectionKeys[index];
  18630. value = collection[key];
  18631. block = nextBlockOrder[index];
  18632. if (nextBlockOrder[index - 1]) previousNode = getBlockEnd(nextBlockOrder[index - 1]);
  18633. if (block.scope) {
  18634. // if we have already seen this object, then we need to reuse the
  18635. // associated scope/element
  18636. childScope = block.scope;
  18637. nextNode = previousNode;
  18638. do {
  18639. nextNode = nextNode.nextSibling;
  18640. } while(nextNode && nextNode[NG_REMOVED]);
  18641. if (getBlockStart(block) != nextNode) {
  18642. // existing item which got moved
  18643. $animate.move(getBlockElements(block.clone), null, jqLite(previousNode));
  18644. }
  18645. previousNode = getBlockEnd(block);
  18646. } else {
  18647. // new item which we don't know about
  18648. childScope = $scope.$new();
  18649. }
  18650. childScope[valueIdentifier] = value;
  18651. if (keyIdentifier) childScope[keyIdentifier] = key;
  18652. childScope.$index = index;
  18653. childScope.$first = (index === 0);
  18654. childScope.$last = (index === (arrayLength - 1));
  18655. childScope.$middle = !(childScope.$first || childScope.$last);
  18656. // jshint bitwise: false
  18657. childScope.$odd = !(childScope.$even = (index&1) === 0);
  18658. // jshint bitwise: true
  18659. if (!block.scope) {
  18660. $transclude(childScope, function(clone) {
  18661. clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
  18662. $animate.enter(clone, null, jqLite(previousNode));
  18663. previousNode = clone;
  18664. block.scope = childScope;
  18665. // Note: We only need the first/last node of the cloned nodes.
  18666. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  18667. // by a directive with templateUrl when its template arrives.
  18668. block.clone = clone;
  18669. nextBlockMap[block.id] = block;
  18670. });
  18671. }
  18672. }
  18673. lastBlockMap = nextBlockMap;
  18674. });
  18675. }
  18676. };
  18677. function getBlockStart(block) {
  18678. return block.clone[0];
  18679. }
  18680. function getBlockEnd(block) {
  18681. return block.clone[block.clone.length - 1];
  18682. }
  18683. }];
  18684. /**
  18685. * @ngdoc directive
  18686. * @name ngShow
  18687. *
  18688. * @description
  18689. * The `ngShow` directive shows or hides the given HTML element based on the expression
  18690. * provided to the ngShow attribute. The element is shown or hidden by removing or adding
  18691. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18692. * in AngularJS and sets the display style to none (using an !important flag).
  18693. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18694. *
  18695. * ```html
  18696. * <!-- when $scope.myValue is truthy (element is visible) -->
  18697. * <div ng-show="myValue"></div>
  18698. *
  18699. * <!-- when $scope.myValue is falsy (element is hidden) -->
  18700. * <div ng-show="myValue" class="ng-hide"></div>
  18701. * ```
  18702. *
  18703. * When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute
  18704. * on the element causing it to become hidden. When true, the ng-hide CSS class is removed
  18705. * from the element causing the element not to appear hidden.
  18706. *
  18707. * <div class="alert alert-warning">
  18708. * **Note:** Here is a list of values that ngShow will consider as a falsy value (case insensitive):<br />
  18709. * "f" / "0" / "false" / "no" / "n" / "[]"
  18710. * </div>
  18711. *
  18712. * ## Why is !important used?
  18713. *
  18714. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  18715. * can be easily overridden by heavier selectors. For example, something as simple
  18716. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18717. * This also becomes a bigger issue when dealing with CSS frameworks.
  18718. *
  18719. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18720. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18721. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18722. *
  18723. * ### Overriding .ng-hide
  18724. *
  18725. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  18726. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  18727. * class in CSS:
  18728. *
  18729. * ```css
  18730. * .ng-hide {
  18731. * //this is just another form of hiding an element
  18732. * display:block!important;
  18733. * position:absolute;
  18734. * top:-9999px;
  18735. * left:-9999px;
  18736. * }
  18737. * ```
  18738. *
  18739. * By default you don't need to override in CSS anything and the animations will work around the display style.
  18740. *
  18741. * ## A note about animations with ngShow
  18742. *
  18743. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  18744. * is true and false. This system works like the animation system present with ngClass except that
  18745. * you must also include the !important flag to override the display property
  18746. * so that you can perform an animation when the element is hidden during the time of the animation.
  18747. *
  18748. * ```css
  18749. * //
  18750. * //a working example can be found at the bottom of this page
  18751. * //
  18752. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  18753. * transition:0.5s linear all;
  18754. * }
  18755. *
  18756. * .my-element.ng-hide-add { ... }
  18757. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  18758. * .my-element.ng-hide-remove { ... }
  18759. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  18760. * ```
  18761. *
  18762. * Keep in mind that, as of AngularJS version 1.2.17 (and 1.3.0-beta.11), there is no need to change the display
  18763. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  18764. *
  18765. * @animations
  18766. * addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
  18767. * removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
  18768. *
  18769. * @element ANY
  18770. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  18771. * then the element is shown or hidden respectively.
  18772. *
  18773. * @example
  18774. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18775. <file name="index.html">
  18776. Click me: <input type="checkbox" ng-model="checked"><br/>
  18777. <div>
  18778. Show:
  18779. <div class="check-element animate-show" ng-show="checked">
  18780. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  18781. </div>
  18782. </div>
  18783. <div>
  18784. Hide:
  18785. <div class="check-element animate-show" ng-hide="checked">
  18786. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  18787. </div>
  18788. </div>
  18789. </file>
  18790. <file name="glyphicons.css">
  18791. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  18792. </file>
  18793. <file name="animations.css">
  18794. .animate-show {
  18795. -webkit-transition:all linear 0.5s;
  18796. transition:all linear 0.5s;
  18797. line-height:20px;
  18798. opacity:1;
  18799. padding:10px;
  18800. border:1px solid black;
  18801. background:white;
  18802. }
  18803. .animate-show.ng-hide {
  18804. line-height:0;
  18805. opacity:0;
  18806. padding:0 10px;
  18807. }
  18808. .check-element {
  18809. padding:10px;
  18810. border:1px solid black;
  18811. background:white;
  18812. }
  18813. </file>
  18814. <file name="protractor.js" type="protractor">
  18815. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  18816. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  18817. it('should check ng-show / ng-hide', function() {
  18818. expect(thumbsUp.isDisplayed()).toBeFalsy();
  18819. expect(thumbsDown.isDisplayed()).toBeTruthy();
  18820. element(by.model('checked')).click();
  18821. expect(thumbsUp.isDisplayed()).toBeTruthy();
  18822. expect(thumbsDown.isDisplayed()).toBeFalsy();
  18823. });
  18824. </file>
  18825. </example>
  18826. */
  18827. var ngShowDirective = ['$animate', function($animate) {
  18828. return function(scope, element, attr) {
  18829. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  18830. $animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
  18831. });
  18832. };
  18833. }];
  18834. /**
  18835. * @ngdoc directive
  18836. * @name ngHide
  18837. *
  18838. * @description
  18839. * The `ngHide` directive shows or hides the given HTML element based on the expression
  18840. * provided to the ngHide attribute. The element is shown or hidden by removing or adding
  18841. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  18842. * in AngularJS and sets the display style to none (using an !important flag).
  18843. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  18844. *
  18845. * ```html
  18846. * <!-- when $scope.myValue is truthy (element is hidden) -->
  18847. * <div ng-hide="myValue" class="ng-hide"></div>
  18848. *
  18849. * <!-- when $scope.myValue is falsy (element is visible) -->
  18850. * <div ng-hide="myValue"></div>
  18851. * ```
  18852. *
  18853. * When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute
  18854. * on the element causing it to become hidden. When false, the ng-hide CSS class is removed
  18855. * from the element causing the element not to appear hidden.
  18856. *
  18857. * <div class="alert alert-warning">
  18858. * **Note:** Here is a list of values that ngHide will consider as a falsy value (case insensitive):<br />
  18859. * "f" / "0" / "false" / "no" / "n" / "[]"
  18860. * </div>
  18861. *
  18862. * ## Why is !important used?
  18863. *
  18864. * You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
  18865. * can be easily overridden by heavier selectors. For example, something as simple
  18866. * as changing the display style on a HTML list item would make hidden elements appear visible.
  18867. * This also becomes a bigger issue when dealing with CSS frameworks.
  18868. *
  18869. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  18870. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  18871. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  18872. *
  18873. * ### Overriding .ng-hide
  18874. *
  18875. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  18876. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  18877. * class in CSS:
  18878. *
  18879. * ```css
  18880. * .ng-hide {
  18881. * //this is just another form of hiding an element
  18882. * display:block!important;
  18883. * position:absolute;
  18884. * top:-9999px;
  18885. * left:-9999px;
  18886. * }
  18887. * ```
  18888. *
  18889. * By default you don't need to override in CSS anything and the animations will work around the display style.
  18890. *
  18891. * ## A note about animations with ngHide
  18892. *
  18893. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  18894. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  18895. * CSS class is added and removed for you instead of your own CSS class.
  18896. *
  18897. * ```css
  18898. * //
  18899. * //a working example can be found at the bottom of this page
  18900. * //
  18901. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  18902. * transition:0.5s linear all;
  18903. * }
  18904. *
  18905. * .my-element.ng-hide-add { ... }
  18906. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  18907. * .my-element.ng-hide-remove { ... }
  18908. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  18909. * ```
  18910. *
  18911. * Keep in mind that, as of AngularJS version 1.2.17 (and 1.3.0-beta.11), there is no need to change the display
  18912. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  18913. *
  18914. * @animations
  18915. * removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
  18916. * addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
  18917. *
  18918. * @element ANY
  18919. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  18920. * the element is shown or hidden respectively.
  18921. *
  18922. * @example
  18923. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  18924. <file name="index.html">
  18925. Click me: <input type="checkbox" ng-model="checked"><br/>
  18926. <div>
  18927. Show:
  18928. <div class="check-element animate-hide" ng-show="checked">
  18929. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  18930. </div>
  18931. </div>
  18932. <div>
  18933. Hide:
  18934. <div class="check-element animate-hide" ng-hide="checked">
  18935. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  18936. </div>
  18937. </div>
  18938. </file>
  18939. <file name="glyphicons.css">
  18940. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  18941. </file>
  18942. <file name="animations.css">
  18943. .animate-hide {
  18944. -webkit-transition:all linear 0.5s;
  18945. transition:all linear 0.5s;
  18946. line-height:20px;
  18947. opacity:1;
  18948. padding:10px;
  18949. border:1px solid black;
  18950. background:white;
  18951. }
  18952. .animate-hide.ng-hide {
  18953. line-height:0;
  18954. opacity:0;
  18955. padding:0 10px;
  18956. }
  18957. .check-element {
  18958. padding:10px;
  18959. border:1px solid black;
  18960. background:white;
  18961. }
  18962. </file>
  18963. <file name="protractor.js" type="protractor">
  18964. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  18965. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  18966. it('should check ng-show / ng-hide', function() {
  18967. expect(thumbsUp.isDisplayed()).toBeFalsy();
  18968. expect(thumbsDown.isDisplayed()).toBeTruthy();
  18969. element(by.model('checked')).click();
  18970. expect(thumbsUp.isDisplayed()).toBeTruthy();
  18971. expect(thumbsDown.isDisplayed()).toBeFalsy();
  18972. });
  18973. </file>
  18974. </example>
  18975. */
  18976. var ngHideDirective = ['$animate', function($animate) {
  18977. return function(scope, element, attr) {
  18978. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  18979. $animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
  18980. });
  18981. };
  18982. }];
  18983. /**
  18984. * @ngdoc directive
  18985. * @name ngStyle
  18986. * @restrict AC
  18987. *
  18988. * @description
  18989. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  18990. *
  18991. * @element ANY
  18992. * @param {expression} ngStyle
  18993. *
  18994. * {@link guide/expression Expression} which evals to an
  18995. * object whose keys are CSS style names and values are corresponding values for those CSS
  18996. * keys.
  18997. *
  18998. * Since some CSS style names are not valid keys for an object, they must be quoted.
  18999. * See the 'background-color' style in the example below.
  19000. *
  19001. * @example
  19002. <example>
  19003. <file name="index.html">
  19004. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  19005. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  19006. <input type="button" value="clear" ng-click="myStyle={}">
  19007. <br/>
  19008. <span ng-style="myStyle">Sample Text</span>
  19009. <pre>myStyle={{myStyle}}</pre>
  19010. </file>
  19011. <file name="style.css">
  19012. span {
  19013. color: black;
  19014. }
  19015. </file>
  19016. <file name="protractor.js" type="protractor">
  19017. var colorSpan = element(by.css('span'));
  19018. it('should check ng-style', function() {
  19019. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  19020. element(by.css('input[value=\'set color\']')).click();
  19021. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  19022. element(by.css('input[value=clear]')).click();
  19023. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  19024. });
  19025. </file>
  19026. </example>
  19027. */
  19028. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  19029. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  19030. if (oldStyles && (newStyles !== oldStyles)) {
  19031. forEach(oldStyles, function(val, style) { element.css(style, '');});
  19032. }
  19033. if (newStyles) element.css(newStyles);
  19034. }, true);
  19035. });
  19036. /**
  19037. * @ngdoc directive
  19038. * @name ngSwitch
  19039. * @restrict EA
  19040. *
  19041. * @description
  19042. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  19043. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  19044. * as specified in the template.
  19045. *
  19046. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  19047. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  19048. * matches the value obtained from the evaluated expression. In other words, you define a container element
  19049. * (where you place the directive), place an expression on the **`on="..."` attribute**
  19050. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  19051. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  19052. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  19053. * attribute is displayed.
  19054. *
  19055. * <div class="alert alert-info">
  19056. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  19057. * as literal string values to match against.
  19058. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  19059. * value of the expression `$scope.someVal`.
  19060. * </div>
  19061. * @animations
  19062. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  19063. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  19064. *
  19065. * @usage
  19066. *
  19067. * ```
  19068. * <ANY ng-switch="expression">
  19069. * <ANY ng-switch-when="matchValue1">...</ANY>
  19070. * <ANY ng-switch-when="matchValue2">...</ANY>
  19071. * <ANY ng-switch-default>...</ANY>
  19072. * </ANY>
  19073. * ```
  19074. *
  19075. *
  19076. * @scope
  19077. * @priority 800
  19078. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  19079. * On child elements add:
  19080. *
  19081. * * `ngSwitchWhen`: the case statement to match against. If match then this
  19082. * case will be displayed. If the same match appears multiple times, all the
  19083. * elements will be displayed.
  19084. * * `ngSwitchDefault`: the default case when no other case match. If there
  19085. * are multiple default cases, all of them will be displayed when no other
  19086. * case match.
  19087. *
  19088. *
  19089. * @example
  19090. <example module="switchExample" deps="angular-animate.js" animations="true">
  19091. <file name="index.html">
  19092. <div ng-controller="ExampleController">
  19093. <select ng-model="selection" ng-options="item for item in items">
  19094. </select>
  19095. <tt>selection={{selection}}</tt>
  19096. <hr/>
  19097. <div class="animate-switch-container"
  19098. ng-switch on="selection">
  19099. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  19100. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  19101. <div class="animate-switch" ng-switch-default>default</div>
  19102. </div>
  19103. </div>
  19104. </file>
  19105. <file name="script.js">
  19106. angular.module('switchExample', ['ngAnimate'])
  19107. .controller('ExampleController', ['$scope', function($scope) {
  19108. $scope.items = ['settings', 'home', 'other'];
  19109. $scope.selection = $scope.items[0];
  19110. }]);
  19111. </file>
  19112. <file name="animations.css">
  19113. .animate-switch-container {
  19114. position:relative;
  19115. background:white;
  19116. border:1px solid black;
  19117. height:40px;
  19118. overflow:hidden;
  19119. }
  19120. .animate-switch {
  19121. padding:10px;
  19122. }
  19123. .animate-switch.ng-animate {
  19124. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19125. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19126. position:absolute;
  19127. top:0;
  19128. left:0;
  19129. right:0;
  19130. bottom:0;
  19131. }
  19132. .animate-switch.ng-leave.ng-leave-active,
  19133. .animate-switch.ng-enter {
  19134. top:-50px;
  19135. }
  19136. .animate-switch.ng-leave,
  19137. .animate-switch.ng-enter.ng-enter-active {
  19138. top:0;
  19139. }
  19140. </file>
  19141. <file name="protractor.js" type="protractor">
  19142. var switchElem = element(by.css('[ng-switch]'));
  19143. var select = element(by.model('selection'));
  19144. it('should start in settings', function() {
  19145. expect(switchElem.getText()).toMatch(/Settings Div/);
  19146. });
  19147. it('should change to home', function() {
  19148. select.all(by.css('option')).get(1).click();
  19149. expect(switchElem.getText()).toMatch(/Home Span/);
  19150. });
  19151. it('should select default', function() {
  19152. select.all(by.css('option')).get(2).click();
  19153. expect(switchElem.getText()).toMatch(/default/);
  19154. });
  19155. </file>
  19156. </example>
  19157. */
  19158. var ngSwitchDirective = ['$animate', function($animate) {
  19159. return {
  19160. restrict: 'EA',
  19161. require: 'ngSwitch',
  19162. // asks for $scope to fool the BC controller module
  19163. controller: ['$scope', function ngSwitchController() {
  19164. this.cases = {};
  19165. }],
  19166. link: function(scope, element, attr, ngSwitchController) {
  19167. var watchExpr = attr.ngSwitch || attr.on,
  19168. selectedTranscludes = [],
  19169. selectedElements = [],
  19170. previousElements = [],
  19171. selectedScopes = [];
  19172. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  19173. var i, ii;
  19174. for (i = 0, ii = previousElements.length; i < ii; ++i) {
  19175. previousElements[i].remove();
  19176. }
  19177. previousElements.length = 0;
  19178. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  19179. var selected = selectedElements[i];
  19180. selectedScopes[i].$destroy();
  19181. previousElements[i] = selected;
  19182. $animate.leave(selected, function() {
  19183. previousElements.splice(i, 1);
  19184. });
  19185. }
  19186. selectedElements.length = 0;
  19187. selectedScopes.length = 0;
  19188. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  19189. scope.$eval(attr.change);
  19190. forEach(selectedTranscludes, function(selectedTransclude) {
  19191. var selectedScope = scope.$new();
  19192. selectedScopes.push(selectedScope);
  19193. selectedTransclude.transclude(selectedScope, function(caseElement) {
  19194. var anchor = selectedTransclude.element;
  19195. selectedElements.push(caseElement);
  19196. $animate.enter(caseElement, anchor.parent(), anchor);
  19197. });
  19198. });
  19199. }
  19200. });
  19201. }
  19202. };
  19203. }];
  19204. var ngSwitchWhenDirective = ngDirective({
  19205. transclude: 'element',
  19206. priority: 800,
  19207. require: '^ngSwitch',
  19208. link: function(scope, element, attrs, ctrl, $transclude) {
  19209. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  19210. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  19211. }
  19212. });
  19213. var ngSwitchDefaultDirective = ngDirective({
  19214. transclude: 'element',
  19215. priority: 800,
  19216. require: '^ngSwitch',
  19217. link: function(scope, element, attr, ctrl, $transclude) {
  19218. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  19219. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  19220. }
  19221. });
  19222. /**
  19223. * @ngdoc directive
  19224. * @name ngTransclude
  19225. * @restrict AC
  19226. *
  19227. * @description
  19228. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  19229. *
  19230. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  19231. *
  19232. * @element ANY
  19233. *
  19234. * @example
  19235. <example module="transcludeExample">
  19236. <file name="index.html">
  19237. <script>
  19238. angular.module('transcludeExample', [])
  19239. .directive('pane', function(){
  19240. return {
  19241. restrict: 'E',
  19242. transclude: true,
  19243. scope: { title:'@' },
  19244. template: '<div style="border: 1px solid black;">' +
  19245. '<div style="background-color: gray">{{title}}</div>' +
  19246. '<div ng-transclude></div>' +
  19247. '</div>'
  19248. };
  19249. })
  19250. .controller('ExampleController', ['$scope', function($scope) {
  19251. $scope.title = 'Lorem Ipsum';
  19252. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  19253. }]);
  19254. </script>
  19255. <div ng-controller="ExampleController">
  19256. <input ng-model="title"><br>
  19257. <textarea ng-model="text"></textarea> <br/>
  19258. <pane title="{{title}}">{{text}}</pane>
  19259. </div>
  19260. </file>
  19261. <file name="protractor.js" type="protractor">
  19262. it('should have transcluded', function() {
  19263. var titleElement = element(by.model('title'));
  19264. titleElement.clear();
  19265. titleElement.sendKeys('TITLE');
  19266. var textElement = element(by.model('text'));
  19267. textElement.clear();
  19268. textElement.sendKeys('TEXT');
  19269. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  19270. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  19271. });
  19272. </file>
  19273. </example>
  19274. *
  19275. */
  19276. var ngTranscludeDirective = ngDirective({
  19277. link: function($scope, $element, $attrs, controller, $transclude) {
  19278. if (!$transclude) {
  19279. throw minErr('ngTransclude')('orphan',
  19280. 'Illegal use of ngTransclude directive in the template! ' +
  19281. 'No parent directive that requires a transclusion found. ' +
  19282. 'Element: {0}',
  19283. startingTag($element));
  19284. }
  19285. $transclude(function(clone) {
  19286. $element.empty();
  19287. $element.append(clone);
  19288. });
  19289. }
  19290. });
  19291. /**
  19292. * @ngdoc directive
  19293. * @name script
  19294. * @restrict E
  19295. *
  19296. * @description
  19297. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  19298. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  19299. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  19300. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  19301. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  19302. *
  19303. * @param {string} type Must be set to `'text/ng-template'`.
  19304. * @param {string} id Cache name of the template.
  19305. *
  19306. * @example
  19307. <example>
  19308. <file name="index.html">
  19309. <script type="text/ng-template" id="/tpl.html">
  19310. Content of the template.
  19311. </script>
  19312. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  19313. <div id="tpl-content" ng-include src="currentTpl"></div>
  19314. </file>
  19315. <file name="protractor.js" type="protractor">
  19316. it('should load template defined inside script tag', function() {
  19317. element(by.css('#tpl-link')).click();
  19318. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  19319. });
  19320. </file>
  19321. </example>
  19322. */
  19323. var scriptDirective = ['$templateCache', function($templateCache) {
  19324. return {
  19325. restrict: 'E',
  19326. terminal: true,
  19327. compile: function(element, attr) {
  19328. if (attr.type == 'text/ng-template') {
  19329. var templateUrl = attr.id,
  19330. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  19331. text = element[0].text;
  19332. $templateCache.put(templateUrl, text);
  19333. }
  19334. }
  19335. };
  19336. }];
  19337. var ngOptionsMinErr = minErr('ngOptions');
  19338. /**
  19339. * @ngdoc directive
  19340. * @name select
  19341. * @restrict E
  19342. *
  19343. * @description
  19344. * HTML `SELECT` element with angular data-binding.
  19345. *
  19346. * # `ngOptions`
  19347. *
  19348. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  19349. * elements for the `<select>` element using the array or object obtained by evaluating the
  19350. * `ngOptions` comprehension_expression.
  19351. *
  19352. * When an item in the `<select>` menu is selected, the array element or object property
  19353. * represented by the selected option will be bound to the model identified by the `ngModel`
  19354. * directive.
  19355. *
  19356. * <div class="alert alert-warning">
  19357. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  19358. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  19359. * </div>
  19360. *
  19361. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  19362. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  19363. * option. See example below for demonstration.
  19364. *
  19365. * <div class="alert alert-warning">
  19366. * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead
  19367. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  19368. * `select` model to be bound to a non-string value. This is because an option element can only
  19369. * be bound to string values at present.
  19370. * </div>
  19371. *
  19372. * @param {string} ngModel Assignable angular expression to data-bind to.
  19373. * @param {string=} name Property name of the form under which the control is published.
  19374. * @param {string=} required The control is considered valid only if value is entered.
  19375. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19376. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19377. * `required` when you want to data-bind to the `required` attribute.
  19378. * @param {comprehension_expression=} ngOptions in one of the following forms:
  19379. *
  19380. * * for array data sources:
  19381. * * `label` **`for`** `value` **`in`** `array`
  19382. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  19383. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  19384. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  19385. * * for object data sources:
  19386. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19387. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  19388. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  19389. * * `select` **`as`** `label` **`group by`** `group`
  19390. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  19391. *
  19392. * Where:
  19393. *
  19394. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  19395. * * `value`: local variable which will refer to each item in the `array` or each property value
  19396. * of `object` during iteration.
  19397. * * `key`: local variable which will refer to a property name in `object` during iteration.
  19398. * * `label`: The result of this expression will be the label for `<option>` element. The
  19399. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  19400. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  19401. * element. If not specified, `select` expression will default to `value`.
  19402. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  19403. * DOM element.
  19404. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  19405. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  19406. * `value` variable (e.g. `value.propertyName`).
  19407. *
  19408. * @example
  19409. <example module="selectExample">
  19410. <file name="index.html">
  19411. <script>
  19412. angular.module('selectExample', [])
  19413. .controller('ExampleController', ['$scope', function($scope) {
  19414. $scope.colors = [
  19415. {name:'black', shade:'dark'},
  19416. {name:'white', shade:'light'},
  19417. {name:'red', shade:'dark'},
  19418. {name:'blue', shade:'dark'},
  19419. {name:'yellow', shade:'light'}
  19420. ];
  19421. $scope.myColor = $scope.colors[2]; // red
  19422. }]);
  19423. </script>
  19424. <div ng-controller="ExampleController">
  19425. <ul>
  19426. <li ng-repeat="color in colors">
  19427. Name: <input ng-model="color.name">
  19428. [<a href ng-click="colors.splice($index, 1)">X</a>]
  19429. </li>
  19430. <li>
  19431. [<a href ng-click="colors.push({})">add</a>]
  19432. </li>
  19433. </ul>
  19434. <hr/>
  19435. Color (null not allowed):
  19436. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  19437. Color (null allowed):
  19438. <span class="nullable">
  19439. <select ng-model="myColor" ng-options="color.name for color in colors">
  19440. <option value="">-- choose color --</option>
  19441. </select>
  19442. </span><br/>
  19443. Color grouped by shade:
  19444. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  19445. </select><br/>
  19446. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  19447. <hr/>
  19448. Currently selected: {{ {selected_color:myColor} }}
  19449. <div style="border:solid 1px black; height:20px"
  19450. ng-style="{'background-color':myColor.name}">
  19451. </div>
  19452. </div>
  19453. </file>
  19454. <file name="protractor.js" type="protractor">
  19455. it('should check ng-options', function() {
  19456. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  19457. element.all(by.model('myColor')).first().click();
  19458. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  19459. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  19460. element(by.css('.nullable select[ng-model="myColor"]')).click();
  19461. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  19462. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  19463. });
  19464. </file>
  19465. </example>
  19466. */
  19467. var ngOptionsDirective = valueFn({ terminal: true });
  19468. // jshint maxlen: false
  19469. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  19470. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  19471. 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]+?))?$/,
  19472. nullModelCtrl = {$setViewValue: noop};
  19473. // jshint maxlen: 100
  19474. return {
  19475. restrict: 'E',
  19476. require: ['select', '?ngModel'],
  19477. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  19478. var self = this,
  19479. optionsMap = {},
  19480. ngModelCtrl = nullModelCtrl,
  19481. nullOption,
  19482. unknownOption;
  19483. self.databound = $attrs.ngModel;
  19484. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  19485. ngModelCtrl = ngModelCtrl_;
  19486. nullOption = nullOption_;
  19487. unknownOption = unknownOption_;
  19488. };
  19489. self.addOption = function(value) {
  19490. assertNotHasOwnProperty(value, '"option value"');
  19491. optionsMap[value] = true;
  19492. if (ngModelCtrl.$viewValue == value) {
  19493. $element.val(value);
  19494. if (unknownOption.parent()) unknownOption.remove();
  19495. }
  19496. };
  19497. self.removeOption = function(value) {
  19498. if (this.hasOption(value)) {
  19499. delete optionsMap[value];
  19500. if (ngModelCtrl.$viewValue == value) {
  19501. this.renderUnknownOption(value);
  19502. }
  19503. }
  19504. };
  19505. self.renderUnknownOption = function(val) {
  19506. var unknownVal = '? ' + hashKey(val) + ' ?';
  19507. unknownOption.val(unknownVal);
  19508. $element.prepend(unknownOption);
  19509. $element.val(unknownVal);
  19510. unknownOption.prop('selected', true); // needed for IE
  19511. };
  19512. self.hasOption = function(value) {
  19513. return optionsMap.hasOwnProperty(value);
  19514. };
  19515. $scope.$on('$destroy', function() {
  19516. // disable unknown option so that we don't do work when the whole select is being destroyed
  19517. self.renderUnknownOption = noop;
  19518. });
  19519. }],
  19520. link: function(scope, element, attr, ctrls) {
  19521. // if ngModel is not defined, we don't need to do anything
  19522. if (!ctrls[1]) return;
  19523. var selectCtrl = ctrls[0],
  19524. ngModelCtrl = ctrls[1],
  19525. multiple = attr.multiple,
  19526. optionsExp = attr.ngOptions,
  19527. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  19528. emptyOption,
  19529. // we can't just jqLite('<option>') since jqLite is not smart enough
  19530. // to create it in <select> and IE barfs otherwise.
  19531. optionTemplate = jqLite(document.createElement('option')),
  19532. optGroupTemplate =jqLite(document.createElement('optgroup')),
  19533. unknownOption = optionTemplate.clone();
  19534. // find "null" option
  19535. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  19536. if (children[i].value === '') {
  19537. emptyOption = nullOption = children.eq(i);
  19538. break;
  19539. }
  19540. }
  19541. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  19542. // required validator
  19543. if (multiple) {
  19544. ngModelCtrl.$isEmpty = function(value) {
  19545. return !value || value.length === 0;
  19546. };
  19547. }
  19548. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  19549. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  19550. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  19551. ////////////////////////////
  19552. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  19553. ngModelCtrl.$render = function() {
  19554. var viewValue = ngModelCtrl.$viewValue;
  19555. if (selectCtrl.hasOption(viewValue)) {
  19556. if (unknownOption.parent()) unknownOption.remove();
  19557. selectElement.val(viewValue);
  19558. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  19559. } else {
  19560. if (isUndefined(viewValue) && emptyOption) {
  19561. selectElement.val('');
  19562. } else {
  19563. selectCtrl.renderUnknownOption(viewValue);
  19564. }
  19565. }
  19566. };
  19567. selectElement.on('change', function() {
  19568. scope.$apply(function() {
  19569. if (unknownOption.parent()) unknownOption.remove();
  19570. ngModelCtrl.$setViewValue(selectElement.val());
  19571. });
  19572. });
  19573. }
  19574. function setupAsMultiple(scope, selectElement, ctrl) {
  19575. var lastView;
  19576. ctrl.$render = function() {
  19577. var items = new HashMap(ctrl.$viewValue);
  19578. forEach(selectElement.find('option'), function(option) {
  19579. option.selected = isDefined(items.get(option.value));
  19580. });
  19581. };
  19582. // we have to do it on each watch since ngModel watches reference, but
  19583. // we need to work of an array, so we need to see if anything was inserted/removed
  19584. scope.$watch(function selectMultipleWatch() {
  19585. if (!equals(lastView, ctrl.$viewValue)) {
  19586. lastView = shallowCopy(ctrl.$viewValue);
  19587. ctrl.$render();
  19588. }
  19589. });
  19590. selectElement.on('change', function() {
  19591. scope.$apply(function() {
  19592. var array = [];
  19593. forEach(selectElement.find('option'), function(option) {
  19594. if (option.selected) {
  19595. array.push(option.value);
  19596. }
  19597. });
  19598. ctrl.$setViewValue(array);
  19599. });
  19600. });
  19601. }
  19602. function setupAsOptions(scope, selectElement, ctrl) {
  19603. var match;
  19604. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  19605. throw ngOptionsMinErr('iexp',
  19606. "Expected expression in form of " +
  19607. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  19608. " but got '{0}'. Element: {1}",
  19609. optionsExp, startingTag(selectElement));
  19610. }
  19611. var displayFn = $parse(match[2] || match[1]),
  19612. valueName = match[4] || match[6],
  19613. keyName = match[5],
  19614. groupByFn = $parse(match[3] || ''),
  19615. valueFn = $parse(match[2] ? match[1] : valueName),
  19616. valuesFn = $parse(match[7]),
  19617. track = match[8],
  19618. trackFn = track ? $parse(match[8]) : null,
  19619. // This is an array of array of existing option groups in DOM.
  19620. // We try to reuse these if possible
  19621. // - optionGroupsCache[0] is the options with no option group
  19622. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  19623. optionGroupsCache = [[{element: selectElement, label:''}]];
  19624. if (nullOption) {
  19625. // compile the element since there might be bindings in it
  19626. $compile(nullOption)(scope);
  19627. // remove the class, which is added automatically because we recompile the element and it
  19628. // becomes the compilation root
  19629. nullOption.removeClass('ng-scope');
  19630. // we need to remove it before calling selectElement.empty() because otherwise IE will
  19631. // remove the label from the element. wtf?
  19632. nullOption.remove();
  19633. }
  19634. // clear contents, we'll add what's needed based on the model
  19635. selectElement.empty();
  19636. selectElement.on('change', function() {
  19637. scope.$apply(function() {
  19638. var optionGroup,
  19639. collection = valuesFn(scope) || [],
  19640. locals = {},
  19641. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  19642. if (multiple) {
  19643. value = [];
  19644. for (groupIndex = 0, groupLength = optionGroupsCache.length;
  19645. groupIndex < groupLength;
  19646. groupIndex++) {
  19647. // list of options for that group. (first item has the parent)
  19648. optionGroup = optionGroupsCache[groupIndex];
  19649. for(index = 1, length = optionGroup.length; index < length; index++) {
  19650. if ((optionElement = optionGroup[index].element)[0].selected) {
  19651. key = optionElement.val();
  19652. if (keyName) locals[keyName] = key;
  19653. if (trackFn) {
  19654. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19655. locals[valueName] = collection[trackIndex];
  19656. if (trackFn(scope, locals) == key) break;
  19657. }
  19658. } else {
  19659. locals[valueName] = collection[key];
  19660. }
  19661. value.push(valueFn(scope, locals));
  19662. }
  19663. }
  19664. }
  19665. } else {
  19666. key = selectElement.val();
  19667. if (key == '?') {
  19668. value = undefined;
  19669. } else if (key === ''){
  19670. value = null;
  19671. } else {
  19672. if (trackFn) {
  19673. for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
  19674. locals[valueName] = collection[trackIndex];
  19675. if (trackFn(scope, locals) == key) {
  19676. value = valueFn(scope, locals);
  19677. break;
  19678. }
  19679. }
  19680. } else {
  19681. locals[valueName] = collection[key];
  19682. if (keyName) locals[keyName] = key;
  19683. value = valueFn(scope, locals);
  19684. }
  19685. }
  19686. // Update the null option's selected property here so $render cleans it up correctly
  19687. if (optionGroupsCache[0].length > 1) {
  19688. if (optionGroupsCache[0][1].id !== key) {
  19689. optionGroupsCache[0][1].selected = false;
  19690. }
  19691. }
  19692. }
  19693. ctrl.$setViewValue(value);
  19694. });
  19695. });
  19696. ctrl.$render = render;
  19697. // TODO(vojta): can't we optimize this ?
  19698. scope.$watch(render);
  19699. function render() {
  19700. // Temporary location for the option groups before we render them
  19701. var optionGroups = {'':[]},
  19702. optionGroupNames = [''],
  19703. optionGroupName,
  19704. optionGroup,
  19705. option,
  19706. existingParent, existingOptions, existingOption,
  19707. modelValue = ctrl.$modelValue,
  19708. values = valuesFn(scope) || [],
  19709. keys = keyName ? sortedKeys(values) : values,
  19710. key,
  19711. groupLength, length,
  19712. groupIndex, index,
  19713. locals = {},
  19714. selected,
  19715. selectedSet = false, // nothing is selected yet
  19716. lastElement,
  19717. element,
  19718. label;
  19719. if (multiple) {
  19720. if (trackFn && isArray(modelValue)) {
  19721. selectedSet = new HashMap([]);
  19722. for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
  19723. locals[valueName] = modelValue[trackIndex];
  19724. selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
  19725. }
  19726. } else {
  19727. selectedSet = new HashMap(modelValue);
  19728. }
  19729. }
  19730. // We now build up the list of options we need (we merge later)
  19731. for (index = 0; length = keys.length, index < length; index++) {
  19732. key = index;
  19733. if (keyName) {
  19734. key = keys[index];
  19735. if ( key.charAt(0) === '$' ) continue;
  19736. locals[keyName] = key;
  19737. }
  19738. locals[valueName] = values[key];
  19739. optionGroupName = groupByFn(scope, locals) || '';
  19740. if (!(optionGroup = optionGroups[optionGroupName])) {
  19741. optionGroup = optionGroups[optionGroupName] = [];
  19742. optionGroupNames.push(optionGroupName);
  19743. }
  19744. if (multiple) {
  19745. selected = isDefined(
  19746. selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
  19747. );
  19748. } else {
  19749. if (trackFn) {
  19750. var modelCast = {};
  19751. modelCast[valueName] = modelValue;
  19752. selected = trackFn(scope, modelCast) === trackFn(scope, locals);
  19753. } else {
  19754. selected = modelValue === valueFn(scope, locals);
  19755. }
  19756. selectedSet = selectedSet || selected; // see if at least one item is selected
  19757. }
  19758. label = displayFn(scope, locals); // what will be seen by the user
  19759. // doing displayFn(scope, locals) || '' overwrites zero values
  19760. label = isDefined(label) ? label : '';
  19761. optionGroup.push({
  19762. // either the index into array or key from object
  19763. id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
  19764. label: label,
  19765. selected: selected // determine if we should be selected
  19766. });
  19767. }
  19768. if (!multiple) {
  19769. if (nullOption || modelValue === null) {
  19770. // insert null option if we have a placeholder, or the model is null
  19771. optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
  19772. } else if (!selectedSet) {
  19773. // option could not be found, we have to insert the undefined item
  19774. optionGroups[''].unshift({id:'?', label:'', selected:true});
  19775. }
  19776. }
  19777. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  19778. for (groupIndex = 0, groupLength = optionGroupNames.length;
  19779. groupIndex < groupLength;
  19780. groupIndex++) {
  19781. // current option group name or '' if no group
  19782. optionGroupName = optionGroupNames[groupIndex];
  19783. // list of options for that group. (first item has the parent)
  19784. optionGroup = optionGroups[optionGroupName];
  19785. if (optionGroupsCache.length <= groupIndex) {
  19786. // we need to grow the optionGroups
  19787. existingParent = {
  19788. element: optGroupTemplate.clone().attr('label', optionGroupName),
  19789. label: optionGroup.label
  19790. };
  19791. existingOptions = [existingParent];
  19792. optionGroupsCache.push(existingOptions);
  19793. selectElement.append(existingParent.element);
  19794. } else {
  19795. existingOptions = optionGroupsCache[groupIndex];
  19796. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  19797. // update the OPTGROUP label if not the same.
  19798. if (existingParent.label != optionGroupName) {
  19799. existingParent.element.attr('label', existingParent.label = optionGroupName);
  19800. }
  19801. }
  19802. lastElement = null; // start at the beginning
  19803. for(index = 0, length = optionGroup.length; index < length; index++) {
  19804. option = optionGroup[index];
  19805. if ((existingOption = existingOptions[index+1])) {
  19806. // reuse elements
  19807. lastElement = existingOption.element;
  19808. if (existingOption.label !== option.label) {
  19809. lastElement.text(existingOption.label = option.label);
  19810. }
  19811. if (existingOption.id !== option.id) {
  19812. lastElement.val(existingOption.id = option.id);
  19813. }
  19814. // lastElement.prop('selected') provided by jQuery has side-effects
  19815. if (existingOption.selected !== option.selected) {
  19816. lastElement.prop('selected', (existingOption.selected = option.selected));
  19817. if (msie) {
  19818. // See #7692
  19819. // The selected item wouldn't visually update on IE without this.
  19820. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  19821. lastElement.prop('selected', existingOption.selected);
  19822. }
  19823. }
  19824. } else {
  19825. // grow elements
  19826. // if it's a null option
  19827. if (option.id === '' && nullOption) {
  19828. // put back the pre-compiled element
  19829. element = nullOption;
  19830. } else {
  19831. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  19832. // in this version of jQuery on some browser the .text() returns a string
  19833. // rather then the element.
  19834. (element = optionTemplate.clone())
  19835. .val(option.id)
  19836. .prop('selected', option.selected)
  19837. .text(option.label);
  19838. }
  19839. existingOptions.push(existingOption = {
  19840. element: element,
  19841. label: option.label,
  19842. id: option.id,
  19843. selected: option.selected
  19844. });
  19845. if (lastElement) {
  19846. lastElement.after(element);
  19847. } else {
  19848. existingParent.element.append(element);
  19849. }
  19850. lastElement = element;
  19851. }
  19852. }
  19853. // remove any excessive OPTIONs in a group
  19854. index++; // increment since the existingOptions[0] is parent element not OPTION
  19855. while(existingOptions.length > index) {
  19856. existingOptions.pop().element.remove();
  19857. }
  19858. }
  19859. // remove any excessive OPTGROUPs from select
  19860. while(optionGroupsCache.length > groupIndex) {
  19861. optionGroupsCache.pop()[0].element.remove();
  19862. }
  19863. }
  19864. }
  19865. }
  19866. };
  19867. }];
  19868. var optionDirective = ['$interpolate', function($interpolate) {
  19869. var nullSelectCtrl = {
  19870. addOption: noop,
  19871. removeOption: noop
  19872. };
  19873. return {
  19874. restrict: 'E',
  19875. priority: 100,
  19876. compile: function(element, attr) {
  19877. if (isUndefined(attr.value)) {
  19878. var interpolateFn = $interpolate(element.text(), true);
  19879. if (!interpolateFn) {
  19880. attr.$set('value', element.text());
  19881. }
  19882. }
  19883. return function (scope, element, attr) {
  19884. var selectCtrlName = '$selectController',
  19885. parent = element.parent(),
  19886. selectCtrl = parent.data(selectCtrlName) ||
  19887. parent.parent().data(selectCtrlName); // in case we are in optgroup
  19888. if (selectCtrl && selectCtrl.databound) {
  19889. // For some reason Opera defaults to true and if not overridden this messes up the repeater.
  19890. // We don't want the view to drive the initialization of the model anyway.
  19891. element.prop('selected', false);
  19892. } else {
  19893. selectCtrl = nullSelectCtrl;
  19894. }
  19895. if (interpolateFn) {
  19896. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  19897. attr.$set('value', newVal);
  19898. if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
  19899. selectCtrl.addOption(newVal);
  19900. });
  19901. } else {
  19902. selectCtrl.addOption(attr.value);
  19903. }
  19904. element.on('$destroy', function() {
  19905. selectCtrl.removeOption(attr.value);
  19906. });
  19907. };
  19908. }
  19909. };
  19910. }];
  19911. var styleDirective = valueFn({
  19912. restrict: 'E',
  19913. terminal: true
  19914. });
  19915. if (window.angular.bootstrap) {
  19916. //AngularJS is already loaded, so we can return here...
  19917. console.log('WARNING: Tried to load angular more than once.');
  19918. return;
  19919. }
  19920. //try to bind to jquery now so that one can write angular.element().read()
  19921. //but we will rebind on bootstrap again.
  19922. bindJQuery();
  19923. publishExternalAPI(angular);
  19924. jqLite(document).ready(function() {
  19925. angularInit(document, bootstrap);
  19926. });
  19927. })(window, document);
  19928. !window.angular.$$csp() && window.angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";[ng\\:cloak],[ng-cloak],[data-ng-cloak],[x-ng-cloak],.ng-cloak,.x-ng-cloak,.ng-hide{display:none !important;}ng\\:form{display:block;}.ng-animate-block-transitions{transition:0s all!important;-webkit-transition:0s all!important;}.ng-hide-add-active,.ng-hide-remove{display:block!important;}</style>');