angular.js 904 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584
  1. /**
  2. * @license AngularJS v1.3.0
  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. * @param {function} ErrorConstructor Custom error constructor to be instantiated when returning
  33. * error from returned function, for cases when a particular type of error is useful.
  34. * @returns {function(code:string, template:string, ...templateArgs): Error} minErr instance
  35. */
  36. function minErr(module, ErrorConstructor) {
  37. ErrorConstructor = ErrorConstructor || Error;
  38. return function () {
  39. var code = arguments[0],
  40. prefix = '[' + (module ? module + ':' : '') + code + '] ',
  41. template = arguments[1],
  42. templateArgs = arguments,
  43. stringify = function (obj) {
  44. if (typeof obj === 'function') {
  45. return obj.toString().replace(/ \{[\s\S]*$/, '');
  46. } else if (typeof obj === 'undefined') {
  47. return 'undefined';
  48. } else if (typeof obj !== 'string') {
  49. return JSON.stringify(obj);
  50. }
  51. return obj;
  52. },
  53. message, i;
  54. message = prefix + template.replace(/\{\d+\}/g, function (match) {
  55. var index = +match.slice(1, -1), arg;
  56. if (index + 2 < templateArgs.length) {
  57. arg = templateArgs[index + 2];
  58. if (typeof arg === 'function') {
  59. return arg.toString().replace(/ ?\{[\s\S]*$/, '');
  60. } else if (typeof arg === 'undefined') {
  61. return 'undefined';
  62. } else if (typeof arg !== 'string') {
  63. return toJson(arg);
  64. }
  65. return arg;
  66. }
  67. return match;
  68. });
  69. message = message + '\nhttp://errors.angularjs.org/1.3.0/' +
  70. (module ? module + '/' : '') + code;
  71. for (i = 2; i < arguments.length; i++) {
  72. message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
  73. encodeURIComponent(stringify(arguments[i]));
  74. }
  75. return new ErrorConstructor(message);
  76. };
  77. }
  78. /* We need to tell jshint what variables are being exported */
  79. /* global angular: true,
  80. msie: true,
  81. jqLite: true,
  82. jQuery: true,
  83. slice: true,
  84. splice: true,
  85. push: true,
  86. toString: true,
  87. ngMinErr: true,
  88. angularModule: true,
  89. uid: true,
  90. REGEX_STRING_REGEXP: true,
  91. VALIDITY_STATE_PROPERTY: true,
  92. lowercase: true,
  93. uppercase: true,
  94. manualLowercase: true,
  95. manualUppercase: true,
  96. nodeName_: true,
  97. isArrayLike: true,
  98. forEach: true,
  99. sortedKeys: true,
  100. forEachSorted: true,
  101. reverseParams: true,
  102. nextUid: true,
  103. setHashKey: true,
  104. extend: true,
  105. int: true,
  106. inherit: true,
  107. noop: true,
  108. identity: true,
  109. valueFn: true,
  110. isUndefined: true,
  111. isDefined: true,
  112. isObject: true,
  113. isString: true,
  114. isNumber: true,
  115. isDate: true,
  116. isArray: true,
  117. isFunction: true,
  118. isRegExp: true,
  119. isWindow: true,
  120. isScope: true,
  121. isFile: true,
  122. isBlob: true,
  123. isBoolean: true,
  124. isPromiseLike: true,
  125. trim: true,
  126. isElement: true,
  127. makeMap: true,
  128. size: true,
  129. includes: true,
  130. arrayRemove: true,
  131. isLeafNode: true,
  132. copy: true,
  133. shallowCopy: true,
  134. equals: true,
  135. csp: true,
  136. concat: true,
  137. sliceArgs: true,
  138. bind: true,
  139. toJsonReplacer: true,
  140. toJson: true,
  141. fromJson: true,
  142. startingTag: true,
  143. tryDecodeURIComponent: true,
  144. parseKeyValue: true,
  145. toKeyValue: true,
  146. encodeUriSegment: true,
  147. encodeUriQuery: true,
  148. angularInit: true,
  149. bootstrap: true,
  150. getTestability: true,
  151. snake_case: true,
  152. bindJQuery: true,
  153. assertArg: true,
  154. assertArgFn: true,
  155. assertNotHasOwnProperty: true,
  156. getter: true,
  157. getBlockNodes: true,
  158. hasOwnProperty: true,
  159. createMap: true,
  160. NODE_TYPE_ELEMENT: true,
  161. NODE_TYPE_TEXT: true,
  162. NODE_TYPE_COMMENT: true,
  163. NODE_TYPE_DOCUMENT: true,
  164. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  165. */
  166. ////////////////////////////////////
  167. /**
  168. * @ngdoc module
  169. * @name ng
  170. * @module ng
  171. * @description
  172. *
  173. * # ng (core module)
  174. * The ng module is loaded by default when an AngularJS application is started. The module itself
  175. * contains the essential components for an AngularJS application to function. The table below
  176. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  177. * components available within this core module.
  178. *
  179. * <div doc-module-components="ng"></div>
  180. */
  181. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  182. // The name of a form control's ValidityState property.
  183. // This is used so that it's possible for internal tests to create mock ValidityStates.
  184. var VALIDITY_STATE_PROPERTY = 'validity';
  185. /**
  186. * @ngdoc function
  187. * @name angular.lowercase
  188. * @module ng
  189. * @kind function
  190. *
  191. * @description Converts the specified string to lowercase.
  192. * @param {string} string String to be converted to lowercase.
  193. * @returns {string} Lowercased string.
  194. */
  195. var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
  196. var hasOwnProperty = Object.prototype.hasOwnProperty;
  197. /**
  198. * @ngdoc function
  199. * @name angular.uppercase
  200. * @module ng
  201. * @kind function
  202. *
  203. * @description Converts the specified string to uppercase.
  204. * @param {string} string String to be converted to uppercase.
  205. * @returns {string} Uppercased string.
  206. */
  207. var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
  208. var manualLowercase = function(s) {
  209. /* jshint bitwise: false */
  210. return isString(s)
  211. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  212. : s;
  213. };
  214. var manualUppercase = function(s) {
  215. /* jshint bitwise: false */
  216. return isString(s)
  217. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  218. : s;
  219. };
  220. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  221. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  222. // with correct but slower alternatives.
  223. if ('i' !== 'I'.toLowerCase()) {
  224. lowercase = manualLowercase;
  225. uppercase = manualUppercase;
  226. }
  227. var /** holds major version number for IE or NaN for real browsers */
  228. msie,
  229. jqLite, // delay binding since jQuery could be loaded after us.
  230. jQuery, // delay binding
  231. slice = [].slice,
  232. splice = [].splice,
  233. push = [].push,
  234. toString = Object.prototype.toString,
  235. ngMinErr = minErr('ng'),
  236. /** @name angular */
  237. angular = window.angular || (window.angular = {}),
  238. angularModule,
  239. uid = 0;
  240. /**
  241. * documentMode is an IE-only property
  242. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  243. */
  244. msie = document.documentMode;
  245. /**
  246. * @private
  247. * @param {*} obj
  248. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  249. * String ...)
  250. */
  251. function isArrayLike(obj) {
  252. if (obj == null || isWindow(obj)) {
  253. return false;
  254. }
  255. var length = obj.length;
  256. if (obj.nodeType === NODE_TYPE_ELEMENT && length) {
  257. return true;
  258. }
  259. return isString(obj) || isArray(obj) || length === 0 ||
  260. typeof length === 'number' && length > 0 && (length - 1) in obj;
  261. }
  262. /**
  263. * @ngdoc function
  264. * @name angular.forEach
  265. * @module ng
  266. * @kind function
  267. *
  268. * @description
  269. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  270. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  271. * is the value of an object property or an array element, `key` is the object property key or
  272. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  273. *
  274. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  275. * using the `hasOwnProperty` method.
  276. *
  277. ```js
  278. var values = {name: 'misko', gender: 'male'};
  279. var log = [];
  280. angular.forEach(values, function(value, key) {
  281. this.push(key + ': ' + value);
  282. }, log);
  283. expect(log).toEqual(['name: misko', 'gender: male']);
  284. ```
  285. *
  286. * @param {Object|Array} obj Object to iterate over.
  287. * @param {Function} iterator Iterator function.
  288. * @param {Object=} context Object to become context (`this`) for the iterator function.
  289. * @returns {Object|Array} Reference to `obj`.
  290. */
  291. function forEach(obj, iterator, context) {
  292. var key, length;
  293. if (obj) {
  294. if (isFunction(obj)) {
  295. for (key in obj) {
  296. // Need to check if hasOwnProperty exists,
  297. // as on IE8 the result of querySelectorAll is an object without a hasOwnProperty function
  298. if (key != 'prototype' && key != 'length' && key != 'name' && (!obj.hasOwnProperty || obj.hasOwnProperty(key))) {
  299. iterator.call(context, obj[key], key, obj);
  300. }
  301. }
  302. } else if (isArray(obj) || isArrayLike(obj)) {
  303. var isPrimitive = typeof obj !== 'object';
  304. for (key = 0, length = obj.length; key < length; key++) {
  305. if (isPrimitive || key in obj) {
  306. iterator.call(context, obj[key], key, obj);
  307. }
  308. }
  309. } else if (obj.forEach && obj.forEach !== forEach) {
  310. obj.forEach(iterator, context, obj);
  311. } else {
  312. for (key in obj) {
  313. if (obj.hasOwnProperty(key)) {
  314. iterator.call(context, obj[key], key, obj);
  315. }
  316. }
  317. }
  318. }
  319. return obj;
  320. }
  321. function sortedKeys(obj) {
  322. var keys = [];
  323. for (var key in obj) {
  324. if (obj.hasOwnProperty(key)) {
  325. keys.push(key);
  326. }
  327. }
  328. return keys.sort();
  329. }
  330. function forEachSorted(obj, iterator, context) {
  331. var keys = sortedKeys(obj);
  332. for ( var i = 0; i < keys.length; i++) {
  333. iterator.call(context, obj[keys[i]], keys[i]);
  334. }
  335. return keys;
  336. }
  337. /**
  338. * when using forEach the params are value, key, but it is often useful to have key, value.
  339. * @param {function(string, *)} iteratorFn
  340. * @returns {function(*, string)}
  341. */
  342. function reverseParams(iteratorFn) {
  343. return function(value, key) { iteratorFn(key, value); };
  344. }
  345. /**
  346. * A consistent way of creating unique IDs in angular.
  347. *
  348. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  349. * we hit number precision issues in JavaScript.
  350. *
  351. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  352. *
  353. * @returns {number} an unique alpha-numeric string
  354. */
  355. function nextUid() {
  356. return ++uid;
  357. }
  358. /**
  359. * Set or clear the hashkey for an object.
  360. * @param obj object
  361. * @param h the hashkey (!truthy to delete the hashkey)
  362. */
  363. function setHashKey(obj, h) {
  364. if (h) {
  365. obj.$$hashKey = h;
  366. }
  367. else {
  368. delete obj.$$hashKey;
  369. }
  370. }
  371. /**
  372. * @ngdoc function
  373. * @name angular.extend
  374. * @module ng
  375. * @kind function
  376. *
  377. * @description
  378. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  379. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  380. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  381. *
  382. * @param {Object} dst Destination object.
  383. * @param {...Object} src Source object(s).
  384. * @returns {Object} Reference to `dst`.
  385. */
  386. function extend(dst) {
  387. var h = dst.$$hashKey;
  388. for (var i = 1, ii = arguments.length; i < ii; i++) {
  389. var obj = arguments[i];
  390. if (obj) {
  391. var keys = Object.keys(obj);
  392. for (var j = 0, jj = keys.length; j < jj; j++) {
  393. var key = keys[j];
  394. dst[key] = obj[key];
  395. }
  396. }
  397. }
  398. setHashKey(dst, h);
  399. return dst;
  400. }
  401. function int(str) {
  402. return parseInt(str, 10);
  403. }
  404. function inherit(parent, extra) {
  405. return extend(new (extend(function() {}, {prototype:parent}))(), extra);
  406. }
  407. /**
  408. * @ngdoc function
  409. * @name angular.noop
  410. * @module ng
  411. * @kind function
  412. *
  413. * @description
  414. * A function that performs no operations. This function can be useful when writing code in the
  415. * functional style.
  416. ```js
  417. function foo(callback) {
  418. var result = calculateResult();
  419. (callback || angular.noop)(result);
  420. }
  421. ```
  422. */
  423. function noop() {}
  424. noop.$inject = [];
  425. /**
  426. * @ngdoc function
  427. * @name angular.identity
  428. * @module ng
  429. * @kind function
  430. *
  431. * @description
  432. * A function that returns its first argument. This function is useful when writing code in the
  433. * functional style.
  434. *
  435. ```js
  436. function transformer(transformationFn, value) {
  437. return (transformationFn || angular.identity)(value);
  438. };
  439. ```
  440. */
  441. function identity($) {return $;}
  442. identity.$inject = [];
  443. function valueFn(value) {return function() {return value;};}
  444. /**
  445. * @ngdoc function
  446. * @name angular.isUndefined
  447. * @module ng
  448. * @kind function
  449. *
  450. * @description
  451. * Determines if a reference is undefined.
  452. *
  453. * @param {*} value Reference to check.
  454. * @returns {boolean} True if `value` is undefined.
  455. */
  456. function isUndefined(value){return typeof value === 'undefined';}
  457. /**
  458. * @ngdoc function
  459. * @name angular.isDefined
  460. * @module ng
  461. * @kind function
  462. *
  463. * @description
  464. * Determines if a reference is defined.
  465. *
  466. * @param {*} value Reference to check.
  467. * @returns {boolean} True if `value` is defined.
  468. */
  469. function isDefined(value){return typeof value !== 'undefined';}
  470. /**
  471. * @ngdoc function
  472. * @name angular.isObject
  473. * @module ng
  474. * @kind function
  475. *
  476. * @description
  477. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  478. * considered to be objects. Note that JavaScript arrays are objects.
  479. *
  480. * @param {*} value Reference to check.
  481. * @returns {boolean} True if `value` is an `Object` but not `null`.
  482. */
  483. function isObject(value){
  484. // http://jsperf.com/isobject4
  485. return value !== null && typeof value === 'object';
  486. }
  487. /**
  488. * @ngdoc function
  489. * @name angular.isString
  490. * @module ng
  491. * @kind function
  492. *
  493. * @description
  494. * Determines if a reference is a `String`.
  495. *
  496. * @param {*} value Reference to check.
  497. * @returns {boolean} True if `value` is a `String`.
  498. */
  499. function isString(value){return typeof value === 'string';}
  500. /**
  501. * @ngdoc function
  502. * @name angular.isNumber
  503. * @module ng
  504. * @kind function
  505. *
  506. * @description
  507. * Determines if a reference is a `Number`.
  508. *
  509. * @param {*} value Reference to check.
  510. * @returns {boolean} True if `value` is a `Number`.
  511. */
  512. function isNumber(value){return typeof value === 'number';}
  513. /**
  514. * @ngdoc function
  515. * @name angular.isDate
  516. * @module ng
  517. * @kind function
  518. *
  519. * @description
  520. * Determines if a value is a date.
  521. *
  522. * @param {*} value Reference to check.
  523. * @returns {boolean} True if `value` is a `Date`.
  524. */
  525. function isDate(value) {
  526. return toString.call(value) === '[object Date]';
  527. }
  528. /**
  529. * @ngdoc function
  530. * @name angular.isArray
  531. * @module ng
  532. * @kind function
  533. *
  534. * @description
  535. * Determines if a reference is an `Array`.
  536. *
  537. * @param {*} value Reference to check.
  538. * @returns {boolean} True if `value` is an `Array`.
  539. */
  540. var isArray = Array.isArray;
  541. /**
  542. * @ngdoc function
  543. * @name angular.isFunction
  544. * @module ng
  545. * @kind function
  546. *
  547. * @description
  548. * Determines if a reference is a `Function`.
  549. *
  550. * @param {*} value Reference to check.
  551. * @returns {boolean} True if `value` is a `Function`.
  552. */
  553. function isFunction(value){return typeof value === 'function';}
  554. /**
  555. * Determines if a value is a regular expression object.
  556. *
  557. * @private
  558. * @param {*} value Reference to check.
  559. * @returns {boolean} True if `value` is a `RegExp`.
  560. */
  561. function isRegExp(value) {
  562. return toString.call(value) === '[object RegExp]';
  563. }
  564. /**
  565. * Checks if `obj` is a window object.
  566. *
  567. * @private
  568. * @param {*} obj Object to check
  569. * @returns {boolean} True if `obj` is a window obj.
  570. */
  571. function isWindow(obj) {
  572. return obj && obj.window === obj;
  573. }
  574. function isScope(obj) {
  575. return obj && obj.$evalAsync && obj.$watch;
  576. }
  577. function isFile(obj) {
  578. return toString.call(obj) === '[object File]';
  579. }
  580. function isBlob(obj) {
  581. return toString.call(obj) === '[object Blob]';
  582. }
  583. function isBoolean(value) {
  584. return typeof value === 'boolean';
  585. }
  586. function isPromiseLike(obj) {
  587. return obj && isFunction(obj.then);
  588. }
  589. var trim = function(value) {
  590. return isString(value) ? value.trim() : value;
  591. };
  592. /**
  593. * @ngdoc function
  594. * @name angular.isElement
  595. * @module ng
  596. * @kind function
  597. *
  598. * @description
  599. * Determines if a reference is a DOM element (or wrapped jQuery element).
  600. *
  601. * @param {*} value Reference to check.
  602. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  603. */
  604. function isElement(node) {
  605. return !!(node &&
  606. (node.nodeName // we are a direct element
  607. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  608. }
  609. /**
  610. * @param str 'key1,key2,...'
  611. * @returns {object} in the form of {key1:true, key2:true, ...}
  612. */
  613. function makeMap(str) {
  614. var obj = {}, items = str.split(","), i;
  615. for ( i = 0; i < items.length; i++ )
  616. obj[ items[i] ] = true;
  617. return obj;
  618. }
  619. function nodeName_(element) {
  620. return lowercase(element.nodeName || element[0].nodeName);
  621. }
  622. /**
  623. * @description
  624. * Determines the number of elements in an array, the number of properties an object has, or
  625. * the length of a string.
  626. *
  627. * Note: This function is used to augment the Object type in Angular expressions. See
  628. * {@link angular.Object} for more information about Angular arrays.
  629. *
  630. * @param {Object|Array|string} obj Object, array, or string to inspect.
  631. * @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
  632. * @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
  633. */
  634. function size(obj, ownPropsOnly) {
  635. var count = 0, key;
  636. if (isArray(obj) || isString(obj)) {
  637. return obj.length;
  638. } else if (isObject(obj)) {
  639. for (key in obj)
  640. if (!ownPropsOnly || obj.hasOwnProperty(key))
  641. count++;
  642. }
  643. return count;
  644. }
  645. function includes(array, obj) {
  646. return Array.prototype.indexOf.call(array, obj) != -1;
  647. }
  648. function arrayRemove(array, value) {
  649. var index = array.indexOf(value);
  650. if (index >=0)
  651. array.splice(index, 1);
  652. return value;
  653. }
  654. function isLeafNode (node) {
  655. if (node) {
  656. switch (nodeName_(node)) {
  657. case "option":
  658. case "pre":
  659. case "title":
  660. return true;
  661. }
  662. }
  663. return false;
  664. }
  665. /**
  666. * @ngdoc function
  667. * @name angular.copy
  668. * @module ng
  669. * @kind function
  670. *
  671. * @description
  672. * Creates a deep copy of `source`, which should be an object or an array.
  673. *
  674. * * If no destination is supplied, a copy of the object or array is created.
  675. * * If a destination is provided, all of its elements (for array) or properties (for objects)
  676. * are deleted and then all elements/properties from the source are copied to it.
  677. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  678. * * If `source` is identical to 'destination' an exception will be thrown.
  679. *
  680. * @param {*} source The source that will be used to make a copy.
  681. * Can be any type, including primitives, `null`, and `undefined`.
  682. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  683. * provided, must be of the same type as `source`.
  684. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  685. *
  686. * @example
  687. <example module="copyExample">
  688. <file name="index.html">
  689. <div ng-controller="ExampleController">
  690. <form novalidate class="simple-form">
  691. Name: <input type="text" ng-model="user.name" /><br />
  692. E-mail: <input type="email" ng-model="user.email" /><br />
  693. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  694. <input type="radio" ng-model="user.gender" value="female" />female<br />
  695. <button ng-click="reset()">RESET</button>
  696. <button ng-click="update(user)">SAVE</button>
  697. </form>
  698. <pre>form = {{user | json}}</pre>
  699. <pre>master = {{master | json}}</pre>
  700. </div>
  701. <script>
  702. angular.module('copyExample', [])
  703. .controller('ExampleController', ['$scope', function($scope) {
  704. $scope.master= {};
  705. $scope.update = function(user) {
  706. // Example with 1 argument
  707. $scope.master= angular.copy(user);
  708. };
  709. $scope.reset = function() {
  710. // Example with 2 arguments
  711. angular.copy($scope.master, $scope.user);
  712. };
  713. $scope.reset();
  714. }]);
  715. </script>
  716. </file>
  717. </example>
  718. */
  719. function copy(source, destination, stackSource, stackDest) {
  720. if (isWindow(source) || isScope(source)) {
  721. throw ngMinErr('cpws',
  722. "Can't copy! Making copies of Window or Scope instances is not supported.");
  723. }
  724. if (!destination) {
  725. destination = source;
  726. if (source) {
  727. if (isArray(source)) {
  728. destination = copy(source, [], stackSource, stackDest);
  729. } else if (isDate(source)) {
  730. destination = new Date(source.getTime());
  731. } else if (isRegExp(source)) {
  732. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  733. destination.lastIndex = source.lastIndex;
  734. } else if (isObject(source)) {
  735. var emptyObject = Object.create(Object.getPrototypeOf(source));
  736. destination = copy(source, emptyObject, stackSource, stackDest);
  737. }
  738. }
  739. } else {
  740. if (source === destination) throw ngMinErr('cpi',
  741. "Can't copy! Source and destination are identical.");
  742. stackSource = stackSource || [];
  743. stackDest = stackDest || [];
  744. if (isObject(source)) {
  745. var index = stackSource.indexOf(source);
  746. if (index !== -1) return stackDest[index];
  747. stackSource.push(source);
  748. stackDest.push(destination);
  749. }
  750. var result;
  751. if (isArray(source)) {
  752. destination.length = 0;
  753. for ( var i = 0; i < source.length; i++) {
  754. result = copy(source[i], null, stackSource, stackDest);
  755. if (isObject(source[i])) {
  756. stackSource.push(source[i]);
  757. stackDest.push(result);
  758. }
  759. destination.push(result);
  760. }
  761. } else {
  762. var h = destination.$$hashKey;
  763. if (isArray(destination)) {
  764. destination.length = 0;
  765. } else {
  766. forEach(destination, function(value, key) {
  767. delete destination[key];
  768. });
  769. }
  770. for ( var key in source) {
  771. if(source.hasOwnProperty(key)) {
  772. result = copy(source[key], null, stackSource, stackDest);
  773. if (isObject(source[key])) {
  774. stackSource.push(source[key]);
  775. stackDest.push(result);
  776. }
  777. destination[key] = result;
  778. }
  779. }
  780. setHashKey(destination,h);
  781. }
  782. }
  783. return destination;
  784. }
  785. /**
  786. * Creates a shallow copy of an object, an array or a primitive.
  787. *
  788. * Assumes that there are no proto properties for objects.
  789. */
  790. function shallowCopy(src, dst) {
  791. if (isArray(src)) {
  792. dst = dst || [];
  793. for (var i = 0, ii = src.length; i < ii; i++) {
  794. dst[i] = src[i];
  795. }
  796. } else if (isObject(src)) {
  797. dst = dst || {};
  798. for (var key in src) {
  799. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  800. dst[key] = src[key];
  801. }
  802. }
  803. }
  804. return dst || src;
  805. }
  806. /**
  807. * @ngdoc function
  808. * @name angular.equals
  809. * @module ng
  810. * @kind function
  811. *
  812. * @description
  813. * Determines if two objects or two values are equivalent. Supports value types, regular
  814. * expressions, arrays and objects.
  815. *
  816. * Two objects or values are considered equivalent if at least one of the following is true:
  817. *
  818. * * Both objects or values pass `===` comparison.
  819. * * Both objects or values are of the same type and all of their properties are equal by
  820. * comparing them with `angular.equals`.
  821. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  822. * * Both values represent the same regular expression (In JavaScript,
  823. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  824. * representation matches).
  825. *
  826. * During a property comparison, properties of `function` type and properties with names
  827. * that begin with `$` are ignored.
  828. *
  829. * Scope and DOMWindow objects are being compared only by identify (`===`).
  830. *
  831. * @param {*} o1 Object or value to compare.
  832. * @param {*} o2 Object or value to compare.
  833. * @returns {boolean} True if arguments are equal.
  834. */
  835. function equals(o1, o2) {
  836. if (o1 === o2) return true;
  837. if (o1 === null || o2 === null) return false;
  838. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  839. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  840. if (t1 == t2) {
  841. if (t1 == 'object') {
  842. if (isArray(o1)) {
  843. if (!isArray(o2)) return false;
  844. if ((length = o1.length) == o2.length) {
  845. for(key=0; key<length; key++) {
  846. if (!equals(o1[key], o2[key])) return false;
  847. }
  848. return true;
  849. }
  850. } else if (isDate(o1)) {
  851. if (!isDate(o2)) return false;
  852. return equals(o1.getTime(), o2.getTime());
  853. } else if (isRegExp(o1) && isRegExp(o2)) {
  854. return o1.toString() == o2.toString();
  855. } else {
  856. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
  857. keySet = {};
  858. for(key in o1) {
  859. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  860. if (!equals(o1[key], o2[key])) return false;
  861. keySet[key] = true;
  862. }
  863. for(key in o2) {
  864. if (!keySet.hasOwnProperty(key) &&
  865. key.charAt(0) !== '$' &&
  866. o2[key] !== undefined &&
  867. !isFunction(o2[key])) return false;
  868. }
  869. return true;
  870. }
  871. }
  872. }
  873. return false;
  874. }
  875. var csp = function() {
  876. if (isDefined(csp.isActive_)) return csp.isActive_;
  877. var active = !!(document.querySelector('[ng-csp]') ||
  878. document.querySelector('[data-ng-csp]'));
  879. if (!active) {
  880. try {
  881. /* jshint -W031, -W054 */
  882. new Function('');
  883. /* jshint +W031, +W054 */
  884. } catch (e) {
  885. active = true;
  886. }
  887. }
  888. return (csp.isActive_ = active);
  889. };
  890. function concat(array1, array2, index) {
  891. return array1.concat(slice.call(array2, index));
  892. }
  893. function sliceArgs(args, startIndex) {
  894. return slice.call(args, startIndex || 0);
  895. }
  896. /* jshint -W101 */
  897. /**
  898. * @ngdoc function
  899. * @name angular.bind
  900. * @module ng
  901. * @kind function
  902. *
  903. * @description
  904. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  905. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  906. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  907. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  908. *
  909. * @param {Object} self Context which `fn` should be evaluated in.
  910. * @param {function()} fn Function to be bound.
  911. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  912. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  913. */
  914. /* jshint +W101 */
  915. function bind(self, fn) {
  916. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  917. if (isFunction(fn) && !(fn instanceof RegExp)) {
  918. return curryArgs.length
  919. ? function() {
  920. return arguments.length
  921. ? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
  922. : fn.apply(self, curryArgs);
  923. }
  924. : function() {
  925. return arguments.length
  926. ? fn.apply(self, arguments)
  927. : fn.call(self);
  928. };
  929. } else {
  930. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  931. return fn;
  932. }
  933. }
  934. function toJsonReplacer(key, value) {
  935. var val = value;
  936. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  937. val = undefined;
  938. } else if (isWindow(value)) {
  939. val = '$WINDOW';
  940. } else if (value && document === value) {
  941. val = '$DOCUMENT';
  942. } else if (isScope(value)) {
  943. val = '$SCOPE';
  944. }
  945. return val;
  946. }
  947. /**
  948. * @ngdoc function
  949. * @name angular.toJson
  950. * @module ng
  951. * @kind function
  952. *
  953. * @description
  954. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  955. * stripped since angular uses this notation internally.
  956. *
  957. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  958. * @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
  959. * @returns {string|undefined} JSON-ified string representing `obj`.
  960. */
  961. function toJson(obj, pretty) {
  962. if (typeof obj === 'undefined') return undefined;
  963. return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
  964. }
  965. /**
  966. * @ngdoc function
  967. * @name angular.fromJson
  968. * @module ng
  969. * @kind function
  970. *
  971. * @description
  972. * Deserializes a JSON string.
  973. *
  974. * @param {string} json JSON string to deserialize.
  975. * @returns {Object|Array|string|number} Deserialized thingy.
  976. */
  977. function fromJson(json) {
  978. return isString(json)
  979. ? JSON.parse(json)
  980. : json;
  981. }
  982. /**
  983. * @returns {string} Returns the string representation of the element.
  984. */
  985. function startingTag(element) {
  986. element = jqLite(element).clone();
  987. try {
  988. // turns out IE does not let you set .html() on elements which
  989. // are not allowed to have children. So we just ignore it.
  990. element.empty();
  991. } catch(e) {}
  992. var elemHtml = jqLite('<div>').append(element).html();
  993. try {
  994. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  995. elemHtml.
  996. match(/^(<[^>]+>)/)[1].
  997. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  998. } catch(e) {
  999. return lowercase(elemHtml);
  1000. }
  1001. }
  1002. /////////////////////////////////////////////////
  1003. /**
  1004. * Tries to decode the URI component without throwing an exception.
  1005. *
  1006. * @private
  1007. * @param str value potential URI component to check.
  1008. * @returns {boolean} True if `value` can be decoded
  1009. * with the decodeURIComponent function.
  1010. */
  1011. function tryDecodeURIComponent(value) {
  1012. try {
  1013. return decodeURIComponent(value);
  1014. } catch(e) {
  1015. // Ignore any invalid uri component
  1016. }
  1017. }
  1018. /**
  1019. * Parses an escaped url query string into key-value pairs.
  1020. * @returns {Object.<string,boolean|Array>}
  1021. */
  1022. function parseKeyValue(/**string*/keyValue) {
  1023. var obj = {}, key_value, key;
  1024. forEach((keyValue || "").split('&'), function(keyValue) {
  1025. if ( keyValue ) {
  1026. key_value = keyValue.replace(/\+/g,'%20').split('=');
  1027. key = tryDecodeURIComponent(key_value[0]);
  1028. if ( isDefined(key) ) {
  1029. var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
  1030. if (!hasOwnProperty.call(obj, key)) {
  1031. obj[key] = val;
  1032. } else if(isArray(obj[key])) {
  1033. obj[key].push(val);
  1034. } else {
  1035. obj[key] = [obj[key],val];
  1036. }
  1037. }
  1038. }
  1039. });
  1040. return obj;
  1041. }
  1042. function toKeyValue(obj) {
  1043. var parts = [];
  1044. forEach(obj, function(value, key) {
  1045. if (isArray(value)) {
  1046. forEach(value, function(arrayValue) {
  1047. parts.push(encodeUriQuery(key, true) +
  1048. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1049. });
  1050. } else {
  1051. parts.push(encodeUriQuery(key, true) +
  1052. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1053. }
  1054. });
  1055. return parts.length ? parts.join('&') : '';
  1056. }
  1057. /**
  1058. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1059. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1060. * segments:
  1061. * segment = *pchar
  1062. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1063. * pct-encoded = "%" HEXDIG HEXDIG
  1064. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1065. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1066. * / "*" / "+" / "," / ";" / "="
  1067. */
  1068. function encodeUriSegment(val) {
  1069. return encodeUriQuery(val, true).
  1070. replace(/%26/gi, '&').
  1071. replace(/%3D/gi, '=').
  1072. replace(/%2B/gi, '+');
  1073. }
  1074. /**
  1075. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1076. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1077. * encoded per http://tools.ietf.org/html/rfc3986:
  1078. * query = *( pchar / "/" / "?" )
  1079. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1080. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1081. * pct-encoded = "%" HEXDIG HEXDIG
  1082. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1083. * / "*" / "+" / "," / ";" / "="
  1084. */
  1085. function encodeUriQuery(val, pctEncodeSpaces) {
  1086. return encodeURIComponent(val).
  1087. replace(/%40/gi, '@').
  1088. replace(/%3A/gi, ':').
  1089. replace(/%24/g, '$').
  1090. replace(/%2C/gi, ',').
  1091. replace(/%3B/gi, ';').
  1092. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1093. }
  1094. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1095. function getNgAttribute(element, ngAttr) {
  1096. var attr, i, ii = ngAttrPrefixes.length;
  1097. element = jqLite(element);
  1098. for (i=0; i<ii; ++i) {
  1099. attr = ngAttrPrefixes[i] + ngAttr;
  1100. if (isString(attr = element.attr(attr))) {
  1101. return attr;
  1102. }
  1103. }
  1104. return null;
  1105. }
  1106. /**
  1107. * @ngdoc directive
  1108. * @name ngApp
  1109. * @module ng
  1110. *
  1111. * @element ANY
  1112. * @param {angular.Module} ngApp an optional application
  1113. * {@link angular.module module} name to load.
  1114. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1115. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1116. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1117. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1118. * tracking down the root of these bugs.
  1119. *
  1120. * @description
  1121. *
  1122. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1123. * designates the **root element** of the application and is typically placed near the root element
  1124. * of the page - e.g. on the `<body>` or `<html>` tags.
  1125. *
  1126. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1127. * found in the document will be used to define the root element to auto-bootstrap as an
  1128. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1129. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1130. *
  1131. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1132. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped and
  1133. * should contain the application code needed or have dependencies on other modules that will
  1134. * contain the code. See {@link angular.module} for more information.
  1135. *
  1136. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1137. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1138. * would not be resolved to `3`.
  1139. *
  1140. * `ngApp` is the easiest, and most common, way to bootstrap an application.
  1141. *
  1142. <example module="ngAppDemo">
  1143. <file name="index.html">
  1144. <div ng-controller="ngAppDemoController">
  1145. I can add: {{a}} + {{b}} = {{ a+b }}
  1146. </div>
  1147. </file>
  1148. <file name="script.js">
  1149. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1150. $scope.a = 1;
  1151. $scope.b = 2;
  1152. });
  1153. </file>
  1154. </example>
  1155. *
  1156. * Using `ngStrictDi`, you would see something like this:
  1157. *
  1158. <example ng-app-included="true">
  1159. <file name="index.html">
  1160. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1161. <div ng-controller="GoodController1">
  1162. I can add: {{a}} + {{b}} = {{ a+b }}
  1163. <p>This renders because the controller does not fail to
  1164. instantiate, by using explicit annotation style (see
  1165. script.js for details)
  1166. </p>
  1167. </div>
  1168. <div ng-controller="GoodController2">
  1169. Name: <input ng-model="name"><br />
  1170. Hello, {{name}}!
  1171. <p>This renders because the controller does not fail to
  1172. instantiate, by using explicit annotation style
  1173. (see script.js for details)
  1174. </p>
  1175. </div>
  1176. <div ng-controller="BadController">
  1177. I can add: {{a}} + {{b}} = {{ a+b }}
  1178. <p>The controller could not be instantiated, due to relying
  1179. on automatic function annotations (which are disabled in
  1180. strict mode). As such, the content of this section is not
  1181. interpolated, and there should be an error in your web console.
  1182. </p>
  1183. </div>
  1184. </div>
  1185. </file>
  1186. <file name="script.js">
  1187. angular.module('ngAppStrictDemo', [])
  1188. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1189. // rather than an explicit annotation
  1190. .controller('BadController', function($scope) {
  1191. $scope.a = 1;
  1192. $scope.b = 2;
  1193. })
  1194. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1195. // due to using explicit annotations using the array style and $inject property, respectively.
  1196. .controller('GoodController1', ['$scope', function($scope) {
  1197. $scope.a = 1;
  1198. $scope.b = 2;
  1199. }])
  1200. .controller('GoodController2', GoodController2);
  1201. function GoodController2($scope) {
  1202. $scope.name = "World";
  1203. }
  1204. GoodController2.$inject = ['$scope'];
  1205. </file>
  1206. <file name="style.css">
  1207. div[ng-controller] {
  1208. margin-bottom: 1em;
  1209. -webkit-border-radius: 4px;
  1210. border-radius: 4px;
  1211. border: 1px solid;
  1212. padding: .5em;
  1213. }
  1214. div[ng-controller^=Good] {
  1215. border-color: #d6e9c6;
  1216. background-color: #dff0d8;
  1217. color: #3c763d;
  1218. }
  1219. div[ng-controller^=Bad] {
  1220. border-color: #ebccd1;
  1221. background-color: #f2dede;
  1222. color: #a94442;
  1223. margin-bottom: 0;
  1224. }
  1225. </file>
  1226. </example>
  1227. */
  1228. function angularInit(element, bootstrap) {
  1229. var appElement,
  1230. module,
  1231. config = {};
  1232. // The element `element` has priority over any other element
  1233. forEach(ngAttrPrefixes, function(prefix) {
  1234. var name = prefix + 'app';
  1235. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1236. appElement = element;
  1237. module = element.getAttribute(name);
  1238. }
  1239. });
  1240. forEach(ngAttrPrefixes, function(prefix) {
  1241. var name = prefix + 'app';
  1242. var candidate;
  1243. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1244. appElement = candidate;
  1245. module = candidate.getAttribute(name);
  1246. }
  1247. });
  1248. if (appElement) {
  1249. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1250. bootstrap(appElement, module ? [module] : [], config);
  1251. }
  1252. }
  1253. /**
  1254. * @ngdoc function
  1255. * @name angular.bootstrap
  1256. * @module ng
  1257. * @description
  1258. * Use this function to manually start up angular application.
  1259. *
  1260. * See: {@link guide/bootstrap Bootstrap}
  1261. *
  1262. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1263. * They must use {@link ng.directive:ngApp ngApp}.
  1264. *
  1265. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1266. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1267. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1268. * multiple instances of Angular try to work on the DOM.
  1269. *
  1270. * ```html
  1271. * <!doctype html>
  1272. * <html>
  1273. * <body>
  1274. * <div ng-controller="WelcomeController">
  1275. * {{greeting}}
  1276. * </div>
  1277. *
  1278. * <script src="angular.js"></script>
  1279. * <script>
  1280. * var app = angular.module('demo', [])
  1281. * .controller('WelcomeController', function($scope) {
  1282. * $scope.greeting = 'Welcome!';
  1283. * });
  1284. * angular.bootstrap(document, ['demo']);
  1285. * </script>
  1286. * </body>
  1287. * </html>
  1288. * ```
  1289. *
  1290. * @param {DOMElement} element DOM element which is the root of angular application.
  1291. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1292. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1293. * function that will be invoked by the injector as a run block.
  1294. * See: {@link angular.module modules}
  1295. * @param {Object=} config an object for defining configuration options for the application. The
  1296. * following keys are supported:
  1297. *
  1298. * - `strictDi`: disable automatic function annotation for the application. This is meant to
  1299. * assist in finding bugs which break minified code.
  1300. *
  1301. * @returns {auto.$injector} Returns the newly created injector for this app.
  1302. */
  1303. function bootstrap(element, modules, config) {
  1304. if (!isObject(config)) config = {};
  1305. var defaultConfig = {
  1306. strictDi: false
  1307. };
  1308. config = extend(defaultConfig, config);
  1309. var doBootstrap = function() {
  1310. element = jqLite(element);
  1311. if (element.injector()) {
  1312. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1313. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1314. throw ngMinErr(
  1315. 'btstrpd',
  1316. "App Already Bootstrapped with this Element '{0}'",
  1317. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1318. }
  1319. modules = modules || [];
  1320. modules.unshift(['$provide', function($provide) {
  1321. $provide.value('$rootElement', element);
  1322. }]);
  1323. if (config.debugInfoEnabled) {
  1324. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1325. modules.push(['$compileProvider', function($compileProvider) {
  1326. $compileProvider.debugInfoEnabled(true);
  1327. }]);
  1328. }
  1329. modules.unshift('ng');
  1330. var injector = createInjector(modules, config.strictDi);
  1331. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1332. function bootstrapApply(scope, element, compile, injector) {
  1333. scope.$apply(function() {
  1334. element.data('$injector', injector);
  1335. compile(element)(scope);
  1336. });
  1337. }]
  1338. );
  1339. return injector;
  1340. };
  1341. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1342. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1343. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1344. config.debugInfoEnabled = true;
  1345. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1346. }
  1347. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1348. return doBootstrap();
  1349. }
  1350. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1351. angular.resumeBootstrap = function(extraModules) {
  1352. forEach(extraModules, function(module) {
  1353. modules.push(module);
  1354. });
  1355. doBootstrap();
  1356. };
  1357. }
  1358. /**
  1359. * @ngdoc function
  1360. * @name angular.reloadWithDebugInfo
  1361. * @module ng
  1362. * @description
  1363. * Use this function to reload the current application with debug information turned on.
  1364. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1365. *
  1366. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1367. */
  1368. function reloadWithDebugInfo() {
  1369. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1370. window.location.reload();
  1371. }
  1372. /**
  1373. * @name angular.getTestability
  1374. * @module ng
  1375. * @description
  1376. * Get the testability service for the instance of Angular on the given
  1377. * element.
  1378. * @param {DOMElement} element DOM element which is the root of angular application.
  1379. */
  1380. function getTestability(rootElement) {
  1381. return angular.element(rootElement).injector().get('$$testability');
  1382. }
  1383. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1384. function snake_case(name, separator) {
  1385. separator = separator || '_';
  1386. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1387. return (pos ? separator : '') + letter.toLowerCase();
  1388. });
  1389. }
  1390. var bindJQueryFired = false;
  1391. var skipDestroyOnNextJQueryCleanData;
  1392. function bindJQuery() {
  1393. var originalCleanData;
  1394. if (bindJQueryFired) {
  1395. return;
  1396. }
  1397. // bind to jQuery if present;
  1398. jQuery = window.jQuery;
  1399. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1400. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1401. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1402. // versions. It will not work for sure with jQuery <1.7, though.
  1403. if (jQuery && jQuery.fn.on) {
  1404. jqLite = jQuery;
  1405. extend(jQuery.fn, {
  1406. scope: JQLitePrototype.scope,
  1407. isolateScope: JQLitePrototype.isolateScope,
  1408. controller: JQLitePrototype.controller,
  1409. injector: JQLitePrototype.injector,
  1410. inheritedData: JQLitePrototype.inheritedData
  1411. });
  1412. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1413. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1414. // the $destroy event on all removed nodes.
  1415. originalCleanData = jQuery.cleanData;
  1416. jQuery.cleanData = function(elems) {
  1417. var events;
  1418. if (!skipDestroyOnNextJQueryCleanData) {
  1419. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1420. events = jQuery._data(elem, "events");
  1421. if (events && events.$destroy) {
  1422. jQuery(elem).triggerHandler('$destroy');
  1423. }
  1424. }
  1425. } else {
  1426. skipDestroyOnNextJQueryCleanData = false;
  1427. }
  1428. originalCleanData(elems);
  1429. };
  1430. } else {
  1431. jqLite = JQLite;
  1432. }
  1433. angular.element = jqLite;
  1434. // Prevent double-proxying.
  1435. bindJQueryFired = true;
  1436. }
  1437. /**
  1438. * throw error if the argument is falsy.
  1439. */
  1440. function assertArg(arg, name, reason) {
  1441. if (!arg) {
  1442. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1443. }
  1444. return arg;
  1445. }
  1446. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1447. if (acceptArrayAnnotation && isArray(arg)) {
  1448. arg = arg[arg.length - 1];
  1449. }
  1450. assertArg(isFunction(arg), name, 'not a function, got ' +
  1451. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1452. return arg;
  1453. }
  1454. /**
  1455. * throw error if the name given is hasOwnProperty
  1456. * @param {String} name the name to test
  1457. * @param {String} context the context in which the name is used, such as module or directive
  1458. */
  1459. function assertNotHasOwnProperty(name, context) {
  1460. if (name === 'hasOwnProperty') {
  1461. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1462. }
  1463. }
  1464. /**
  1465. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1466. * @param {Object} obj starting object
  1467. * @param {String} path path to traverse
  1468. * @param {boolean} [bindFnToScope=true]
  1469. * @returns {Object} value as accessible by path
  1470. */
  1471. //TODO(misko): this function needs to be removed
  1472. function getter(obj, path, bindFnToScope) {
  1473. if (!path) return obj;
  1474. var keys = path.split('.');
  1475. var key;
  1476. var lastInstance = obj;
  1477. var len = keys.length;
  1478. for (var i = 0; i < len; i++) {
  1479. key = keys[i];
  1480. if (obj) {
  1481. obj = (lastInstance = obj)[key];
  1482. }
  1483. }
  1484. if (!bindFnToScope && isFunction(obj)) {
  1485. return bind(lastInstance, obj);
  1486. }
  1487. return obj;
  1488. }
  1489. /**
  1490. * Return the DOM siblings between the first and last node in the given array.
  1491. * @param {Array} array like object
  1492. * @returns {jqLite} jqLite collection containing the nodes
  1493. */
  1494. function getBlockNodes(nodes) {
  1495. // TODO(perf): just check if all items in `nodes` are siblings and if they are return the original
  1496. // collection, otherwise update the original collection.
  1497. var node = nodes[0];
  1498. var endNode = nodes[nodes.length - 1];
  1499. var blockNodes = [node];
  1500. do {
  1501. node = node.nextSibling;
  1502. if (!node) break;
  1503. blockNodes.push(node);
  1504. } while (node !== endNode);
  1505. return jqLite(blockNodes);
  1506. }
  1507. /**
  1508. * Creates a new object without a prototype. This object is useful for lookup without having to
  1509. * guard against prototypically inherited properties via hasOwnProperty.
  1510. *
  1511. * Related micro-benchmarks:
  1512. * - http://jsperf.com/object-create2
  1513. * - http://jsperf.com/proto-map-lookup/2
  1514. * - http://jsperf.com/for-in-vs-object-keys2
  1515. *
  1516. * @returns {Object}
  1517. */
  1518. function createMap() {
  1519. return Object.create(null);
  1520. }
  1521. var NODE_TYPE_ELEMENT = 1;
  1522. var NODE_TYPE_TEXT = 3;
  1523. var NODE_TYPE_COMMENT = 8;
  1524. var NODE_TYPE_DOCUMENT = 9;
  1525. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1526. /**
  1527. * @ngdoc type
  1528. * @name angular.Module
  1529. * @module ng
  1530. * @description
  1531. *
  1532. * Interface for configuring angular {@link angular.module modules}.
  1533. */
  1534. function setupModuleLoader(window) {
  1535. var $injectorMinErr = minErr('$injector');
  1536. var ngMinErr = minErr('ng');
  1537. function ensure(obj, name, factory) {
  1538. return obj[name] || (obj[name] = factory());
  1539. }
  1540. var angular = ensure(window, 'angular', Object);
  1541. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1542. angular.$$minErr = angular.$$minErr || minErr;
  1543. return ensure(angular, 'module', function() {
  1544. /** @type {Object.<string, angular.Module>} */
  1545. var modules = {};
  1546. /**
  1547. * @ngdoc function
  1548. * @name angular.module
  1549. * @module ng
  1550. * @description
  1551. *
  1552. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1553. * modules.
  1554. * All modules (angular core or 3rd party) that should be available to an application must be
  1555. * registered using this mechanism.
  1556. *
  1557. * When passed two or more arguments, a new module is created. If passed only one argument, an
  1558. * existing module (the name passed as the first argument to `module`) is retrieved.
  1559. *
  1560. *
  1561. * # Module
  1562. *
  1563. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1564. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1565. *
  1566. * ```js
  1567. * // Create a new module
  1568. * var myModule = angular.module('myModule', []);
  1569. *
  1570. * // register a new service
  1571. * myModule.value('appName', 'MyCoolApp');
  1572. *
  1573. * // configure existing services inside initialization blocks.
  1574. * myModule.config(['$locationProvider', function($locationProvider) {
  1575. * // Configure existing providers
  1576. * $locationProvider.hashPrefix('!');
  1577. * }]);
  1578. * ```
  1579. *
  1580. * Then you can create an injector and load your modules like this:
  1581. *
  1582. * ```js
  1583. * var injector = angular.injector(['ng', 'myModule'])
  1584. * ```
  1585. *
  1586. * However it's more likely that you'll just use
  1587. * {@link ng.directive:ngApp ngApp} or
  1588. * {@link angular.bootstrap} to simplify this process for you.
  1589. *
  1590. * @param {!string} name The name of the module to create or retrieve.
  1591. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1592. * unspecified then the module is being retrieved for further configuration.
  1593. * @param {Function=} configFn Optional configuration function for the module. Same as
  1594. * {@link angular.Module#config Module#config()}.
  1595. * @returns {module} new module with the {@link angular.Module} api.
  1596. */
  1597. return function module(name, requires, configFn) {
  1598. var assertNotHasOwnProperty = function(name, context) {
  1599. if (name === 'hasOwnProperty') {
  1600. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1601. }
  1602. };
  1603. assertNotHasOwnProperty(name, 'module');
  1604. if (requires && modules.hasOwnProperty(name)) {
  1605. modules[name] = null;
  1606. }
  1607. return ensure(modules, name, function() {
  1608. if (!requires) {
  1609. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1610. "the module name or forgot to load it. If registering a module ensure that you " +
  1611. "specify the dependencies as the second argument.", name);
  1612. }
  1613. /** @type {!Array.<Array.<*>>} */
  1614. var invokeQueue = [];
  1615. /** @type {!Array.<Function>} */
  1616. var configBlocks = [];
  1617. /** @type {!Array.<Function>} */
  1618. var runBlocks = [];
  1619. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1620. /** @type {angular.Module} */
  1621. var moduleInstance = {
  1622. // Private state
  1623. _invokeQueue: invokeQueue,
  1624. _configBlocks: configBlocks,
  1625. _runBlocks: runBlocks,
  1626. /**
  1627. * @ngdoc property
  1628. * @name angular.Module#requires
  1629. * @module ng
  1630. *
  1631. * @description
  1632. * Holds the list of modules which the injector will load before the current module is
  1633. * loaded.
  1634. */
  1635. requires: requires,
  1636. /**
  1637. * @ngdoc property
  1638. * @name angular.Module#name
  1639. * @module ng
  1640. *
  1641. * @description
  1642. * Name of the module.
  1643. */
  1644. name: name,
  1645. /**
  1646. * @ngdoc method
  1647. * @name angular.Module#provider
  1648. * @module ng
  1649. * @param {string} name service name
  1650. * @param {Function} providerType Construction function for creating new instance of the
  1651. * service.
  1652. * @description
  1653. * See {@link auto.$provide#provider $provide.provider()}.
  1654. */
  1655. provider: invokeLater('$provide', 'provider'),
  1656. /**
  1657. * @ngdoc method
  1658. * @name angular.Module#factory
  1659. * @module ng
  1660. * @param {string} name service name
  1661. * @param {Function} providerFunction Function for creating new instance of the service.
  1662. * @description
  1663. * See {@link auto.$provide#factory $provide.factory()}.
  1664. */
  1665. factory: invokeLater('$provide', 'factory'),
  1666. /**
  1667. * @ngdoc method
  1668. * @name angular.Module#service
  1669. * @module ng
  1670. * @param {string} name service name
  1671. * @param {Function} constructor A constructor function that will be instantiated.
  1672. * @description
  1673. * See {@link auto.$provide#service $provide.service()}.
  1674. */
  1675. service: invokeLater('$provide', 'service'),
  1676. /**
  1677. * @ngdoc method
  1678. * @name angular.Module#value
  1679. * @module ng
  1680. * @param {string} name service name
  1681. * @param {*} object Service instance object.
  1682. * @description
  1683. * See {@link auto.$provide#value $provide.value()}.
  1684. */
  1685. value: invokeLater('$provide', 'value'),
  1686. /**
  1687. * @ngdoc method
  1688. * @name angular.Module#constant
  1689. * @module ng
  1690. * @param {string} name constant name
  1691. * @param {*} object Constant value.
  1692. * @description
  1693. * Because the constant are fixed, they get applied before other provide methods.
  1694. * See {@link auto.$provide#constant $provide.constant()}.
  1695. */
  1696. constant: invokeLater('$provide', 'constant', 'unshift'),
  1697. /**
  1698. * @ngdoc method
  1699. * @name angular.Module#animation
  1700. * @module ng
  1701. * @param {string} name animation name
  1702. * @param {Function} animationFactory Factory function for creating new instance of an
  1703. * animation.
  1704. * @description
  1705. *
  1706. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1707. *
  1708. *
  1709. * Defines an animation hook that can be later used with
  1710. * {@link ngAnimate.$animate $animate} service and directives that use this service.
  1711. *
  1712. * ```js
  1713. * module.animation('.animation-name', function($inject1, $inject2) {
  1714. * return {
  1715. * eventName : function(element, done) {
  1716. * //code to run the animation
  1717. * //once complete, then run done()
  1718. * return function cancellationFunction(element) {
  1719. * //code to cancel the animation
  1720. * }
  1721. * }
  1722. * }
  1723. * })
  1724. * ```
  1725. *
  1726. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1727. * {@link ngAnimate ngAnimate module} for more information.
  1728. */
  1729. animation: invokeLater('$animateProvider', 'register'),
  1730. /**
  1731. * @ngdoc method
  1732. * @name angular.Module#filter
  1733. * @module ng
  1734. * @param {string} name Filter name.
  1735. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1736. * @description
  1737. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1738. */
  1739. filter: invokeLater('$filterProvider', 'register'),
  1740. /**
  1741. * @ngdoc method
  1742. * @name angular.Module#controller
  1743. * @module ng
  1744. * @param {string|Object} name Controller name, or an object map of controllers where the
  1745. * keys are the names and the values are the constructors.
  1746. * @param {Function} constructor Controller constructor function.
  1747. * @description
  1748. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1749. */
  1750. controller: invokeLater('$controllerProvider', 'register'),
  1751. /**
  1752. * @ngdoc method
  1753. * @name angular.Module#directive
  1754. * @module ng
  1755. * @param {string|Object} name Directive name, or an object map of directives where the
  1756. * keys are the names and the values are the factories.
  1757. * @param {Function} directiveFactory Factory function for creating new instance of
  1758. * directives.
  1759. * @description
  1760. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1761. */
  1762. directive: invokeLater('$compileProvider', 'directive'),
  1763. /**
  1764. * @ngdoc method
  1765. * @name angular.Module#config
  1766. * @module ng
  1767. * @param {Function} configFn Execute this function on module load. Useful for service
  1768. * configuration.
  1769. * @description
  1770. * Use this method to register work which needs to be performed on module loading.
  1771. * For more about how to configure services, see
  1772. * {@link providers#provider-recipe Provider Recipe}.
  1773. */
  1774. config: config,
  1775. /**
  1776. * @ngdoc method
  1777. * @name angular.Module#run
  1778. * @module ng
  1779. * @param {Function} initializationFn Execute this function after injector creation.
  1780. * Useful for application initialization.
  1781. * @description
  1782. * Use this method to register work which should be performed when the injector is done
  1783. * loading all modules.
  1784. */
  1785. run: function(block) {
  1786. runBlocks.push(block);
  1787. return this;
  1788. }
  1789. };
  1790. if (configFn) {
  1791. config(configFn);
  1792. }
  1793. return moduleInstance;
  1794. /**
  1795. * @param {string} provider
  1796. * @param {string} method
  1797. * @param {String=} insertMethod
  1798. * @returns {angular.Module}
  1799. */
  1800. function invokeLater(provider, method, insertMethod, queue) {
  1801. if (!queue) queue = invokeQueue;
  1802. return function() {
  1803. queue[insertMethod || 'push']([provider, method, arguments]);
  1804. return moduleInstance;
  1805. };
  1806. }
  1807. });
  1808. };
  1809. });
  1810. }
  1811. /* global angularModule: true,
  1812. version: true,
  1813. $LocaleProvider,
  1814. $CompileProvider,
  1815. htmlAnchorDirective,
  1816. inputDirective,
  1817. inputDirective,
  1818. formDirective,
  1819. scriptDirective,
  1820. selectDirective,
  1821. styleDirective,
  1822. optionDirective,
  1823. ngBindDirective,
  1824. ngBindHtmlDirective,
  1825. ngBindTemplateDirective,
  1826. ngClassDirective,
  1827. ngClassEvenDirective,
  1828. ngClassOddDirective,
  1829. ngCspDirective,
  1830. ngCloakDirective,
  1831. ngControllerDirective,
  1832. ngFormDirective,
  1833. ngHideDirective,
  1834. ngIfDirective,
  1835. ngIncludeDirective,
  1836. ngIncludeFillContentDirective,
  1837. ngInitDirective,
  1838. ngNonBindableDirective,
  1839. ngPluralizeDirective,
  1840. ngRepeatDirective,
  1841. ngShowDirective,
  1842. ngStyleDirective,
  1843. ngSwitchDirective,
  1844. ngSwitchWhenDirective,
  1845. ngSwitchDefaultDirective,
  1846. ngOptionsDirective,
  1847. ngTranscludeDirective,
  1848. ngModelDirective,
  1849. ngListDirective,
  1850. ngChangeDirective,
  1851. patternDirective,
  1852. patternDirective,
  1853. requiredDirective,
  1854. requiredDirective,
  1855. minlengthDirective,
  1856. minlengthDirective,
  1857. maxlengthDirective,
  1858. maxlengthDirective,
  1859. ngValueDirective,
  1860. ngModelOptionsDirective,
  1861. ngAttributeAliasDirectives,
  1862. ngEventDirectives,
  1863. $AnchorScrollProvider,
  1864. $AnimateProvider,
  1865. $BrowserProvider,
  1866. $CacheFactoryProvider,
  1867. $ControllerProvider,
  1868. $DocumentProvider,
  1869. $ExceptionHandlerProvider,
  1870. $FilterProvider,
  1871. $InterpolateProvider,
  1872. $IntervalProvider,
  1873. $HttpProvider,
  1874. $HttpBackendProvider,
  1875. $LocationProvider,
  1876. $LogProvider,
  1877. $ParseProvider,
  1878. $RootScopeProvider,
  1879. $QProvider,
  1880. $$QProvider,
  1881. $$SanitizeUriProvider,
  1882. $SceProvider,
  1883. $SceDelegateProvider,
  1884. $SnifferProvider,
  1885. $TemplateCacheProvider,
  1886. $TemplateRequestProvider,
  1887. $$TestabilityProvider,
  1888. $TimeoutProvider,
  1889. $$RAFProvider,
  1890. $$AsyncCallbackProvider,
  1891. $WindowProvider
  1892. */
  1893. /**
  1894. * @ngdoc object
  1895. * @name angular.version
  1896. * @module ng
  1897. * @description
  1898. * An object that contains information about the current AngularJS version. This object has the
  1899. * following properties:
  1900. *
  1901. * - `full` – `{string}` – Full version string, such as "0.9.18".
  1902. * - `major` – `{number}` – Major version number, such as "0".
  1903. * - `minor` – `{number}` – Minor version number, such as "9".
  1904. * - `dot` – `{number}` – Dot version number, such as "18".
  1905. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  1906. */
  1907. var version = {
  1908. full: '1.3.0', // all of these placeholder strings will be replaced by grunt's
  1909. major: 1, // package task
  1910. minor: 3,
  1911. dot: 0,
  1912. codeName: 'superluminal-nudge'
  1913. };
  1914. function publishExternalAPI(angular){
  1915. extend(angular, {
  1916. 'bootstrap': bootstrap,
  1917. 'copy': copy,
  1918. 'extend': extend,
  1919. 'equals': equals,
  1920. 'element': jqLite,
  1921. 'forEach': forEach,
  1922. 'injector': createInjector,
  1923. 'noop': noop,
  1924. 'bind': bind,
  1925. 'toJson': toJson,
  1926. 'fromJson': fromJson,
  1927. 'identity': identity,
  1928. 'isUndefined': isUndefined,
  1929. 'isDefined': isDefined,
  1930. 'isString': isString,
  1931. 'isFunction': isFunction,
  1932. 'isObject': isObject,
  1933. 'isNumber': isNumber,
  1934. 'isElement': isElement,
  1935. 'isArray': isArray,
  1936. 'version': version,
  1937. 'isDate': isDate,
  1938. 'lowercase': lowercase,
  1939. 'uppercase': uppercase,
  1940. 'callbacks': {counter: 0},
  1941. 'getTestability': getTestability,
  1942. '$$minErr': minErr,
  1943. '$$csp': csp,
  1944. 'reloadWithDebugInfo': reloadWithDebugInfo
  1945. });
  1946. angularModule = setupModuleLoader(window);
  1947. try {
  1948. angularModule('ngLocale');
  1949. } catch (e) {
  1950. angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
  1951. }
  1952. angularModule('ng', ['ngLocale'], ['$provide',
  1953. function ngModule($provide) {
  1954. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  1955. $provide.provider({
  1956. $$sanitizeUri: $$SanitizeUriProvider
  1957. });
  1958. $provide.provider('$compile', $CompileProvider).
  1959. directive({
  1960. a: htmlAnchorDirective,
  1961. input: inputDirective,
  1962. textarea: inputDirective,
  1963. form: formDirective,
  1964. script: scriptDirective,
  1965. select: selectDirective,
  1966. style: styleDirective,
  1967. option: optionDirective,
  1968. ngBind: ngBindDirective,
  1969. ngBindHtml: ngBindHtmlDirective,
  1970. ngBindTemplate: ngBindTemplateDirective,
  1971. ngClass: ngClassDirective,
  1972. ngClassEven: ngClassEvenDirective,
  1973. ngClassOdd: ngClassOddDirective,
  1974. ngCloak: ngCloakDirective,
  1975. ngController: ngControllerDirective,
  1976. ngForm: ngFormDirective,
  1977. ngHide: ngHideDirective,
  1978. ngIf: ngIfDirective,
  1979. ngInclude: ngIncludeDirective,
  1980. ngInit: ngInitDirective,
  1981. ngNonBindable: ngNonBindableDirective,
  1982. ngPluralize: ngPluralizeDirective,
  1983. ngRepeat: ngRepeatDirective,
  1984. ngShow: ngShowDirective,
  1985. ngStyle: ngStyleDirective,
  1986. ngSwitch: ngSwitchDirective,
  1987. ngSwitchWhen: ngSwitchWhenDirective,
  1988. ngSwitchDefault: ngSwitchDefaultDirective,
  1989. ngOptions: ngOptionsDirective,
  1990. ngTransclude: ngTranscludeDirective,
  1991. ngModel: ngModelDirective,
  1992. ngList: ngListDirective,
  1993. ngChange: ngChangeDirective,
  1994. pattern: patternDirective,
  1995. ngPattern: patternDirective,
  1996. required: requiredDirective,
  1997. ngRequired: requiredDirective,
  1998. minlength: minlengthDirective,
  1999. ngMinlength: minlengthDirective,
  2000. maxlength: maxlengthDirective,
  2001. ngMaxlength: maxlengthDirective,
  2002. ngValue: ngValueDirective,
  2003. ngModelOptions: ngModelOptionsDirective
  2004. }).
  2005. directive({
  2006. ngInclude: ngIncludeFillContentDirective
  2007. }).
  2008. directive(ngAttributeAliasDirectives).
  2009. directive(ngEventDirectives);
  2010. $provide.provider({
  2011. $anchorScroll: $AnchorScrollProvider,
  2012. $animate: $AnimateProvider,
  2013. $browser: $BrowserProvider,
  2014. $cacheFactory: $CacheFactoryProvider,
  2015. $controller: $ControllerProvider,
  2016. $document: $DocumentProvider,
  2017. $exceptionHandler: $ExceptionHandlerProvider,
  2018. $filter: $FilterProvider,
  2019. $interpolate: $InterpolateProvider,
  2020. $interval: $IntervalProvider,
  2021. $http: $HttpProvider,
  2022. $httpBackend: $HttpBackendProvider,
  2023. $location: $LocationProvider,
  2024. $log: $LogProvider,
  2025. $parse: $ParseProvider,
  2026. $rootScope: $RootScopeProvider,
  2027. $q: $QProvider,
  2028. $$q: $$QProvider,
  2029. $sce: $SceProvider,
  2030. $sceDelegate: $SceDelegateProvider,
  2031. $sniffer: $SnifferProvider,
  2032. $templateCache: $TemplateCacheProvider,
  2033. $templateRequest: $TemplateRequestProvider,
  2034. $$testability: $$TestabilityProvider,
  2035. $timeout: $TimeoutProvider,
  2036. $window: $WindowProvider,
  2037. $$rAF: $$RAFProvider,
  2038. $$asyncCallback : $$AsyncCallbackProvider
  2039. });
  2040. }
  2041. ]);
  2042. }
  2043. /* global JQLitePrototype: true,
  2044. addEventListenerFn: true,
  2045. removeEventListenerFn: true,
  2046. BOOLEAN_ATTR: true,
  2047. ALIASED_ATTR: true,
  2048. */
  2049. //////////////////////////////////
  2050. //JQLite
  2051. //////////////////////////////////
  2052. /**
  2053. * @ngdoc function
  2054. * @name angular.element
  2055. * @module ng
  2056. * @kind function
  2057. *
  2058. * @description
  2059. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2060. *
  2061. * If jQuery is available, `angular.element` is an alias for the
  2062. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2063. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2064. *
  2065. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2066. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2067. * commonly needed functionality with the goal of having a very small footprint.</div>
  2068. *
  2069. * To use jQuery, simply load it before `DOMContentLoaded` event fired.
  2070. *
  2071. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2072. * jqLite; they are never raw DOM references.</div>
  2073. *
  2074. * ## Angular's jqLite
  2075. * jqLite provides only the following jQuery methods:
  2076. *
  2077. * - [`addClass()`](http://api.jquery.com/addClass/)
  2078. * - [`after()`](http://api.jquery.com/after/)
  2079. * - [`append()`](http://api.jquery.com/append/)
  2080. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2081. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2082. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2083. * - [`clone()`](http://api.jquery.com/clone/)
  2084. * - [`contents()`](http://api.jquery.com/contents/)
  2085. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyles()`
  2086. * - [`data()`](http://api.jquery.com/data/)
  2087. * - [`detach()`](http://api.jquery.com/detach/)
  2088. * - [`empty()`](http://api.jquery.com/empty/)
  2089. * - [`eq()`](http://api.jquery.com/eq/)
  2090. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2091. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2092. * - [`html()`](http://api.jquery.com/html/)
  2093. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2094. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2095. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
  2096. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2097. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2098. * - [`prepend()`](http://api.jquery.com/prepend/)
  2099. * - [`prop()`](http://api.jquery.com/prop/)
  2100. * - [`ready()`](http://api.jquery.com/ready/)
  2101. * - [`remove()`](http://api.jquery.com/remove/)
  2102. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2103. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2104. * - [`removeData()`](http://api.jquery.com/removeData/)
  2105. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2106. * - [`text()`](http://api.jquery.com/text/)
  2107. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2108. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2109. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces
  2110. * - [`val()`](http://api.jquery.com/val/)
  2111. * - [`wrap()`](http://api.jquery.com/wrap/)
  2112. *
  2113. * ## jQuery/jqLite Extras
  2114. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2115. *
  2116. * ### Events
  2117. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2118. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2119. * element before it is removed.
  2120. *
  2121. * ### Methods
  2122. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2123. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2124. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2125. * `'ngModel'`).
  2126. * - `injector()` - retrieves the injector of the current element or its parent.
  2127. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2128. * element or its parent.
  2129. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2130. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2131. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2132. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2133. * parent element is reached.
  2134. *
  2135. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2136. * @returns {Object} jQuery object.
  2137. */
  2138. JQLite.expando = 'ng339';
  2139. var jqCache = JQLite.cache = {},
  2140. jqId = 1,
  2141. addEventListenerFn = function(element, type, fn) {
  2142. element.addEventListener(type, fn, false);
  2143. },
  2144. removeEventListenerFn = function(element, type, fn) {
  2145. element.removeEventListener(type, fn, false);
  2146. };
  2147. /*
  2148. * !!! This is an undocumented "private" function !!!
  2149. */
  2150. JQLite._data = function(node) {
  2151. //jQuery always returns an object on cache miss
  2152. return this.cache[node[this.expando]] || {};
  2153. };
  2154. function jqNextId() { return ++jqId; }
  2155. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2156. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2157. var MOUSE_EVENT_MAP= { mouseleave : "mouseout", mouseenter : "mouseover"};
  2158. var jqLiteMinErr = minErr('jqLite');
  2159. /**
  2160. * Converts snake_case to camelCase.
  2161. * Also there is special case for Moz prefix starting with upper case letter.
  2162. * @param name Name to normalize
  2163. */
  2164. function camelCase(name) {
  2165. return name.
  2166. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2167. return offset ? letter.toUpperCase() : letter;
  2168. }).
  2169. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2170. }
  2171. var SINGLE_TAG_REGEXP = /^<(\w+)\s*\/?>(?:<\/\1>|)$/;
  2172. var HTML_REGEXP = /<|&#?\w+;/;
  2173. var TAG_NAME_REGEXP = /<([\w:]+)/;
  2174. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi;
  2175. var wrapMap = {
  2176. 'option': [1, '<select multiple="multiple">', '</select>'],
  2177. 'thead': [1, '<table>', '</table>'],
  2178. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2179. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2180. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2181. '_default': [0, "", ""]
  2182. };
  2183. wrapMap.optgroup = wrapMap.option;
  2184. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2185. wrapMap.th = wrapMap.td;
  2186. function jqLiteIsTextNode(html) {
  2187. return !HTML_REGEXP.test(html);
  2188. }
  2189. function jqLiteAcceptsData(node) {
  2190. // The window object can accept data but has no nodeType
  2191. // Otherwise we are only interested in elements (1) and documents (9)
  2192. var nodeType = node.nodeType;
  2193. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2194. }
  2195. function jqLiteBuildFragment(html, context) {
  2196. var tmp, tag, wrap,
  2197. fragment = context.createDocumentFragment(),
  2198. nodes = [], i;
  2199. if (jqLiteIsTextNode(html)) {
  2200. // Convert non-html into a text node
  2201. nodes.push(context.createTextNode(html));
  2202. } else {
  2203. // Convert html into DOM nodes
  2204. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2205. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2206. wrap = wrapMap[tag] || wrapMap._default;
  2207. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2208. // Descend through wrappers to the right content
  2209. i = wrap[0];
  2210. while (i--) {
  2211. tmp = tmp.lastChild;
  2212. }
  2213. nodes = concat(nodes, tmp.childNodes);
  2214. tmp = fragment.firstChild;
  2215. tmp.textContent = "";
  2216. }
  2217. // Remove wrapper from fragment
  2218. fragment.textContent = "";
  2219. fragment.innerHTML = ""; // Clear inner HTML
  2220. forEach(nodes, function(node) {
  2221. fragment.appendChild(node);
  2222. });
  2223. return fragment;
  2224. }
  2225. function jqLiteParseHTML(html, context) {
  2226. context = context || document;
  2227. var parsed;
  2228. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2229. return [context.createElement(parsed[1])];
  2230. }
  2231. if ((parsed = jqLiteBuildFragment(html, context))) {
  2232. return parsed.childNodes;
  2233. }
  2234. return [];
  2235. }
  2236. /////////////////////////////////////////////
  2237. function JQLite(element) {
  2238. if (element instanceof JQLite) {
  2239. return element;
  2240. }
  2241. var argIsString;
  2242. if (isString(element)) {
  2243. element = trim(element);
  2244. argIsString = true;
  2245. }
  2246. if (!(this instanceof JQLite)) {
  2247. if (argIsString && element.charAt(0) != '<') {
  2248. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2249. }
  2250. return new JQLite(element);
  2251. }
  2252. if (argIsString) {
  2253. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2254. } else {
  2255. jqLiteAddNodes(this, element);
  2256. }
  2257. }
  2258. function jqLiteClone(element) {
  2259. return element.cloneNode(true);
  2260. }
  2261. function jqLiteDealoc(element, onlyDescendants){
  2262. if (!onlyDescendants) jqLiteRemoveData(element);
  2263. if (element.querySelectorAll) {
  2264. var descendants = element.querySelectorAll('*');
  2265. for (var i = 0, l = descendants.length; i < l; i++) {
  2266. jqLiteRemoveData(descendants[i]);
  2267. }
  2268. }
  2269. }
  2270. function jqLiteOff(element, type, fn, unsupported) {
  2271. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2272. var expandoStore = jqLiteExpandoStore(element);
  2273. var events = expandoStore && expandoStore.events;
  2274. var handle = expandoStore && expandoStore.handle;
  2275. if (!handle) return; //no listeners registered
  2276. if (!type) {
  2277. for (type in events) {
  2278. if (type !== '$destroy') {
  2279. removeEventListenerFn(element, type, handle);
  2280. }
  2281. delete events[type];
  2282. }
  2283. } else {
  2284. forEach(type.split(' '), function(type) {
  2285. if (isDefined(fn)) {
  2286. var listenerFns = events[type];
  2287. arrayRemove(listenerFns || [], fn);
  2288. if (listenerFns && listenerFns.length > 0) {
  2289. return;
  2290. }
  2291. }
  2292. removeEventListenerFn(element, type, handle);
  2293. delete events[type];
  2294. });
  2295. }
  2296. }
  2297. function jqLiteRemoveData(element, name) {
  2298. var expandoId = element.ng339;
  2299. var expandoStore = expandoId && jqCache[expandoId];
  2300. if (expandoStore) {
  2301. if (name) {
  2302. delete expandoStore.data[name];
  2303. return;
  2304. }
  2305. if (expandoStore.handle) {
  2306. if (expandoStore.events.$destroy) {
  2307. expandoStore.handle({}, '$destroy');
  2308. }
  2309. jqLiteOff(element);
  2310. }
  2311. delete jqCache[expandoId];
  2312. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2313. }
  2314. }
  2315. function jqLiteExpandoStore(element, createIfNecessary) {
  2316. var expandoId = element.ng339,
  2317. expandoStore = expandoId && jqCache[expandoId];
  2318. if (createIfNecessary && !expandoStore) {
  2319. element.ng339 = expandoId = jqNextId();
  2320. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2321. }
  2322. return expandoStore;
  2323. }
  2324. function jqLiteData(element, key, value) {
  2325. if (jqLiteAcceptsData(element)) {
  2326. var isSimpleSetter = isDefined(value);
  2327. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2328. var massGetter = !key;
  2329. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2330. var data = expandoStore && expandoStore.data;
  2331. if (isSimpleSetter) { // data('key', value)
  2332. data[key] = value;
  2333. } else {
  2334. if (massGetter) { // data()
  2335. return data;
  2336. } else {
  2337. if (isSimpleGetter) { // data('key')
  2338. // don't force creation of expandoStore if it doesn't exist yet
  2339. return data && data[key];
  2340. } else { // mass-setter: data({key1: val1, key2: val2})
  2341. extend(data, key);
  2342. }
  2343. }
  2344. }
  2345. }
  2346. }
  2347. function jqLiteHasClass(element, selector) {
  2348. if (!element.getAttribute) return false;
  2349. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2350. indexOf( " " + selector + " " ) > -1);
  2351. }
  2352. function jqLiteRemoveClass(element, cssClasses) {
  2353. if (cssClasses && element.setAttribute) {
  2354. forEach(cssClasses.split(' '), function(cssClass) {
  2355. element.setAttribute('class', trim(
  2356. (" " + (element.getAttribute('class') || '') + " ")
  2357. .replace(/[\n\t]/g, " ")
  2358. .replace(" " + trim(cssClass) + " ", " "))
  2359. );
  2360. });
  2361. }
  2362. }
  2363. function jqLiteAddClass(element, cssClasses) {
  2364. if (cssClasses && element.setAttribute) {
  2365. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2366. .replace(/[\n\t]/g, " ");
  2367. forEach(cssClasses.split(' '), function(cssClass) {
  2368. cssClass = trim(cssClass);
  2369. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2370. existingClasses += cssClass + ' ';
  2371. }
  2372. });
  2373. element.setAttribute('class', trim(existingClasses));
  2374. }
  2375. }
  2376. function jqLiteAddNodes(root, elements) {
  2377. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2378. if (elements) {
  2379. // if a Node (the most common case)
  2380. if (elements.nodeType) {
  2381. root[root.length++] = elements;
  2382. } else {
  2383. var length = elements.length;
  2384. // if an Array or NodeList and not a Window
  2385. if (typeof length === 'number' && elements.window !== elements) {
  2386. if (length) {
  2387. for (var i = 0; i < length; i++) {
  2388. root[root.length++] = elements[i];
  2389. }
  2390. }
  2391. } else {
  2392. root[root.length++] = elements;
  2393. }
  2394. }
  2395. }
  2396. }
  2397. function jqLiteController(element, name) {
  2398. return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
  2399. }
  2400. function jqLiteInheritedData(element, name, value) {
  2401. // if element is the document object work with the html element instead
  2402. // this makes $(document).scope() possible
  2403. if(element.nodeType == NODE_TYPE_DOCUMENT) {
  2404. element = element.documentElement;
  2405. }
  2406. var names = isArray(name) ? name : [name];
  2407. while (element) {
  2408. for (var i = 0, ii = names.length; i < ii; i++) {
  2409. if ((value = jqLite.data(element, names[i])) !== undefined) return value;
  2410. }
  2411. // If dealing with a document fragment node with a host element, and no parent, use the host
  2412. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2413. // to lookup parent controllers.
  2414. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2415. }
  2416. }
  2417. function jqLiteEmpty(element) {
  2418. jqLiteDealoc(element, true);
  2419. while (element.firstChild) {
  2420. element.removeChild(element.firstChild);
  2421. }
  2422. }
  2423. function jqLiteRemove(element, keepData) {
  2424. if (!keepData) jqLiteDealoc(element);
  2425. var parent = element.parentNode;
  2426. if (parent) parent.removeChild(element);
  2427. }
  2428. function jqLiteDocumentLoaded(action, win) {
  2429. win = win || window;
  2430. if (win.document.readyState === 'complete') {
  2431. // Force the action to be run async for consistent behaviour
  2432. // from the action's point of view
  2433. // i.e. it will definitely not be in a $apply
  2434. win.setTimeout(action);
  2435. } else {
  2436. // No need to unbind this handler as load is only ever called once
  2437. jqLite(win).on('load', action);
  2438. }
  2439. }
  2440. //////////////////////////////////////////
  2441. // Functions which are declared directly.
  2442. //////////////////////////////////////////
  2443. var JQLitePrototype = JQLite.prototype = {
  2444. ready: function(fn) {
  2445. var fired = false;
  2446. function trigger() {
  2447. if (fired) return;
  2448. fired = true;
  2449. fn();
  2450. }
  2451. // check if document is already loaded
  2452. if (document.readyState === 'complete'){
  2453. setTimeout(trigger);
  2454. } else {
  2455. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2456. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2457. // jshint -W064
  2458. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2459. // jshint +W064
  2460. this.on('DOMContentLoaded', trigger);
  2461. }
  2462. },
  2463. toString: function() {
  2464. var value = [];
  2465. forEach(this, function(e){ value.push('' + e);});
  2466. return '[' + value.join(', ') + ']';
  2467. },
  2468. eq: function(index) {
  2469. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2470. },
  2471. length: 0,
  2472. push: push,
  2473. sort: [].sort,
  2474. splice: [].splice
  2475. };
  2476. //////////////////////////////////////////
  2477. // Functions iterating getter/setters.
  2478. // these functions return self on setter and
  2479. // value on get.
  2480. //////////////////////////////////////////
  2481. var BOOLEAN_ATTR = {};
  2482. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2483. BOOLEAN_ATTR[lowercase(value)] = value;
  2484. });
  2485. var BOOLEAN_ELEMENTS = {};
  2486. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2487. BOOLEAN_ELEMENTS[value] = true;
  2488. });
  2489. var ALIASED_ATTR = {
  2490. 'ngMinlength' : 'minlength',
  2491. 'ngMaxlength' : 'maxlength',
  2492. 'ngMin' : 'min',
  2493. 'ngMax' : 'max',
  2494. 'ngPattern' : 'pattern'
  2495. };
  2496. function getBooleanAttrName(element, name) {
  2497. // check dom last since we will most likely fail on name
  2498. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2499. // booleanAttr is here twice to minimize DOM access
  2500. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2501. }
  2502. function getAliasedAttrName(element, name) {
  2503. var nodeName = element.nodeName;
  2504. return (nodeName === 'INPUT' || nodeName === 'TEXTAREA') && ALIASED_ATTR[name];
  2505. }
  2506. forEach({
  2507. data: jqLiteData,
  2508. removeData: jqLiteRemoveData
  2509. }, function(fn, name) {
  2510. JQLite[name] = fn;
  2511. });
  2512. forEach({
  2513. data: jqLiteData,
  2514. inheritedData: jqLiteInheritedData,
  2515. scope: function(element) {
  2516. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2517. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2518. },
  2519. isolateScope: function(element) {
  2520. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2521. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2522. },
  2523. controller: jqLiteController,
  2524. injector: function(element) {
  2525. return jqLiteInheritedData(element, '$injector');
  2526. },
  2527. removeAttr: function(element, name) {
  2528. element.removeAttribute(name);
  2529. },
  2530. hasClass: jqLiteHasClass,
  2531. css: function(element, name, value) {
  2532. name = camelCase(name);
  2533. if (isDefined(value)) {
  2534. element.style[name] = value;
  2535. } else {
  2536. return element.style[name];
  2537. }
  2538. },
  2539. attr: function(element, name, value){
  2540. var lowercasedName = lowercase(name);
  2541. if (BOOLEAN_ATTR[lowercasedName]) {
  2542. if (isDefined(value)) {
  2543. if (!!value) {
  2544. element[name] = true;
  2545. element.setAttribute(name, lowercasedName);
  2546. } else {
  2547. element[name] = false;
  2548. element.removeAttribute(lowercasedName);
  2549. }
  2550. } else {
  2551. return (element[name] ||
  2552. (element.attributes.getNamedItem(name)|| noop).specified)
  2553. ? lowercasedName
  2554. : undefined;
  2555. }
  2556. } else if (isDefined(value)) {
  2557. element.setAttribute(name, value);
  2558. } else if (element.getAttribute) {
  2559. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2560. // some elements (e.g. Document) don't have get attribute, so return undefined
  2561. var ret = element.getAttribute(name, 2);
  2562. // normalize non-existing attributes to undefined (as jQuery)
  2563. return ret === null ? undefined : ret;
  2564. }
  2565. },
  2566. prop: function(element, name, value) {
  2567. if (isDefined(value)) {
  2568. element[name] = value;
  2569. } else {
  2570. return element[name];
  2571. }
  2572. },
  2573. text: (function() {
  2574. getText.$dv = '';
  2575. return getText;
  2576. function getText(element, value) {
  2577. if (isUndefined(value)) {
  2578. var nodeType = element.nodeType;
  2579. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2580. }
  2581. element.textContent = value;
  2582. }
  2583. })(),
  2584. val: function(element, value) {
  2585. if (isUndefined(value)) {
  2586. if (element.multiple && nodeName_(element) === 'select') {
  2587. var result = [];
  2588. forEach(element.options, function (option) {
  2589. if (option.selected) {
  2590. result.push(option.value || option.text);
  2591. }
  2592. });
  2593. return result.length === 0 ? null : result;
  2594. }
  2595. return element.value;
  2596. }
  2597. element.value = value;
  2598. },
  2599. html: function(element, value) {
  2600. if (isUndefined(value)) {
  2601. return element.innerHTML;
  2602. }
  2603. jqLiteDealoc(element, true);
  2604. element.innerHTML = value;
  2605. },
  2606. empty: jqLiteEmpty
  2607. }, function(fn, name){
  2608. /**
  2609. * Properties: writes return selection, reads return first value
  2610. */
  2611. JQLite.prototype[name] = function(arg1, arg2) {
  2612. var i, key;
  2613. var nodeCount = this.length;
  2614. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2615. // in a way that survives minification.
  2616. // jqLiteEmpty takes no arguments but is a setter.
  2617. if (fn !== jqLiteEmpty &&
  2618. (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined)) {
  2619. if (isObject(arg1)) {
  2620. // we are a write, but the object properties are the key/values
  2621. for (i = 0; i < nodeCount; i++) {
  2622. if (fn === jqLiteData) {
  2623. // data() takes the whole object in jQuery
  2624. fn(this[i], arg1);
  2625. } else {
  2626. for (key in arg1) {
  2627. fn(this[i], key, arg1[key]);
  2628. }
  2629. }
  2630. }
  2631. // return self for chaining
  2632. return this;
  2633. } else {
  2634. // we are a read, so read the first child.
  2635. // TODO: do we still need this?
  2636. var value = fn.$dv;
  2637. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2638. var jj = (value === undefined) ? Math.min(nodeCount, 1) : nodeCount;
  2639. for (var j = 0; j < jj; j++) {
  2640. var nodeValue = fn(this[j], arg1, arg2);
  2641. value = value ? value + nodeValue : nodeValue;
  2642. }
  2643. return value;
  2644. }
  2645. } else {
  2646. // we are a write, so apply to all children
  2647. for (i = 0; i < nodeCount; i++) {
  2648. fn(this[i], arg1, arg2);
  2649. }
  2650. // return self for chaining
  2651. return this;
  2652. }
  2653. };
  2654. });
  2655. function createEventHandler(element, events) {
  2656. var eventHandler = function (event, type) {
  2657. // jQuery specific api
  2658. event.isDefaultPrevented = function() {
  2659. return event.defaultPrevented;
  2660. };
  2661. var eventFns = events[type || event.type];
  2662. var eventFnsLength = eventFns ? eventFns.length : 0;
  2663. if (!eventFnsLength) return;
  2664. if (isUndefined(event.immediatePropagationStopped)) {
  2665. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2666. event.stopImmediatePropagation = function() {
  2667. event.immediatePropagationStopped = true;
  2668. if (event.stopPropagation) {
  2669. event.stopPropagation();
  2670. }
  2671. if (originalStopImmediatePropagation) {
  2672. originalStopImmediatePropagation.call(event);
  2673. }
  2674. };
  2675. }
  2676. event.isImmediatePropagationStopped = function() {
  2677. return event.immediatePropagationStopped === true;
  2678. };
  2679. // Copy event handlers in case event handlers array is modified during execution.
  2680. if ((eventFnsLength > 1)) {
  2681. eventFns = shallowCopy(eventFns);
  2682. }
  2683. for (var i = 0; i < eventFnsLength; i++) {
  2684. if (!event.isImmediatePropagationStopped()) {
  2685. eventFns[i].call(element, event);
  2686. }
  2687. }
  2688. };
  2689. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2690. // events on `element`
  2691. eventHandler.elem = element;
  2692. return eventHandler;
  2693. }
  2694. //////////////////////////////////////////
  2695. // Functions iterating traversal.
  2696. // These functions chain results into a single
  2697. // selector.
  2698. //////////////////////////////////////////
  2699. forEach({
  2700. removeData: jqLiteRemoveData,
  2701. on: function jqLiteOn(element, type, fn, unsupported){
  2702. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2703. // Do not add event handlers to non-elements because they will not be cleaned up.
  2704. if (!jqLiteAcceptsData(element)) {
  2705. return;
  2706. }
  2707. var expandoStore = jqLiteExpandoStore(element, true);
  2708. var events = expandoStore.events;
  2709. var handle = expandoStore.handle;
  2710. if (!handle) {
  2711. handle = expandoStore.handle = createEventHandler(element, events);
  2712. }
  2713. // http://jsperf.com/string-indexof-vs-split
  2714. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  2715. var i = types.length;
  2716. while (i--) {
  2717. type = types[i];
  2718. var eventFns = events[type];
  2719. if (!eventFns) {
  2720. events[type] = [];
  2721. if (type === 'mouseenter' || type === 'mouseleave') {
  2722. // Refer to jQuery's implementation of mouseenter & mouseleave
  2723. // Read about mouseenter and mouseleave:
  2724. // http://www.quirksmode.org/js/events_mouse.html#link8
  2725. jqLiteOn(element, MOUSE_EVENT_MAP[type], function(event) {
  2726. var target = this, related = event.relatedTarget;
  2727. // For mousenter/leave call the handler if related is outside the target.
  2728. // NB: No relatedTarget if the mouse left/entered the browser window
  2729. if ( !related || (related !== target && !target.contains(related)) ){
  2730. handle(event, type);
  2731. }
  2732. });
  2733. } else {
  2734. if (type !== '$destroy') {
  2735. addEventListenerFn(element, type, handle);
  2736. }
  2737. }
  2738. eventFns = events[type];
  2739. }
  2740. eventFns.push(fn);
  2741. }
  2742. },
  2743. off: jqLiteOff,
  2744. one: function(element, type, fn) {
  2745. element = jqLite(element);
  2746. //add the listener twice so that when it is called
  2747. //you can remove the original function and still be
  2748. //able to call element.off(ev, fn) normally
  2749. element.on(type, function onFn() {
  2750. element.off(type, fn);
  2751. element.off(type, onFn);
  2752. });
  2753. element.on(type, fn);
  2754. },
  2755. replaceWith: function(element, replaceNode) {
  2756. var index, parent = element.parentNode;
  2757. jqLiteDealoc(element);
  2758. forEach(new JQLite(replaceNode), function(node){
  2759. if (index) {
  2760. parent.insertBefore(node, index.nextSibling);
  2761. } else {
  2762. parent.replaceChild(node, element);
  2763. }
  2764. index = node;
  2765. });
  2766. },
  2767. children: function(element) {
  2768. var children = [];
  2769. forEach(element.childNodes, function(element){
  2770. if (element.nodeType === NODE_TYPE_ELEMENT)
  2771. children.push(element);
  2772. });
  2773. return children;
  2774. },
  2775. contents: function(element) {
  2776. return element.contentDocument || element.childNodes || [];
  2777. },
  2778. append: function(element, node) {
  2779. var nodeType = element.nodeType;
  2780. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  2781. node = new JQLite(node);
  2782. for (var i = 0, ii = node.length; i < ii; i++) {
  2783. var child = node[i];
  2784. element.appendChild(child);
  2785. }
  2786. },
  2787. prepend: function(element, node) {
  2788. if (element.nodeType === NODE_TYPE_ELEMENT) {
  2789. var index = element.firstChild;
  2790. forEach(new JQLite(node), function(child){
  2791. element.insertBefore(child, index);
  2792. });
  2793. }
  2794. },
  2795. wrap: function(element, wrapNode) {
  2796. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  2797. var parent = element.parentNode;
  2798. if (parent) {
  2799. parent.replaceChild(wrapNode, element);
  2800. }
  2801. wrapNode.appendChild(element);
  2802. },
  2803. remove: jqLiteRemove,
  2804. detach: function(element) {
  2805. jqLiteRemove(element, true);
  2806. },
  2807. after: function(element, newElement) {
  2808. var index = element, parent = element.parentNode;
  2809. newElement = new JQLite(newElement);
  2810. for (var i = 0, ii = newElement.length; i < ii; i++) {
  2811. var node = newElement[i];
  2812. parent.insertBefore(node, index.nextSibling);
  2813. index = node;
  2814. }
  2815. },
  2816. addClass: jqLiteAddClass,
  2817. removeClass: jqLiteRemoveClass,
  2818. toggleClass: function(element, selector, condition) {
  2819. if (selector) {
  2820. forEach(selector.split(' '), function(className){
  2821. var classCondition = condition;
  2822. if (isUndefined(classCondition)) {
  2823. classCondition = !jqLiteHasClass(element, className);
  2824. }
  2825. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  2826. });
  2827. }
  2828. },
  2829. parent: function(element) {
  2830. var parent = element.parentNode;
  2831. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  2832. },
  2833. next: function(element) {
  2834. return element.nextElementSibling;
  2835. },
  2836. find: function(element, selector) {
  2837. if (element.getElementsByTagName) {
  2838. return element.getElementsByTagName(selector);
  2839. } else {
  2840. return [];
  2841. }
  2842. },
  2843. clone: jqLiteClone,
  2844. triggerHandler: function(element, event, extraParameters) {
  2845. var dummyEvent, eventFnsCopy, handlerArgs;
  2846. var eventName = event.type || event;
  2847. var expandoStore = jqLiteExpandoStore(element);
  2848. var events = expandoStore && expandoStore.events;
  2849. var eventFns = events && events[eventName];
  2850. if (eventFns) {
  2851. // Create a dummy event to pass to the handlers
  2852. dummyEvent = {
  2853. preventDefault: function() { this.defaultPrevented = true; },
  2854. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  2855. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  2856. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  2857. stopPropagation: noop,
  2858. type: eventName,
  2859. target: element
  2860. };
  2861. // If a custom event was provided then extend our dummy event with it
  2862. if (event.type) {
  2863. dummyEvent = extend(dummyEvent, event);
  2864. }
  2865. // Copy event handlers in case event handlers array is modified during execution.
  2866. eventFnsCopy = shallowCopy(eventFns);
  2867. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  2868. forEach(eventFnsCopy, function(fn) {
  2869. if (!dummyEvent.isImmediatePropagationStopped()) {
  2870. fn.apply(element, handlerArgs);
  2871. }
  2872. });
  2873. }
  2874. }
  2875. }, function(fn, name){
  2876. /**
  2877. * chaining functions
  2878. */
  2879. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  2880. var value;
  2881. for(var i = 0, ii = this.length; i < ii; i++) {
  2882. if (isUndefined(value)) {
  2883. value = fn(this[i], arg1, arg2, arg3);
  2884. if (isDefined(value)) {
  2885. // any function which returns a value needs to be wrapped
  2886. value = jqLite(value);
  2887. }
  2888. } else {
  2889. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  2890. }
  2891. }
  2892. return isDefined(value) ? value : this;
  2893. };
  2894. // bind legacy bind/unbind to on/off
  2895. JQLite.prototype.bind = JQLite.prototype.on;
  2896. JQLite.prototype.unbind = JQLite.prototype.off;
  2897. });
  2898. /**
  2899. * Computes a hash of an 'obj'.
  2900. * Hash of a:
  2901. * string is string
  2902. * number is number as string
  2903. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  2904. * that is also assigned to the $$hashKey property of the object.
  2905. *
  2906. * @param obj
  2907. * @returns {string} hash string such that the same input will have the same hash string.
  2908. * The resulting string key is in 'type:hashKey' format.
  2909. */
  2910. function hashKey(obj, nextUidFn) {
  2911. var key = obj && obj.$$hashKey;
  2912. if (key) {
  2913. if (typeof key === 'function') {
  2914. key = obj.$$hashKey();
  2915. }
  2916. return key;
  2917. }
  2918. var objType = typeof obj;
  2919. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  2920. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  2921. } else {
  2922. key = objType + ':' + obj;
  2923. }
  2924. return key;
  2925. }
  2926. /**
  2927. * HashMap which can use objects as keys
  2928. */
  2929. function HashMap(array, isolatedUid) {
  2930. if (isolatedUid) {
  2931. var uid = 0;
  2932. this.nextUid = function() {
  2933. return ++uid;
  2934. };
  2935. }
  2936. forEach(array, this.put, this);
  2937. }
  2938. HashMap.prototype = {
  2939. /**
  2940. * Store key value pair
  2941. * @param key key to store can be any type
  2942. * @param value value to store can be any type
  2943. */
  2944. put: function(key, value) {
  2945. this[hashKey(key, this.nextUid)] = value;
  2946. },
  2947. /**
  2948. * @param key
  2949. * @returns {Object} the value for the key
  2950. */
  2951. get: function(key) {
  2952. return this[hashKey(key, this.nextUid)];
  2953. },
  2954. /**
  2955. * Remove the key/value pair
  2956. * @param key
  2957. */
  2958. remove: function(key) {
  2959. var value = this[key = hashKey(key, this.nextUid)];
  2960. delete this[key];
  2961. return value;
  2962. }
  2963. };
  2964. /**
  2965. * @ngdoc function
  2966. * @module ng
  2967. * @name angular.injector
  2968. * @kind function
  2969. *
  2970. * @description
  2971. * Creates an injector object that can be used for retrieving services as well as for
  2972. * dependency injection (see {@link guide/di dependency injection}).
  2973. *
  2974. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  2975. * {@link angular.module}. The `ng` module must be explicitly added.
  2976. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  2977. *
  2978. * @example
  2979. * Typical usage
  2980. * ```js
  2981. * // create an injector
  2982. * var $injector = angular.injector(['ng']);
  2983. *
  2984. * // use the injector to kick off your application
  2985. * // use the type inference to auto inject arguments, or use implicit injection
  2986. * $injector.invoke(function($rootScope, $compile, $document) {
  2987. * $compile($document)($rootScope);
  2988. * $rootScope.$digest();
  2989. * });
  2990. * ```
  2991. *
  2992. * Sometimes you want to get access to the injector of a currently running Angular app
  2993. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  2994. * application has been bootstrapped. You can do this using the extra `injector()` added
  2995. * to JQuery/jqLite elements. See {@link angular.element}.
  2996. *
  2997. * *This is fairly rare but could be the case if a third party library is injecting the
  2998. * markup.*
  2999. *
  3000. * In the following example a new block of HTML containing a `ng-controller`
  3001. * directive is added to the end of the document body by JQuery. We then compile and link
  3002. * it into the current AngularJS scope.
  3003. *
  3004. * ```js
  3005. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3006. * $(document.body).append($div);
  3007. *
  3008. * angular.element(document).injector().invoke(function($compile) {
  3009. * var scope = angular.element($div).scope();
  3010. * $compile($div)(scope);
  3011. * });
  3012. * ```
  3013. */
  3014. /**
  3015. * @ngdoc module
  3016. * @name auto
  3017. * @description
  3018. *
  3019. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3020. */
  3021. var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
  3022. var FN_ARG_SPLIT = /,/;
  3023. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3024. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3025. var $injectorMinErr = minErr('$injector');
  3026. function anonFn(fn) {
  3027. // For anonymous functions, showing at the very least the function signature can help in
  3028. // debugging.
  3029. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3030. args = fnText.match(FN_ARGS);
  3031. if (args) {
  3032. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3033. }
  3034. return 'fn';
  3035. }
  3036. function annotate(fn, strictDi, name) {
  3037. var $inject,
  3038. fnText,
  3039. argDecl,
  3040. last;
  3041. if (typeof fn === 'function') {
  3042. if (!($inject = fn.$inject)) {
  3043. $inject = [];
  3044. if (fn.length) {
  3045. if (strictDi) {
  3046. if (!isString(name) || !name) {
  3047. name = fn.name || anonFn(fn);
  3048. }
  3049. throw $injectorMinErr('strictdi',
  3050. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3051. }
  3052. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3053. argDecl = fnText.match(FN_ARGS);
  3054. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3055. arg.replace(FN_ARG, function(all, underscore, name) {
  3056. $inject.push(name);
  3057. });
  3058. });
  3059. }
  3060. fn.$inject = $inject;
  3061. }
  3062. } else if (isArray(fn)) {
  3063. last = fn.length - 1;
  3064. assertArgFn(fn[last], 'fn');
  3065. $inject = fn.slice(0, last);
  3066. } else {
  3067. assertArgFn(fn, 'fn', true);
  3068. }
  3069. return $inject;
  3070. }
  3071. ///////////////////////////////////////
  3072. /**
  3073. * @ngdoc service
  3074. * @name $injector
  3075. *
  3076. * @description
  3077. *
  3078. * `$injector` is used to retrieve object instances as defined by
  3079. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3080. * and load modules.
  3081. *
  3082. * The following always holds true:
  3083. *
  3084. * ```js
  3085. * var $injector = angular.injector();
  3086. * expect($injector.get('$injector')).toBe($injector);
  3087. * expect($injector.invoke(function($injector) {
  3088. * return $injector;
  3089. * })).toBe($injector);
  3090. * ```
  3091. *
  3092. * # Injection Function Annotation
  3093. *
  3094. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3095. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3096. *
  3097. * ```js
  3098. * // inferred (only works if code not minified/obfuscated)
  3099. * $injector.invoke(function(serviceA){});
  3100. *
  3101. * // annotated
  3102. * function explicit(serviceA) {};
  3103. * explicit.$inject = ['serviceA'];
  3104. * $injector.invoke(explicit);
  3105. *
  3106. * // inline
  3107. * $injector.invoke(['serviceA', function(serviceA){}]);
  3108. * ```
  3109. *
  3110. * ## Inference
  3111. *
  3112. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3113. * can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
  3114. * minification, and obfuscation tools since these tools change the argument names.
  3115. *
  3116. * ## `$inject` Annotation
  3117. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3118. *
  3119. * ## Inline
  3120. * As an array of injection names, where the last item in the array is the function to call.
  3121. */
  3122. /**
  3123. * @ngdoc method
  3124. * @name $injector#get
  3125. *
  3126. * @description
  3127. * Return an instance of the service.
  3128. *
  3129. * @param {string} name The name of the instance to retrieve.
  3130. * @return {*} The instance.
  3131. */
  3132. /**
  3133. * @ngdoc method
  3134. * @name $injector#invoke
  3135. *
  3136. * @description
  3137. * Invoke the method and supply the method arguments from the `$injector`.
  3138. *
  3139. * @param {!Function} fn The function to invoke. Function parameters are injected according to the
  3140. * {@link guide/di $inject Annotation} rules.
  3141. * @param {Object=} self The `this` for the invoked method.
  3142. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3143. * object first, before the `$injector` is consulted.
  3144. * @returns {*} the value returned by the invoked `fn` function.
  3145. */
  3146. /**
  3147. * @ngdoc method
  3148. * @name $injector#has
  3149. *
  3150. * @description
  3151. * Allows the user to query if the particular service exists.
  3152. *
  3153. * @param {string} name Name of the service to query.
  3154. * @returns {boolean} `true` if injector has given service.
  3155. */
  3156. /**
  3157. * @ngdoc method
  3158. * @name $injector#instantiate
  3159. * @description
  3160. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3161. * operator, and supplies all of the arguments to the constructor function as specified by the
  3162. * constructor annotation.
  3163. *
  3164. * @param {Function} Type Annotated constructor function.
  3165. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3166. * object first, before the `$injector` is consulted.
  3167. * @returns {Object} new instance of `Type`.
  3168. */
  3169. /**
  3170. * @ngdoc method
  3171. * @name $injector#annotate
  3172. *
  3173. * @description
  3174. * Returns an array of service names which the function is requesting for injection. This API is
  3175. * used by the injector to determine which services need to be injected into the function when the
  3176. * function is invoked. There are three ways in which the function can be annotated with the needed
  3177. * dependencies.
  3178. *
  3179. * # Argument names
  3180. *
  3181. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3182. * by converting the function into a string using `toString()` method and extracting the argument
  3183. * names.
  3184. * ```js
  3185. * // Given
  3186. * function MyController($scope, $route) {
  3187. * // ...
  3188. * }
  3189. *
  3190. * // Then
  3191. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3192. * ```
  3193. *
  3194. * This method does not work with code minification / obfuscation. For this reason the following
  3195. * annotation strategies are supported.
  3196. *
  3197. * # The `$inject` property
  3198. *
  3199. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3200. * represent names of services to be injected into the function.
  3201. * ```js
  3202. * // Given
  3203. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3204. * // ...
  3205. * }
  3206. * // Define function dependencies
  3207. * MyController['$inject'] = ['$scope', '$route'];
  3208. *
  3209. * // Then
  3210. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3211. * ```
  3212. *
  3213. * # The array notation
  3214. *
  3215. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3216. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3217. * a way that survives minification is a better choice:
  3218. *
  3219. * ```js
  3220. * // We wish to write this (not minification / obfuscation safe)
  3221. * injector.invoke(function($compile, $rootScope) {
  3222. * // ...
  3223. * });
  3224. *
  3225. * // We are forced to write break inlining
  3226. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3227. * // ...
  3228. * };
  3229. * tmpFn.$inject = ['$compile', '$rootScope'];
  3230. * injector.invoke(tmpFn);
  3231. *
  3232. * // To better support inline function the inline annotation is supported
  3233. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3234. * // ...
  3235. * }]);
  3236. *
  3237. * // Therefore
  3238. * expect(injector.annotate(
  3239. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3240. * ).toEqual(['$compile', '$rootScope']);
  3241. * ```
  3242. *
  3243. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3244. * be retrieved as described above.
  3245. *
  3246. * @returns {Array.<string>} The names of the services which the function requires.
  3247. */
  3248. /**
  3249. * @ngdoc service
  3250. * @name $provide
  3251. *
  3252. * @description
  3253. *
  3254. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3255. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3256. * {@link angular.Module}.
  3257. *
  3258. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3259. * factories** are functions which, in turn, are created by a **service provider**.
  3260. * The **service providers** are constructor functions. When instantiated they must contain a
  3261. * property called `$get`, which holds the **service factory** function.
  3262. *
  3263. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3264. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3265. * function to get the instance of the **service**.
  3266. *
  3267. * Often services have no configuration options and there is no need to add methods to the service
  3268. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3269. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3270. * services without specifying a provider.
  3271. *
  3272. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3273. * {@link auto.$injector $injector}
  3274. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3275. * providers and services.
  3276. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3277. * services, not providers.
  3278. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3279. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3280. * given factory function.
  3281. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3282. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3283. * a new object using the given constructor function.
  3284. *
  3285. * See the individual methods for more information and examples.
  3286. */
  3287. /**
  3288. * @ngdoc method
  3289. * @name $provide#provider
  3290. * @description
  3291. *
  3292. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3293. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3294. * service.
  3295. *
  3296. * Service provider names start with the name of the service they provide followed by `Provider`.
  3297. * For example, the {@link ng.$log $log} service has a provider called
  3298. * {@link ng.$logProvider $logProvider}.
  3299. *
  3300. * Service provider objects can have additional methods which allow configuration of the provider
  3301. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3302. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3303. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3304. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3305. * console or not.
  3306. *
  3307. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3308. 'Provider'` key.
  3309. * @param {(Object|function())} provider If the provider is:
  3310. *
  3311. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3312. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3313. * - `Constructor`: a new instance of the provider will be created using
  3314. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3315. *
  3316. * @returns {Object} registered provider instance
  3317. * @example
  3318. *
  3319. * The following example shows how to create a simple event tracking service and register it using
  3320. * {@link auto.$provide#provider $provide.provider()}.
  3321. *
  3322. * ```js
  3323. * // Define the eventTracker provider
  3324. * function EventTrackerProvider() {
  3325. * var trackingUrl = '/track';
  3326. *
  3327. * // A provider method for configuring where the tracked events should been saved
  3328. * this.setTrackingUrl = function(url) {
  3329. * trackingUrl = url;
  3330. * };
  3331. *
  3332. * // The service factory function
  3333. * this.$get = ['$http', function($http) {
  3334. * var trackedEvents = {};
  3335. * return {
  3336. * // Call this to track an event
  3337. * event: function(event) {
  3338. * var count = trackedEvents[event] || 0;
  3339. * count += 1;
  3340. * trackedEvents[event] = count;
  3341. * return count;
  3342. * },
  3343. * // Call this to save the tracked events to the trackingUrl
  3344. * save: function() {
  3345. * $http.post(trackingUrl, trackedEvents);
  3346. * }
  3347. * };
  3348. * }];
  3349. * }
  3350. *
  3351. * describe('eventTracker', function() {
  3352. * var postSpy;
  3353. *
  3354. * beforeEach(module(function($provide) {
  3355. * // Register the eventTracker provider
  3356. * $provide.provider('eventTracker', EventTrackerProvider);
  3357. * }));
  3358. *
  3359. * beforeEach(module(function(eventTrackerProvider) {
  3360. * // Configure eventTracker provider
  3361. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3362. * }));
  3363. *
  3364. * it('tracks events', inject(function(eventTracker) {
  3365. * expect(eventTracker.event('login')).toEqual(1);
  3366. * expect(eventTracker.event('login')).toEqual(2);
  3367. * }));
  3368. *
  3369. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3370. * postSpy = spyOn($http, 'post');
  3371. * eventTracker.event('login');
  3372. * eventTracker.save();
  3373. * expect(postSpy).toHaveBeenCalled();
  3374. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3375. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3376. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3377. * }));
  3378. * });
  3379. * ```
  3380. */
  3381. /**
  3382. * @ngdoc method
  3383. * @name $provide#factory
  3384. * @description
  3385. *
  3386. * Register a **service factory**, which will be called to return the service instance.
  3387. * This is short for registering a service where its provider consists of only a `$get` property,
  3388. * which is the given service factory function.
  3389. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3390. * configure your service in a provider.
  3391. *
  3392. * @param {string} name The name of the instance.
  3393. * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
  3394. * for `$provide.provider(name, {$get: $getFn})`.
  3395. * @returns {Object} registered provider instance
  3396. *
  3397. * @example
  3398. * Here is an example of registering a service
  3399. * ```js
  3400. * $provide.factory('ping', ['$http', function($http) {
  3401. * return function ping() {
  3402. * return $http.send('/ping');
  3403. * };
  3404. * }]);
  3405. * ```
  3406. * You would then inject and use this service like this:
  3407. * ```js
  3408. * someModule.controller('Ctrl', ['ping', function(ping) {
  3409. * ping();
  3410. * }]);
  3411. * ```
  3412. */
  3413. /**
  3414. * @ngdoc method
  3415. * @name $provide#service
  3416. * @description
  3417. *
  3418. * Register a **service constructor**, which will be invoked with `new` to create the service
  3419. * instance.
  3420. * This is short for registering a service where its provider's `$get` property is the service
  3421. * constructor function that will be used to instantiate the service instance.
  3422. *
  3423. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3424. * as a type/class.
  3425. *
  3426. * @param {string} name The name of the instance.
  3427. * @param {Function} constructor A class (constructor function) that will be instantiated.
  3428. * @returns {Object} registered provider instance
  3429. *
  3430. * @example
  3431. * Here is an example of registering a service using
  3432. * {@link auto.$provide#service $provide.service(class)}.
  3433. * ```js
  3434. * var Ping = function($http) {
  3435. * this.$http = $http;
  3436. * };
  3437. *
  3438. * Ping.$inject = ['$http'];
  3439. *
  3440. * Ping.prototype.send = function() {
  3441. * return this.$http.get('/ping');
  3442. * };
  3443. * $provide.service('ping', Ping);
  3444. * ```
  3445. * You would then inject and use this service like this:
  3446. * ```js
  3447. * someModule.controller('Ctrl', ['ping', function(ping) {
  3448. * ping.send();
  3449. * }]);
  3450. * ```
  3451. */
  3452. /**
  3453. * @ngdoc method
  3454. * @name $provide#value
  3455. * @description
  3456. *
  3457. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3458. * number, an array, an object or a function. This is short for registering a service where its
  3459. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3460. * service**.
  3461. *
  3462. * Value services are similar to constant services, except that they cannot be injected into a
  3463. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3464. * an Angular
  3465. * {@link auto.$provide#decorator decorator}.
  3466. *
  3467. * @param {string} name The name of the instance.
  3468. * @param {*} value The value.
  3469. * @returns {Object} registered provider instance
  3470. *
  3471. * @example
  3472. * Here are some examples of creating value services.
  3473. * ```js
  3474. * $provide.value('ADMIN_USER', 'admin');
  3475. *
  3476. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3477. *
  3478. * $provide.value('halfOf', function(value) {
  3479. * return value / 2;
  3480. * });
  3481. * ```
  3482. */
  3483. /**
  3484. * @ngdoc method
  3485. * @name $provide#constant
  3486. * @description
  3487. *
  3488. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3489. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3490. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3491. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3492. *
  3493. * @param {string} name The name of the constant.
  3494. * @param {*} value The constant value.
  3495. * @returns {Object} registered instance
  3496. *
  3497. * @example
  3498. * Here a some examples of creating constants:
  3499. * ```js
  3500. * $provide.constant('SHARD_HEIGHT', 306);
  3501. *
  3502. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3503. *
  3504. * $provide.constant('double', function(value) {
  3505. * return value * 2;
  3506. * });
  3507. * ```
  3508. */
  3509. /**
  3510. * @ngdoc method
  3511. * @name $provide#decorator
  3512. * @description
  3513. *
  3514. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3515. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3516. * service. The object returned by the decorator may be the original service, or a new service
  3517. * object which replaces or wraps and delegates to the original service.
  3518. *
  3519. * @param {string} name The name of the service to decorate.
  3520. * @param {function()} decorator This function will be invoked when the service needs to be
  3521. * instantiated and should return the decorated service instance. The function is called using
  3522. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3523. * Local injection arguments:
  3524. *
  3525. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3526. * decorated or delegated to.
  3527. *
  3528. * @example
  3529. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3530. * calls to {@link ng.$log#error $log.warn()}.
  3531. * ```js
  3532. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3533. * $delegate.warn = $delegate.error;
  3534. * return $delegate;
  3535. * }]);
  3536. * ```
  3537. */
  3538. function createInjector(modulesToLoad, strictDi) {
  3539. strictDi = (strictDi === true);
  3540. var INSTANTIATING = {},
  3541. providerSuffix = 'Provider',
  3542. path = [],
  3543. loadedModules = new HashMap([], true),
  3544. providerCache = {
  3545. $provide: {
  3546. provider: supportObject(provider),
  3547. factory: supportObject(factory),
  3548. service: supportObject(service),
  3549. value: supportObject(value),
  3550. constant: supportObject(constant),
  3551. decorator: decorator
  3552. }
  3553. },
  3554. providerInjector = (providerCache.$injector =
  3555. createInternalInjector(providerCache, function() {
  3556. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3557. })),
  3558. instanceCache = {},
  3559. instanceInjector = (instanceCache.$injector =
  3560. createInternalInjector(instanceCache, function(servicename) {
  3561. var provider = providerInjector.get(servicename + providerSuffix);
  3562. return instanceInjector.invoke(provider.$get, provider, undefined, servicename);
  3563. }));
  3564. forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
  3565. return instanceInjector;
  3566. ////////////////////////////////////
  3567. // $provider
  3568. ////////////////////////////////////
  3569. function supportObject(delegate) {
  3570. return function(key, value) {
  3571. if (isObject(key)) {
  3572. forEach(key, reverseParams(delegate));
  3573. } else {
  3574. return delegate(key, value);
  3575. }
  3576. };
  3577. }
  3578. function provider(name, provider_) {
  3579. assertNotHasOwnProperty(name, 'service');
  3580. if (isFunction(provider_) || isArray(provider_)) {
  3581. provider_ = providerInjector.instantiate(provider_);
  3582. }
  3583. if (!provider_.$get) {
  3584. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3585. }
  3586. return providerCache[name + providerSuffix] = provider_;
  3587. }
  3588. function enforceReturnValue(name, factory) {
  3589. return function enforcedReturnValue() {
  3590. var result = instanceInjector.invoke(factory, this, undefined, name);
  3591. if (isUndefined(result)) {
  3592. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3593. }
  3594. return result;
  3595. };
  3596. }
  3597. function factory(name, factoryFn, enforce) {
  3598. return provider(name, {
  3599. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3600. });
  3601. }
  3602. function service(name, constructor) {
  3603. return factory(name, ['$injector', function($injector) {
  3604. return $injector.instantiate(constructor);
  3605. }]);
  3606. }
  3607. function value(name, val) { return factory(name, valueFn(val), false); }
  3608. function constant(name, value) {
  3609. assertNotHasOwnProperty(name, 'constant');
  3610. providerCache[name] = value;
  3611. instanceCache[name] = value;
  3612. }
  3613. function decorator(serviceName, decorFn) {
  3614. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3615. orig$get = origProvider.$get;
  3616. origProvider.$get = function() {
  3617. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3618. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3619. };
  3620. }
  3621. ////////////////////////////////////
  3622. // Module Loading
  3623. ////////////////////////////////////
  3624. function loadModules(modulesToLoad){
  3625. var runBlocks = [], moduleFn;
  3626. forEach(modulesToLoad, function(module) {
  3627. if (loadedModules.get(module)) return;
  3628. loadedModules.put(module, true);
  3629. function runInvokeQueue(queue) {
  3630. var i, ii;
  3631. for(i = 0, ii = queue.length; i < ii; i++) {
  3632. var invokeArgs = queue[i],
  3633. provider = providerInjector.get(invokeArgs[0]);
  3634. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3635. }
  3636. }
  3637. try {
  3638. if (isString(module)) {
  3639. moduleFn = angularModule(module);
  3640. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3641. runInvokeQueue(moduleFn._invokeQueue);
  3642. runInvokeQueue(moduleFn._configBlocks);
  3643. } else if (isFunction(module)) {
  3644. runBlocks.push(providerInjector.invoke(module));
  3645. } else if (isArray(module)) {
  3646. runBlocks.push(providerInjector.invoke(module));
  3647. } else {
  3648. assertArgFn(module, 'module');
  3649. }
  3650. } catch (e) {
  3651. if (isArray(module)) {
  3652. module = module[module.length - 1];
  3653. }
  3654. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3655. // Safari & FF's stack traces don't contain error.message content
  3656. // unlike those of Chrome and IE
  3657. // So if stack doesn't contain message, we create a new string that contains both.
  3658. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3659. /* jshint -W022 */
  3660. e = e.message + '\n' + e.stack;
  3661. }
  3662. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3663. module, e.stack || e.message || e);
  3664. }
  3665. });
  3666. return runBlocks;
  3667. }
  3668. ////////////////////////////////////
  3669. // internal Injector
  3670. ////////////////////////////////////
  3671. function createInternalInjector(cache, factory) {
  3672. function getService(serviceName) {
  3673. if (cache.hasOwnProperty(serviceName)) {
  3674. if (cache[serviceName] === INSTANTIATING) {
  3675. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  3676. serviceName + ' <- ' + path.join(' <- '));
  3677. }
  3678. return cache[serviceName];
  3679. } else {
  3680. try {
  3681. path.unshift(serviceName);
  3682. cache[serviceName] = INSTANTIATING;
  3683. return cache[serviceName] = factory(serviceName);
  3684. } catch (err) {
  3685. if (cache[serviceName] === INSTANTIATING) {
  3686. delete cache[serviceName];
  3687. }
  3688. throw err;
  3689. } finally {
  3690. path.shift();
  3691. }
  3692. }
  3693. }
  3694. function invoke(fn, self, locals, serviceName) {
  3695. if (typeof locals === 'string') {
  3696. serviceName = locals;
  3697. locals = null;
  3698. }
  3699. var args = [],
  3700. $inject = annotate(fn, strictDi, serviceName),
  3701. length, i,
  3702. key;
  3703. for(i = 0, length = $inject.length; i < length; i++) {
  3704. key = $inject[i];
  3705. if (typeof key !== 'string') {
  3706. throw $injectorMinErr('itkn',
  3707. 'Incorrect injection token! Expected service name as string, got {0}', key);
  3708. }
  3709. args.push(
  3710. locals && locals.hasOwnProperty(key)
  3711. ? locals[key]
  3712. : getService(key)
  3713. );
  3714. }
  3715. if (isArray(fn)) {
  3716. fn = fn[length];
  3717. }
  3718. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  3719. // #5388
  3720. return fn.apply(self, args);
  3721. }
  3722. function instantiate(Type, locals, serviceName) {
  3723. var Constructor = function() {},
  3724. instance, returnedValue;
  3725. // Check if Type is annotated and use just the given function at n-1 as parameter
  3726. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  3727. Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
  3728. instance = new Constructor();
  3729. returnedValue = invoke(Type, instance, locals, serviceName);
  3730. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  3731. }
  3732. return {
  3733. invoke: invoke,
  3734. instantiate: instantiate,
  3735. get: getService,
  3736. annotate: annotate,
  3737. has: function(name) {
  3738. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  3739. }
  3740. };
  3741. }
  3742. }
  3743. createInjector.$$annotate = annotate;
  3744. /**
  3745. * @ngdoc provider
  3746. * @name $anchorScrollProvider
  3747. *
  3748. * @description
  3749. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  3750. * {@link ng.$location#hash $location.hash()} changes.
  3751. */
  3752. function $AnchorScrollProvider() {
  3753. var autoScrollingEnabled = true;
  3754. /**
  3755. * @ngdoc method
  3756. * @name $anchorScrollProvider#disableAutoScrolling
  3757. *
  3758. * @description
  3759. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically will detect changes to
  3760. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  3761. * Use this method to disable automatic scrolling.
  3762. *
  3763. * If automatic scrolling is disabled, one must explicitly call
  3764. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  3765. * current hash.
  3766. */
  3767. this.disableAutoScrolling = function() {
  3768. autoScrollingEnabled = false;
  3769. };
  3770. /**
  3771. * @ngdoc service
  3772. * @name $anchorScroll
  3773. * @kind function
  3774. * @requires $window
  3775. * @requires $location
  3776. * @requires $rootScope
  3777. *
  3778. * @description
  3779. * When called, it checks the current value of {@link ng.$location#hash $location.hash()} and
  3780. * scrolls to the related element, according to the rules specified in the
  3781. * [Html5 spec](http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document).
  3782. *
  3783. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  3784. * match any anchor whenever it changes. This can be disabled by calling
  3785. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  3786. *
  3787. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  3788. * vertical scroll-offset (either fixed or dynamic).
  3789. *
  3790. * @property {(number|function|jqLite)} yOffset
  3791. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  3792. * positioned elements at the top of the page, such as navbars, headers etc.
  3793. *
  3794. * `yOffset` can be specified in various ways:
  3795. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  3796. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  3797. * a number representing the offset (in pixels).<br /><br />
  3798. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  3799. * the top of the page to the element's bottom will be used as offset.<br />
  3800. * **Note**: The element will be taken into account only as long as its `position` is set to
  3801. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  3802. * their height and/or positioning according to the viewport's size.
  3803. *
  3804. * <br />
  3805. * <div class="alert alert-warning">
  3806. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  3807. * not some child element.
  3808. * </div>
  3809. *
  3810. * @example
  3811. <example module="anchorScrollExample">
  3812. <file name="index.html">
  3813. <div id="scrollArea" ng-controller="ScrollController">
  3814. <a ng-click="gotoBottom()">Go to bottom</a>
  3815. <a id="bottom"></a> You're at the bottom!
  3816. </div>
  3817. </file>
  3818. <file name="script.js">
  3819. angular.module('anchorScrollExample', [])
  3820. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  3821. function ($scope, $location, $anchorScroll) {
  3822. $scope.gotoBottom = function() {
  3823. // set the location.hash to the id of
  3824. // the element you wish to scroll to.
  3825. $location.hash('bottom');
  3826. // call $anchorScroll()
  3827. $anchorScroll();
  3828. };
  3829. }]);
  3830. </file>
  3831. <file name="style.css">
  3832. #scrollArea {
  3833. height: 280px;
  3834. overflow: auto;
  3835. }
  3836. #bottom {
  3837. display: block;
  3838. margin-top: 2000px;
  3839. }
  3840. </file>
  3841. </example>
  3842. *
  3843. * <hr />
  3844. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  3845. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  3846. *
  3847. * @example
  3848. <example module="anchorScrollOffsetExample">
  3849. <file name="index.html">
  3850. <div class="fixed-header" ng-controller="headerCtrl">
  3851. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  3852. Go to anchor {{x}}
  3853. </a>
  3854. </div>
  3855. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  3856. Anchor {{x}} of 5
  3857. </div>
  3858. </file>
  3859. <file name="script.js">
  3860. angular.module('anchorScrollOffsetExample', [])
  3861. .run(['$anchorScroll', function($anchorScroll) {
  3862. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  3863. }])
  3864. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  3865. function ($anchorScroll, $location, $scope) {
  3866. $scope.gotoAnchor = function(x) {
  3867. var newHash = 'anchor' + x;
  3868. if ($location.hash() !== newHash) {
  3869. // set the $location.hash to `newHash` and
  3870. // $anchorScroll will automatically scroll to it
  3871. $location.hash('anchor' + x);
  3872. } else {
  3873. // call $anchorScroll() explicitly,
  3874. // since $location.hash hasn't changed
  3875. $anchorScroll();
  3876. }
  3877. };
  3878. }
  3879. ]);
  3880. </file>
  3881. <file name="style.css">
  3882. body {
  3883. padding-top: 50px;
  3884. }
  3885. .anchor {
  3886. border: 2px dashed DarkOrchid;
  3887. padding: 10px 10px 200px 10px;
  3888. }
  3889. .fixed-header {
  3890. background-color: rgba(0, 0, 0, 0.2);
  3891. height: 50px;
  3892. position: fixed;
  3893. top: 0; left: 0; right: 0;
  3894. }
  3895. .fixed-header > a {
  3896. display: inline-block;
  3897. margin: 5px 15px;
  3898. }
  3899. </file>
  3900. </example>
  3901. */
  3902. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  3903. var document = $window.document;
  3904. var scrollScheduled = false;
  3905. // Helper function to get first anchor from a NodeList
  3906. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  3907. // and working in all supported browsers.)
  3908. function getFirstAnchor(list) {
  3909. var result = null;
  3910. Array.prototype.some.call(list, function(element) {
  3911. if (nodeName_(element) === 'a') {
  3912. result = element;
  3913. return true;
  3914. }
  3915. });
  3916. return result;
  3917. }
  3918. function getYOffset() {
  3919. var offset = scroll.yOffset;
  3920. if (isFunction(offset)) {
  3921. offset = offset();
  3922. } else if (isElement(offset)) {
  3923. var elem = offset[0];
  3924. var style = $window.getComputedStyle(elem);
  3925. if (style.position !== 'fixed') {
  3926. offset = 0;
  3927. } else {
  3928. offset = elem.getBoundingClientRect().bottom;
  3929. }
  3930. } else if (!isNumber(offset)) {
  3931. offset = 0;
  3932. }
  3933. return offset;
  3934. }
  3935. function scrollTo(elem) {
  3936. if (elem) {
  3937. elem.scrollIntoView();
  3938. var offset = getYOffset();
  3939. if (offset) {
  3940. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  3941. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  3942. // top of the viewport.
  3943. //
  3944. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  3945. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  3946. // way down the page.
  3947. //
  3948. // This is often the case for elements near the bottom of the page.
  3949. //
  3950. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  3951. // the top of the element and the offset, which is enough to align the top of `elem` at the
  3952. // desired position.
  3953. var elemTop = elem.getBoundingClientRect().top;
  3954. $window.scrollBy(0, elemTop - offset);
  3955. }
  3956. } else {
  3957. $window.scrollTo(0, 0);
  3958. }
  3959. }
  3960. function scroll() {
  3961. var hash = $location.hash(), elm;
  3962. // empty hash, scroll to the top of the page
  3963. if (!hash) scrollTo(null);
  3964. // element with given id
  3965. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  3966. // first anchor with given name :-D
  3967. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  3968. // no element and hash == 'top', scroll to the top of the page
  3969. else if (hash === 'top') scrollTo(null);
  3970. }
  3971. // does not scroll when user clicks on anchor link that is currently on
  3972. // (no url change, no $location.hash() change), browser native does scroll
  3973. if (autoScrollingEnabled) {
  3974. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  3975. function autoScrollWatchAction(newVal, oldVal) {
  3976. // skip the initial scroll if $location.hash is empty
  3977. if (newVal === oldVal && newVal === '') return;
  3978. jqLiteDocumentLoaded(function() {
  3979. $rootScope.$evalAsync(scroll);
  3980. });
  3981. });
  3982. }
  3983. return scroll;
  3984. }];
  3985. }
  3986. var $animateMinErr = minErr('$animate');
  3987. /**
  3988. * @ngdoc provider
  3989. * @name $animateProvider
  3990. *
  3991. * @description
  3992. * Default implementation of $animate that doesn't perform any animations, instead just
  3993. * synchronously performs DOM
  3994. * updates and calls done() callbacks.
  3995. *
  3996. * In order to enable animations the ngAnimate module has to be loaded.
  3997. *
  3998. * To see the functional implementation check out src/ngAnimate/animate.js
  3999. */
  4000. var $AnimateProvider = ['$provide', function($provide) {
  4001. this.$$selectors = {};
  4002. /**
  4003. * @ngdoc method
  4004. * @name $animateProvider#register
  4005. *
  4006. * @description
  4007. * Registers a new injectable animation factory function. The factory function produces the
  4008. * animation object which contains callback functions for each event that is expected to be
  4009. * animated.
  4010. *
  4011. * * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
  4012. * must be called once the element animation is complete. If a function is returned then the
  4013. * animation service will use this function to cancel the animation whenever a cancel event is
  4014. * triggered.
  4015. *
  4016. *
  4017. * ```js
  4018. * return {
  4019. * eventFn : function(element, done) {
  4020. * //code to run the animation
  4021. * //once complete, then run done()
  4022. * return function cancellationFunction() {
  4023. * //code to cancel the animation
  4024. * }
  4025. * }
  4026. * }
  4027. * ```
  4028. *
  4029. * @param {string} name The name of the animation.
  4030. * @param {Function} factory The factory function that will be executed to return the animation
  4031. * object.
  4032. */
  4033. this.register = function(name, factory) {
  4034. var key = name + '-animation';
  4035. if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
  4036. "Expecting class selector starting with '.' got '{0}'.", name);
  4037. this.$$selectors[name.substr(1)] = key;
  4038. $provide.factory(key, factory);
  4039. };
  4040. /**
  4041. * @ngdoc method
  4042. * @name $animateProvider#classNameFilter
  4043. *
  4044. * @description
  4045. * Sets and/or returns the CSS class regular expression that is checked when performing
  4046. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4047. * therefore enable $animate to attempt to perform an animation on any element.
  4048. * When setting the classNameFilter value, animations will only be performed on elements
  4049. * that successfully match the filter expression. This in turn can boost performance
  4050. * for low-powered devices as well as applications containing a lot of structural operations.
  4051. * @param {RegExp=} expression The className expression which will be checked against all animations
  4052. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4053. */
  4054. this.classNameFilter = function(expression) {
  4055. if(arguments.length === 1) {
  4056. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4057. }
  4058. return this.$$classNameFilter;
  4059. };
  4060. this.$get = ['$$q', '$$asyncCallback', '$rootScope', function($$q, $$asyncCallback, $rootScope) {
  4061. var currentDefer;
  4062. function runAnimationPostDigest(fn) {
  4063. var cancelFn, defer = $$q.defer();
  4064. defer.promise.$$cancelFn = function ngAnimateMaybeCancel() {
  4065. cancelFn && cancelFn();
  4066. };
  4067. $rootScope.$$postDigest(function ngAnimatePostDigest() {
  4068. cancelFn = fn(function ngAnimateNotifyComplete() {
  4069. defer.resolve();
  4070. });
  4071. });
  4072. return defer.promise;
  4073. }
  4074. function resolveElementClasses(element, classes) {
  4075. var toAdd = [], toRemove = [];
  4076. var hasClasses = createMap();
  4077. forEach((element.attr('class') || '').split(/\s+/), function(className) {
  4078. hasClasses[className] = true;
  4079. });
  4080. forEach(classes, function(status, className) {
  4081. var hasClass = hasClasses[className];
  4082. // If the most recent class manipulation (via $animate) was to remove the class, and the
  4083. // element currently has the class, the class is scheduled for removal. Otherwise, if
  4084. // the most recent class manipulation (via $animate) was to add the class, and the
  4085. // element does not currently have the class, the class is scheduled to be added.
  4086. if (status === false && hasClass) {
  4087. toRemove.push(className);
  4088. } else if (status === true && !hasClass) {
  4089. toAdd.push(className);
  4090. }
  4091. });
  4092. return (toAdd.length + toRemove.length) > 0 &&
  4093. [toAdd.length ? toAdd : null, toRemove.length ? toRemove : null];
  4094. }
  4095. function cachedClassManipulation(cache, classes, op) {
  4096. for (var i=0, ii = classes.length; i < ii; ++i) {
  4097. var className = classes[i];
  4098. cache[className] = op;
  4099. }
  4100. }
  4101. function asyncPromise() {
  4102. // only serve one instance of a promise in order to save CPU cycles
  4103. if (!currentDefer) {
  4104. currentDefer = $$q.defer();
  4105. $$asyncCallback(function() {
  4106. currentDefer.resolve();
  4107. currentDefer = null;
  4108. });
  4109. }
  4110. return currentDefer.promise;
  4111. }
  4112. function applyStyles(element, options) {
  4113. if (angular.isObject(options)) {
  4114. var styles = extend(options.from || {}, options.to || {});
  4115. element.css(styles);
  4116. }
  4117. }
  4118. /**
  4119. *
  4120. * @ngdoc service
  4121. * @name $animate
  4122. * @description The $animate service provides rudimentary DOM manipulation functions to
  4123. * insert, remove and move elements within the DOM, as well as adding and removing classes.
  4124. * This service is the core service used by the ngAnimate $animator service which provides
  4125. * high-level animation hooks for CSS and JavaScript.
  4126. *
  4127. * $animate is available in the AngularJS core, however, the ngAnimate module must be included
  4128. * to enable full out animation support. Otherwise, $animate will only perform simple DOM
  4129. * manipulation operations.
  4130. *
  4131. * To learn more about enabling animation support, click here to visit the {@link ngAnimate
  4132. * ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
  4133. * page}.
  4134. */
  4135. return {
  4136. animate : function(element, from, to) {
  4137. applyStyles(element, { from: from, to: to });
  4138. return asyncPromise();
  4139. },
  4140. /**
  4141. *
  4142. * @ngdoc method
  4143. * @name $animate#enter
  4144. * @kind function
  4145. * @description Inserts the element into the DOM either after the `after` element or
  4146. * as the first child within the `parent` element. When the function is called a promise
  4147. * is returned that will be resolved at a later time.
  4148. * @param {DOMElement} element the element which will be inserted into the DOM
  4149. * @param {DOMElement} parent the parent element which will append the element as
  4150. * a child (if the after element is not present)
  4151. * @param {DOMElement} after the sibling element which will append the element
  4152. * after itself
  4153. * @param {object=} options an optional collection of styles that will be applied to the element.
  4154. * @return {Promise} the animation callback promise
  4155. */
  4156. enter : function(element, parent, after, options) {
  4157. applyStyles(element, options);
  4158. after ? after.after(element)
  4159. : parent.prepend(element);
  4160. return asyncPromise();
  4161. },
  4162. /**
  4163. *
  4164. * @ngdoc method
  4165. * @name $animate#leave
  4166. * @kind function
  4167. * @description Removes the element from the DOM. When the function is called a promise
  4168. * is returned that will be resolved at a later time.
  4169. * @param {DOMElement} element the element which will be removed from the DOM
  4170. * @param {object=} options an optional collection of options that will be applied to the element.
  4171. * @return {Promise} the animation callback promise
  4172. */
  4173. leave : function(element, options) {
  4174. element.remove();
  4175. return asyncPromise();
  4176. },
  4177. /**
  4178. *
  4179. * @ngdoc method
  4180. * @name $animate#move
  4181. * @kind function
  4182. * @description Moves the position of the provided element within the DOM to be placed
  4183. * either after the `after` element or inside of the `parent` element. When the function
  4184. * is called a promise is returned that will be resolved at a later time.
  4185. *
  4186. * @param {DOMElement} element the element which will be moved around within the
  4187. * DOM
  4188. * @param {DOMElement} parent the parent element where the element will be
  4189. * inserted into (if the after element is not present)
  4190. * @param {DOMElement} after the sibling element where the element will be
  4191. * positioned next to
  4192. * @param {object=} options an optional collection of options that will be applied to the element.
  4193. * @return {Promise} the animation callback promise
  4194. */
  4195. move : function(element, parent, after, options) {
  4196. // Do not remove element before insert. Removing will cause data associated with the
  4197. // element to be dropped. Insert will implicitly do the remove.
  4198. return this.enter(element, parent, after, options);
  4199. },
  4200. /**
  4201. *
  4202. * @ngdoc method
  4203. * @name $animate#addClass
  4204. * @kind function
  4205. * @description Adds the provided className CSS class value to the provided element.
  4206. * When the function is called a promise is returned that will be resolved at a later time.
  4207. * @param {DOMElement} element the element which will have the className value
  4208. * added to it
  4209. * @param {string} className the CSS class which will be added to the element
  4210. * @param {object=} options an optional collection of options that will be applied to the element.
  4211. * @return {Promise} the animation callback promise
  4212. */
  4213. addClass : function(element, className, options) {
  4214. return this.setClass(element, className, [], options);
  4215. },
  4216. $$addClassImmediately : function(element, className, options) {
  4217. element = jqLite(element);
  4218. className = !isString(className)
  4219. ? (isArray(className) ? className.join(' ') : '')
  4220. : className;
  4221. forEach(element, function (element) {
  4222. jqLiteAddClass(element, className);
  4223. });
  4224. applyStyles(element, options);
  4225. return asyncPromise();
  4226. },
  4227. /**
  4228. *
  4229. * @ngdoc method
  4230. * @name $animate#removeClass
  4231. * @kind function
  4232. * @description Removes the provided className CSS class value from the provided element.
  4233. * When the function is called a promise is returned that will be resolved at a later time.
  4234. * @param {DOMElement} element the element which will have the className value
  4235. * removed from it
  4236. * @param {string} className the CSS class which will be removed from the element
  4237. * @param {object=} options an optional collection of options that will be applied to the element.
  4238. * @return {Promise} the animation callback promise
  4239. */
  4240. removeClass : function(element, className, options) {
  4241. return this.setClass(element, [], className, options);
  4242. },
  4243. $$removeClassImmediately : function(element, className, options) {
  4244. element = jqLite(element);
  4245. className = !isString(className)
  4246. ? (isArray(className) ? className.join(' ') : '')
  4247. : className;
  4248. forEach(element, function (element) {
  4249. jqLiteRemoveClass(element, className);
  4250. });
  4251. applyStyles(element, options);
  4252. return asyncPromise();
  4253. },
  4254. /**
  4255. *
  4256. * @ngdoc method
  4257. * @name $animate#setClass
  4258. * @kind function
  4259. * @description Adds and/or removes the given CSS classes to and from the element.
  4260. * When the function is called a promise is returned that will be resolved at a later time.
  4261. * @param {DOMElement} element the element which will have its CSS classes changed
  4262. * removed from it
  4263. * @param {string} add the CSS classes which will be added to the element
  4264. * @param {string} remove the CSS class which will be removed from the element
  4265. * @param {object=} options an optional collection of options that will be applied to the element.
  4266. * @return {Promise} the animation callback promise
  4267. */
  4268. setClass : function(element, add, remove, options) {
  4269. var self = this;
  4270. var STORAGE_KEY = '$$animateClasses';
  4271. var createdCache = false;
  4272. element = jqLite(element);
  4273. var cache = element.data(STORAGE_KEY);
  4274. if (!cache) {
  4275. cache = {
  4276. classes: {},
  4277. options : options
  4278. };
  4279. createdCache = true;
  4280. } else if (options && cache.options) {
  4281. cache.options = angular.extend(cache.options || {}, options);
  4282. }
  4283. var classes = cache.classes;
  4284. add = isArray(add) ? add : add.split(' ');
  4285. remove = isArray(remove) ? remove : remove.split(' ');
  4286. cachedClassManipulation(classes, add, true);
  4287. cachedClassManipulation(classes, remove, false);
  4288. if (createdCache) {
  4289. cache.promise = runAnimationPostDigest(function(done) {
  4290. var cache = element.data(STORAGE_KEY);
  4291. element.removeData(STORAGE_KEY);
  4292. // in the event that the element is removed before postDigest
  4293. // is run then the cache will be undefined and there will be
  4294. // no need anymore to add or remove and of the element classes
  4295. if (cache) {
  4296. var classes = resolveElementClasses(element, cache.classes);
  4297. if (classes) {
  4298. self.$$setClassImmediately(element, classes[0], classes[1], cache.options);
  4299. }
  4300. }
  4301. done();
  4302. });
  4303. element.data(STORAGE_KEY, cache);
  4304. }
  4305. return cache.promise;
  4306. },
  4307. $$setClassImmediately : function(element, add, remove, options) {
  4308. add && this.$$addClassImmediately(element, add);
  4309. remove && this.$$removeClassImmediately(element, remove);
  4310. applyStyles(element, options);
  4311. return asyncPromise();
  4312. },
  4313. enabled : noop,
  4314. cancel : noop
  4315. };
  4316. }];
  4317. }];
  4318. function $$AsyncCallbackProvider(){
  4319. this.$get = ['$$rAF', '$timeout', function($$rAF, $timeout) {
  4320. return $$rAF.supported
  4321. ? function(fn) { return $$rAF(fn); }
  4322. : function(fn) {
  4323. return $timeout(fn, 0, false);
  4324. };
  4325. }];
  4326. }
  4327. /* global stripHash: true */
  4328. /**
  4329. * ! This is a private undocumented service !
  4330. *
  4331. * @name $browser
  4332. * @requires $log
  4333. * @description
  4334. * This object has two goals:
  4335. *
  4336. * - hide all the global state in the browser caused by the window object
  4337. * - abstract away all the browser specific features and inconsistencies
  4338. *
  4339. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4340. * service, which can be used for convenient testing of the application without the interaction with
  4341. * the real browser apis.
  4342. */
  4343. /**
  4344. * @param {object} window The global window object.
  4345. * @param {object} document jQuery wrapped document.
  4346. * @param {function()} XHR XMLHttpRequest constructor.
  4347. * @param {object} $log console.log or an object with the same interface.
  4348. * @param {object} $sniffer $sniffer service
  4349. */
  4350. function Browser(window, document, $log, $sniffer) {
  4351. var self = this,
  4352. rawDocument = document[0],
  4353. location = window.location,
  4354. history = window.history,
  4355. setTimeout = window.setTimeout,
  4356. clearTimeout = window.clearTimeout,
  4357. pendingDeferIds = {};
  4358. self.isMock = false;
  4359. var outstandingRequestCount = 0;
  4360. var outstandingRequestCallbacks = [];
  4361. // TODO(vojta): remove this temporary api
  4362. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4363. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4364. /**
  4365. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4366. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4367. */
  4368. function completeOutstandingRequest(fn) {
  4369. try {
  4370. fn.apply(null, sliceArgs(arguments, 1));
  4371. } finally {
  4372. outstandingRequestCount--;
  4373. if (outstandingRequestCount === 0) {
  4374. while(outstandingRequestCallbacks.length) {
  4375. try {
  4376. outstandingRequestCallbacks.pop()();
  4377. } catch (e) {
  4378. $log.error(e);
  4379. }
  4380. }
  4381. }
  4382. }
  4383. }
  4384. /**
  4385. * @private
  4386. * Note: this method is used only by scenario runner
  4387. * TODO(vojta): prefix this method with $$ ?
  4388. * @param {function()} callback Function that will be called when no outstanding request
  4389. */
  4390. self.notifyWhenNoOutstandingRequests = function(callback) {
  4391. // force browser to execute all pollFns - this is needed so that cookies and other pollers fire
  4392. // at some deterministic time in respect to the test runner's actions. Leaving things up to the
  4393. // regular poller would result in flaky tests.
  4394. forEach(pollFns, function(pollFn){ pollFn(); });
  4395. if (outstandingRequestCount === 0) {
  4396. callback();
  4397. } else {
  4398. outstandingRequestCallbacks.push(callback);
  4399. }
  4400. };
  4401. //////////////////////////////////////////////////////////////
  4402. // Poll Watcher API
  4403. //////////////////////////////////////////////////////////////
  4404. var pollFns = [],
  4405. pollTimeout;
  4406. /**
  4407. * @name $browser#addPollFn
  4408. *
  4409. * @param {function()} fn Poll function to add
  4410. *
  4411. * @description
  4412. * Adds a function to the list of functions that poller periodically executes,
  4413. * and starts polling if not started yet.
  4414. *
  4415. * @returns {function()} the added function
  4416. */
  4417. self.addPollFn = function(fn) {
  4418. if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
  4419. pollFns.push(fn);
  4420. return fn;
  4421. };
  4422. /**
  4423. * @param {number} interval How often should browser call poll functions (ms)
  4424. * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
  4425. *
  4426. * @description
  4427. * Configures the poller to run in the specified intervals, using the specified
  4428. * setTimeout fn and kicks it off.
  4429. */
  4430. function startPoller(interval, setTimeout) {
  4431. (function check() {
  4432. forEach(pollFns, function(pollFn){ pollFn(); });
  4433. pollTimeout = setTimeout(check, interval);
  4434. })();
  4435. }
  4436. //////////////////////////////////////////////////////////////
  4437. // URL API
  4438. //////////////////////////////////////////////////////////////
  4439. var cachedState, lastHistoryState,
  4440. lastBrowserUrl = location.href,
  4441. baseElement = document.find('base'),
  4442. reloadLocation = null;
  4443. cacheState();
  4444. lastHistoryState = cachedState;
  4445. /**
  4446. * @name $browser#url
  4447. *
  4448. * @description
  4449. * GETTER:
  4450. * Without any argument, this method just returns current value of location.href.
  4451. *
  4452. * SETTER:
  4453. * With at least one argument, this method sets url to new value.
  4454. * If html5 history api supported, pushState/replaceState is used, otherwise
  4455. * location.href/location.replace is used.
  4456. * Returns its own instance to allow chaining
  4457. *
  4458. * NOTE: this api is intended for use only by the $location service. Please use the
  4459. * {@link ng.$location $location service} to change url.
  4460. *
  4461. * @param {string} url New url (when used as setter)
  4462. * @param {boolean=} replace Should new url replace current history record?
  4463. * @param {object=} state object to use with pushState/replaceState
  4464. */
  4465. self.url = function(url, replace, state) {
  4466. // In modern browsers `history.state` is `null` by default; treating it separately
  4467. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  4468. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  4469. if (isUndefined(state)) {
  4470. state = null;
  4471. }
  4472. // Android Browser BFCache causes location, history reference to become stale.
  4473. if (location !== window.location) location = window.location;
  4474. if (history !== window.history) history = window.history;
  4475. // setter
  4476. if (url) {
  4477. var sameState = lastHistoryState === state;
  4478. // Don't change anything if previous and current URLs and states match. This also prevents
  4479. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  4480. // See https://github.com/angular/angular.js/commit/ffb2701
  4481. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  4482. return;
  4483. }
  4484. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  4485. lastBrowserUrl = url;
  4486. lastHistoryState = state;
  4487. // Don't use history API if only the hash changed
  4488. // due to a bug in IE10/IE11 which leads
  4489. // to not firing a `hashchange` nor `popstate` event
  4490. // in some cases (see #9143).
  4491. if ($sniffer.history && (!sameBase || !sameState)) {
  4492. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  4493. cacheState();
  4494. // Do the assignment again so that those two variables are referentially identical.
  4495. lastHistoryState = cachedState;
  4496. } else {
  4497. if (!sameBase) {
  4498. reloadLocation = url;
  4499. }
  4500. if (replace) {
  4501. location.replace(url);
  4502. } else {
  4503. location.href = url;
  4504. }
  4505. }
  4506. return self;
  4507. // getter
  4508. } else {
  4509. // - reloadLocation is needed as browsers don't allow to read out
  4510. // the new location.href if a reload happened.
  4511. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  4512. return reloadLocation || location.href.replace(/%27/g,"'");
  4513. }
  4514. };
  4515. /**
  4516. * @name $browser#state
  4517. *
  4518. * @description
  4519. * This method is a getter.
  4520. *
  4521. * Return history.state or null if history.state is undefined.
  4522. *
  4523. * @returns {object} state
  4524. */
  4525. self.state = function() {
  4526. return cachedState;
  4527. };
  4528. var urlChangeListeners = [],
  4529. urlChangeInit = false;
  4530. function cacheStateAndFireUrlChange() {
  4531. cacheState();
  4532. fireUrlChange();
  4533. }
  4534. // This variable should be used *only* inside the cacheState function.
  4535. var lastCachedState = null;
  4536. function cacheState() {
  4537. // This should be the only place in $browser where `history.state` is read.
  4538. cachedState = window.history.state;
  4539. cachedState = isUndefined(cachedState) ? null : cachedState;
  4540. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  4541. if (equals(cachedState, lastCachedState)) {
  4542. cachedState = lastCachedState;
  4543. }
  4544. lastCachedState = cachedState;
  4545. }
  4546. function fireUrlChange() {
  4547. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  4548. return;
  4549. }
  4550. lastBrowserUrl = self.url();
  4551. lastHistoryState = cachedState;
  4552. forEach(urlChangeListeners, function(listener) {
  4553. listener(self.url(), cachedState);
  4554. });
  4555. }
  4556. /**
  4557. * @name $browser#onUrlChange
  4558. *
  4559. * @description
  4560. * Register callback function that will be called, when url changes.
  4561. *
  4562. * It's only called when the url is changed from outside of angular:
  4563. * - user types different url into address bar
  4564. * - user clicks on history (forward/back) button
  4565. * - user clicks on a link
  4566. *
  4567. * It's not called when url is changed by $browser.url() method
  4568. *
  4569. * The listener gets called with new url as parameter.
  4570. *
  4571. * NOTE: this api is intended for use only by the $location service. Please use the
  4572. * {@link ng.$location $location service} to monitor url changes in angular apps.
  4573. *
  4574. * @param {function(string)} listener Listener function to be called when url changes.
  4575. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  4576. */
  4577. self.onUrlChange = function(callback) {
  4578. // TODO(vojta): refactor to use node's syntax for events
  4579. if (!urlChangeInit) {
  4580. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  4581. // don't fire popstate when user change the address bar and don't fire hashchange when url
  4582. // changed by push/replaceState
  4583. // html5 history api - popstate event
  4584. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  4585. // hashchange event
  4586. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  4587. urlChangeInit = true;
  4588. }
  4589. urlChangeListeners.push(callback);
  4590. return callback;
  4591. };
  4592. /**
  4593. * Checks whether the url has changed outside of Angular.
  4594. * Needs to be exported to be able to check for changes that have been done in sync,
  4595. * as hashchange/popstate events fire in async.
  4596. */
  4597. self.$$checkUrlChange = fireUrlChange;
  4598. //////////////////////////////////////////////////////////////
  4599. // Misc API
  4600. //////////////////////////////////////////////////////////////
  4601. /**
  4602. * @name $browser#baseHref
  4603. *
  4604. * @description
  4605. * Returns current <base href>
  4606. * (always relative - without domain)
  4607. *
  4608. * @returns {string} The current base href
  4609. */
  4610. self.baseHref = function() {
  4611. var href = baseElement.attr('href');
  4612. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  4613. };
  4614. //////////////////////////////////////////////////////////////
  4615. // Cookies API
  4616. //////////////////////////////////////////////////////////////
  4617. var lastCookies = {};
  4618. var lastCookieString = '';
  4619. var cookiePath = self.baseHref();
  4620. function safeDecodeURIComponent(str) {
  4621. try {
  4622. return decodeURIComponent(str);
  4623. } catch (e) {
  4624. return str;
  4625. }
  4626. }
  4627. /**
  4628. * @name $browser#cookies
  4629. *
  4630. * @param {string=} name Cookie name
  4631. * @param {string=} value Cookie value
  4632. *
  4633. * @description
  4634. * The cookies method provides a 'private' low level access to browser cookies.
  4635. * It is not meant to be used directly, use the $cookie service instead.
  4636. *
  4637. * The return values vary depending on the arguments that the method was called with as follows:
  4638. *
  4639. * - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
  4640. * it
  4641. * - cookies(name, value) -> set name to value, if value is undefined delete the cookie
  4642. * - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
  4643. * way)
  4644. *
  4645. * @returns {Object} Hash of all cookies (if called without any parameter)
  4646. */
  4647. self.cookies = function(name, value) {
  4648. var cookieLength, cookieArray, cookie, i, index;
  4649. if (name) {
  4650. if (value === undefined) {
  4651. rawDocument.cookie = encodeURIComponent(name) + "=;path=" + cookiePath +
  4652. ";expires=Thu, 01 Jan 1970 00:00:00 GMT";
  4653. } else {
  4654. if (isString(value)) {
  4655. cookieLength = (rawDocument.cookie = encodeURIComponent(name) + '=' + encodeURIComponent(value) +
  4656. ';path=' + cookiePath).length + 1;
  4657. // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
  4658. // - 300 cookies
  4659. // - 20 cookies per unique domain
  4660. // - 4096 bytes per cookie
  4661. if (cookieLength > 4096) {
  4662. $log.warn("Cookie '"+ name +
  4663. "' possibly not set or overflowed because it was too large ("+
  4664. cookieLength + " > 4096 bytes)!");
  4665. }
  4666. }
  4667. }
  4668. } else {
  4669. if (rawDocument.cookie !== lastCookieString) {
  4670. lastCookieString = rawDocument.cookie;
  4671. cookieArray = lastCookieString.split("; ");
  4672. lastCookies = {};
  4673. for (i = 0; i < cookieArray.length; i++) {
  4674. cookie = cookieArray[i];
  4675. index = cookie.indexOf('=');
  4676. if (index > 0) { //ignore nameless cookies
  4677. name = safeDecodeURIComponent(cookie.substring(0, index));
  4678. // the first value that is seen for a cookie is the most
  4679. // specific one. values for the same cookie name that
  4680. // follow are for less specific paths.
  4681. if (lastCookies[name] === undefined) {
  4682. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  4683. }
  4684. }
  4685. }
  4686. }
  4687. return lastCookies;
  4688. }
  4689. };
  4690. /**
  4691. * @name $browser#defer
  4692. * @param {function()} fn A function, who's execution should be deferred.
  4693. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  4694. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  4695. *
  4696. * @description
  4697. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  4698. *
  4699. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  4700. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  4701. * via `$browser.defer.flush()`.
  4702. *
  4703. */
  4704. self.defer = function(fn, delay) {
  4705. var timeoutId;
  4706. outstandingRequestCount++;
  4707. timeoutId = setTimeout(function() {
  4708. delete pendingDeferIds[timeoutId];
  4709. completeOutstandingRequest(fn);
  4710. }, delay || 0);
  4711. pendingDeferIds[timeoutId] = true;
  4712. return timeoutId;
  4713. };
  4714. /**
  4715. * @name $browser#defer.cancel
  4716. *
  4717. * @description
  4718. * Cancels a deferred task identified with `deferId`.
  4719. *
  4720. * @param {*} deferId Token returned by the `$browser.defer` function.
  4721. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  4722. * canceled.
  4723. */
  4724. self.defer.cancel = function(deferId) {
  4725. if (pendingDeferIds[deferId]) {
  4726. delete pendingDeferIds[deferId];
  4727. clearTimeout(deferId);
  4728. completeOutstandingRequest(noop);
  4729. return true;
  4730. }
  4731. return false;
  4732. };
  4733. }
  4734. function $BrowserProvider(){
  4735. this.$get = ['$window', '$log', '$sniffer', '$document',
  4736. function( $window, $log, $sniffer, $document){
  4737. return new Browser($window, $document, $log, $sniffer);
  4738. }];
  4739. }
  4740. /**
  4741. * @ngdoc service
  4742. * @name $cacheFactory
  4743. *
  4744. * @description
  4745. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  4746. * them.
  4747. *
  4748. * ```js
  4749. *
  4750. * var cache = $cacheFactory('cacheId');
  4751. * expect($cacheFactory.get('cacheId')).toBe(cache);
  4752. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  4753. *
  4754. * cache.put("key", "value");
  4755. * cache.put("another key", "another value");
  4756. *
  4757. * // We've specified no options on creation
  4758. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  4759. *
  4760. * ```
  4761. *
  4762. *
  4763. * @param {string} cacheId Name or id of the newly created cache.
  4764. * @param {object=} options Options object that specifies the cache behavior. Properties:
  4765. *
  4766. * - `{number=}` `capacity` — turns the cache into LRU cache.
  4767. *
  4768. * @returns {object} Newly created cache object with the following set of methods:
  4769. *
  4770. * - `{object}` `info()` — Returns id, size, and options of cache.
  4771. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  4772. * it.
  4773. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  4774. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  4775. * - `{void}` `removeAll()` — Removes all cached values.
  4776. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  4777. *
  4778. * @example
  4779. <example module="cacheExampleApp">
  4780. <file name="index.html">
  4781. <div ng-controller="CacheController">
  4782. <input ng-model="newCacheKey" placeholder="Key">
  4783. <input ng-model="newCacheValue" placeholder="Value">
  4784. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  4785. <p ng-if="keys.length">Cached Values</p>
  4786. <div ng-repeat="key in keys">
  4787. <span ng-bind="key"></span>
  4788. <span>: </span>
  4789. <b ng-bind="cache.get(key)"></b>
  4790. </div>
  4791. <p>Cache Info</p>
  4792. <div ng-repeat="(key, value) in cache.info()">
  4793. <span ng-bind="key"></span>
  4794. <span>: </span>
  4795. <b ng-bind="value"></b>
  4796. </div>
  4797. </div>
  4798. </file>
  4799. <file name="script.js">
  4800. angular.module('cacheExampleApp', []).
  4801. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  4802. $scope.keys = [];
  4803. $scope.cache = $cacheFactory('cacheId');
  4804. $scope.put = function(key, value) {
  4805. if ($scope.cache.get(key) === undefined) {
  4806. $scope.keys.push(key);
  4807. }
  4808. $scope.cache.put(key, value === undefined ? null : value);
  4809. };
  4810. }]);
  4811. </file>
  4812. <file name="style.css">
  4813. p {
  4814. margin: 10px 0 3px;
  4815. }
  4816. </file>
  4817. </example>
  4818. */
  4819. function $CacheFactoryProvider() {
  4820. this.$get = function() {
  4821. var caches = {};
  4822. function cacheFactory(cacheId, options) {
  4823. if (cacheId in caches) {
  4824. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  4825. }
  4826. var size = 0,
  4827. stats = extend({}, options, {id: cacheId}),
  4828. data = {},
  4829. capacity = (options && options.capacity) || Number.MAX_VALUE,
  4830. lruHash = {},
  4831. freshEnd = null,
  4832. staleEnd = null;
  4833. /**
  4834. * @ngdoc type
  4835. * @name $cacheFactory.Cache
  4836. *
  4837. * @description
  4838. * A cache object used to store and retrieve data, primarily used by
  4839. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  4840. * templates and other data.
  4841. *
  4842. * ```js
  4843. * angular.module('superCache')
  4844. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  4845. * return $cacheFactory('super-cache');
  4846. * }]);
  4847. * ```
  4848. *
  4849. * Example test:
  4850. *
  4851. * ```js
  4852. * it('should behave like a cache', inject(function(superCache) {
  4853. * superCache.put('key', 'value');
  4854. * superCache.put('another key', 'another value');
  4855. *
  4856. * expect(superCache.info()).toEqual({
  4857. * id: 'super-cache',
  4858. * size: 2
  4859. * });
  4860. *
  4861. * superCache.remove('another key');
  4862. * expect(superCache.get('another key')).toBeUndefined();
  4863. *
  4864. * superCache.removeAll();
  4865. * expect(superCache.info()).toEqual({
  4866. * id: 'super-cache',
  4867. * size: 0
  4868. * });
  4869. * }));
  4870. * ```
  4871. */
  4872. return caches[cacheId] = {
  4873. /**
  4874. * @ngdoc method
  4875. * @name $cacheFactory.Cache#put
  4876. * @kind function
  4877. *
  4878. * @description
  4879. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  4880. * retrieved later, and incrementing the size of the cache if the key was not already
  4881. * present in the cache. If behaving like an LRU cache, it will also remove stale
  4882. * entries from the set.
  4883. *
  4884. * It will not insert undefined values into the cache.
  4885. *
  4886. * @param {string} key the key under which the cached data is stored.
  4887. * @param {*} value the value to store alongside the key. If it is undefined, the key
  4888. * will not be stored.
  4889. * @returns {*} the value stored.
  4890. */
  4891. put: function(key, value) {
  4892. if (capacity < Number.MAX_VALUE) {
  4893. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  4894. refresh(lruEntry);
  4895. }
  4896. if (isUndefined(value)) return;
  4897. if (!(key in data)) size++;
  4898. data[key] = value;
  4899. if (size > capacity) {
  4900. this.remove(staleEnd.key);
  4901. }
  4902. return value;
  4903. },
  4904. /**
  4905. * @ngdoc method
  4906. * @name $cacheFactory.Cache#get
  4907. * @kind function
  4908. *
  4909. * @description
  4910. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  4911. *
  4912. * @param {string} key the key of the data to be retrieved
  4913. * @returns {*} the value stored.
  4914. */
  4915. get: function(key) {
  4916. if (capacity < Number.MAX_VALUE) {
  4917. var lruEntry = lruHash[key];
  4918. if (!lruEntry) return;
  4919. refresh(lruEntry);
  4920. }
  4921. return data[key];
  4922. },
  4923. /**
  4924. * @ngdoc method
  4925. * @name $cacheFactory.Cache#remove
  4926. * @kind function
  4927. *
  4928. * @description
  4929. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  4930. *
  4931. * @param {string} key the key of the entry to be removed
  4932. */
  4933. remove: function(key) {
  4934. if (capacity < Number.MAX_VALUE) {
  4935. var lruEntry = lruHash[key];
  4936. if (!lruEntry) return;
  4937. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  4938. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  4939. link(lruEntry.n,lruEntry.p);
  4940. delete lruHash[key];
  4941. }
  4942. delete data[key];
  4943. size--;
  4944. },
  4945. /**
  4946. * @ngdoc method
  4947. * @name $cacheFactory.Cache#removeAll
  4948. * @kind function
  4949. *
  4950. * @description
  4951. * Clears the cache object of any entries.
  4952. */
  4953. removeAll: function() {
  4954. data = {};
  4955. size = 0;
  4956. lruHash = {};
  4957. freshEnd = staleEnd = null;
  4958. },
  4959. /**
  4960. * @ngdoc method
  4961. * @name $cacheFactory.Cache#destroy
  4962. * @kind function
  4963. *
  4964. * @description
  4965. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  4966. * removing it from the {@link $cacheFactory $cacheFactory} set.
  4967. */
  4968. destroy: function() {
  4969. data = null;
  4970. stats = null;
  4971. lruHash = null;
  4972. delete caches[cacheId];
  4973. },
  4974. /**
  4975. * @ngdoc method
  4976. * @name $cacheFactory.Cache#info
  4977. * @kind function
  4978. *
  4979. * @description
  4980. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  4981. *
  4982. * @returns {object} an object with the following properties:
  4983. * <ul>
  4984. * <li>**id**: the id of the cache instance</li>
  4985. * <li>**size**: the number of entries kept in the cache instance</li>
  4986. * <li>**...**: any additional properties from the options object when creating the
  4987. * cache.</li>
  4988. * </ul>
  4989. */
  4990. info: function() {
  4991. return extend({}, stats, {size: size});
  4992. }
  4993. };
  4994. /**
  4995. * makes the `entry` the freshEnd of the LRU linked list
  4996. */
  4997. function refresh(entry) {
  4998. if (entry != freshEnd) {
  4999. if (!staleEnd) {
  5000. staleEnd = entry;
  5001. } else if (staleEnd == entry) {
  5002. staleEnd = entry.n;
  5003. }
  5004. link(entry.n, entry.p);
  5005. link(entry, freshEnd);
  5006. freshEnd = entry;
  5007. freshEnd.n = null;
  5008. }
  5009. }
  5010. /**
  5011. * bidirectionally links two entries of the LRU linked list
  5012. */
  5013. function link(nextEntry, prevEntry) {
  5014. if (nextEntry != prevEntry) {
  5015. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5016. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5017. }
  5018. }
  5019. }
  5020. /**
  5021. * @ngdoc method
  5022. * @name $cacheFactory#info
  5023. *
  5024. * @description
  5025. * Get information about all the caches that have been created
  5026. *
  5027. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5028. */
  5029. cacheFactory.info = function() {
  5030. var info = {};
  5031. forEach(caches, function(cache, cacheId) {
  5032. info[cacheId] = cache.info();
  5033. });
  5034. return info;
  5035. };
  5036. /**
  5037. * @ngdoc method
  5038. * @name $cacheFactory#get
  5039. *
  5040. * @description
  5041. * Get access to a cache object by the `cacheId` used when it was created.
  5042. *
  5043. * @param {string} cacheId Name or id of a cache to access.
  5044. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5045. */
  5046. cacheFactory.get = function(cacheId) {
  5047. return caches[cacheId];
  5048. };
  5049. return cacheFactory;
  5050. };
  5051. }
  5052. /**
  5053. * @ngdoc service
  5054. * @name $templateCache
  5055. *
  5056. * @description
  5057. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5058. * can load templates directly into the cache in a `script` tag, or by consuming the
  5059. * `$templateCache` service directly.
  5060. *
  5061. * Adding via the `script` tag:
  5062. *
  5063. * ```html
  5064. * <script type="text/ng-template" id="templateId.html">
  5065. * <p>This is the content of the template</p>
  5066. * </script>
  5067. * ```
  5068. *
  5069. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5070. * the document, but it must be below the `ng-app` definition.
  5071. *
  5072. * Adding via the $templateCache service:
  5073. *
  5074. * ```js
  5075. * var myApp = angular.module('myApp', []);
  5076. * myApp.run(function($templateCache) {
  5077. * $templateCache.put('templateId.html', 'This is the content of the template');
  5078. * });
  5079. * ```
  5080. *
  5081. * To retrieve the template later, simply use it in your HTML:
  5082. * ```html
  5083. * <div ng-include=" 'templateId.html' "></div>
  5084. * ```
  5085. *
  5086. * or get it via Javascript:
  5087. * ```js
  5088. * $templateCache.get('templateId.html')
  5089. * ```
  5090. *
  5091. * See {@link ng.$cacheFactory $cacheFactory}.
  5092. *
  5093. */
  5094. function $TemplateCacheProvider() {
  5095. this.$get = ['$cacheFactory', function($cacheFactory) {
  5096. return $cacheFactory('templates');
  5097. }];
  5098. }
  5099. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5100. *
  5101. * DOM-related variables:
  5102. *
  5103. * - "node" - DOM Node
  5104. * - "element" - DOM Element or Node
  5105. * - "$node" or "$element" - jqLite-wrapped node or element
  5106. *
  5107. *
  5108. * Compiler related stuff:
  5109. *
  5110. * - "linkFn" - linking fn of a single directive
  5111. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5112. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5113. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5114. */
  5115. /**
  5116. * @ngdoc service
  5117. * @name $compile
  5118. * @kind function
  5119. *
  5120. * @description
  5121. * Compiles an HTML string or DOM into a template and produces a template function, which
  5122. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5123. *
  5124. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5125. * {@link ng.$compileProvider#directive directives}.
  5126. *
  5127. * <div class="alert alert-warning">
  5128. * **Note:** This document is an in-depth reference of all directive options.
  5129. * For a gentle introduction to directives with examples of common use cases,
  5130. * see the {@link guide/directive directive guide}.
  5131. * </div>
  5132. *
  5133. * ## Comprehensive Directive API
  5134. *
  5135. * There are many different options for a directive.
  5136. *
  5137. * The difference resides in the return value of the factory function.
  5138. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5139. * or just the `postLink` function (all other properties will have the default values).
  5140. *
  5141. * <div class="alert alert-success">
  5142. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5143. * </div>
  5144. *
  5145. * Here's an example directive declared with a Directive Definition Object:
  5146. *
  5147. * ```js
  5148. * var myModule = angular.module(...);
  5149. *
  5150. * myModule.directive('directiveName', function factory(injectables) {
  5151. * var directiveDefinitionObject = {
  5152. * priority: 0,
  5153. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5154. * // or
  5155. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5156. * transclude: false,
  5157. * restrict: 'A',
  5158. * templateNamespace: 'html',
  5159. * scope: false,
  5160. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5161. * controllerAs: 'stringAlias',
  5162. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5163. * compile: function compile(tElement, tAttrs, transclude) {
  5164. * return {
  5165. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5166. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5167. * }
  5168. * // or
  5169. * // return function postLink( ... ) { ... }
  5170. * },
  5171. * // or
  5172. * // link: {
  5173. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5174. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5175. * // }
  5176. * // or
  5177. * // link: function postLink( ... ) { ... }
  5178. * };
  5179. * return directiveDefinitionObject;
  5180. * });
  5181. * ```
  5182. *
  5183. * <div class="alert alert-warning">
  5184. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5185. * </div>
  5186. *
  5187. * Therefore the above can be simplified as:
  5188. *
  5189. * ```js
  5190. * var myModule = angular.module(...);
  5191. *
  5192. * myModule.directive('directiveName', function factory(injectables) {
  5193. * var directiveDefinitionObject = {
  5194. * link: function postLink(scope, iElement, iAttrs) { ... }
  5195. * };
  5196. * return directiveDefinitionObject;
  5197. * // or
  5198. * // return function postLink(scope, iElement, iAttrs) { ... }
  5199. * });
  5200. * ```
  5201. *
  5202. *
  5203. *
  5204. * ### Directive Definition Object
  5205. *
  5206. * The directive definition object provides instructions to the {@link ng.$compile
  5207. * compiler}. The attributes are:
  5208. *
  5209. * #### `multiElement`
  5210. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5211. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5212. * together as the directive elements. It is recomended that this feature be used on directives
  5213. * which are not strictly behavioural (such as {@link ngClick}), and which
  5214. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5215. *
  5216. * #### `priority`
  5217. * When there are multiple directives defined on a single DOM element, sometimes it
  5218. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5219. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5220. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5221. * are also run in priority order, but post-link functions are run in reverse order. The order
  5222. * of directives with the same priority is undefined. The default priority is `0`.
  5223. *
  5224. * #### `terminal`
  5225. * If set to true then the current `priority` will be the last set of directives
  5226. * which will execute (any directives at the current priority will still execute
  5227. * as the order of execution on same `priority` is undefined). Note that expressions
  5228. * and other directives used in the directive's template will also be excluded from execution.
  5229. *
  5230. * #### `scope`
  5231. * **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
  5232. * same element request a new scope, only one new scope is created. The new scope rule does not
  5233. * apply for the root of the template since the root of the template always gets a new scope.
  5234. *
  5235. * **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
  5236. * normal scope in that it does not prototypically inherit from the parent scope. This is useful
  5237. * when creating reusable components, which should not accidentally read or modify data in the
  5238. * parent scope.
  5239. *
  5240. * The 'isolate' scope takes an object hash which defines a set of local scope properties
  5241. * derived from the parent scope. These local properties are useful for aliasing values for
  5242. * templates. Locals definition is a hash of local scope property to its source:
  5243. *
  5244. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5245. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5246. * attribute name is assumed to be the same as the local name.
  5247. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5248. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5249. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5250. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5251. * component scope).
  5252. *
  5253. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5254. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5255. * name is specified then the attribute name is assumed to be the same as the local name.
  5256. * Given `<widget my-attr="parentModel">` and widget definition of
  5257. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5258. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5259. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5260. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5261. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
  5262. *
  5263. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5264. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5265. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5266. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5267. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5268. * pass data from the isolated scope via an expression to the parent scope, this can be
  5269. * done by passing a map of local variable names and values into the expression wrapper fn.
  5270. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5271. * by calling the `localFn` as `localFn({amount: 22})`.
  5272. *
  5273. *
  5274. * #### `bindToController`
  5275. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController` will
  5276. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5277. * is instantiated, the initial values of the isolate scope bindings are already available.
  5278. *
  5279. * #### `controller`
  5280. * Controller constructor function. The controller is instantiated before the
  5281. * pre-linking phase and it is shared with other directives (see
  5282. * `require` attribute). This allows the directives to communicate with each other and augment
  5283. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5284. *
  5285. * * `$scope` - Current scope associated with the element
  5286. * * `$element` - Current element
  5287. * * `$attrs` - Current attributes object for the element
  5288. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5289. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5290. * * `scope`: optional argument to override the scope.
  5291. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5292. * * `futureParentElement`:
  5293. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5294. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5295. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5296. * and when the `cloneLinkinFn` is passed,
  5297. * as those elements need to created and cloned in a special way when they are defined outside their
  5298. * usual containers (e.g. like `<svg>`).
  5299. * * See also the `directive.templateNamespace` property.
  5300. *
  5301. *
  5302. * #### `require`
  5303. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5304. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5305. * injected argument will be an array in corresponding order. If no such directive can be
  5306. * found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
  5307. *
  5308. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5309. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5310. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5311. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5312. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5313. * `null` to the `link` fn if not found.
  5314. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5315. * `null` to the `link` fn if not found.
  5316. *
  5317. *
  5318. * #### `controllerAs`
  5319. * Controller alias at the directive scope. An alias for the controller so it
  5320. * can be referenced at the directive template. The directive needs to define a scope for this
  5321. * configuration to be used. Useful in the case when directive is used as component.
  5322. *
  5323. *
  5324. * #### `restrict`
  5325. * String of subset of `EACM` which restricts the directive to a specific directive
  5326. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5327. *
  5328. * * `E` - Element name (default): `<my-directive></my-directive>`
  5329. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5330. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5331. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5332. *
  5333. *
  5334. * #### `templateNamespace`
  5335. * String representing the document type used by the markup in the template.
  5336. * AngularJS needs this information as those elements need to be created and cloned
  5337. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5338. *
  5339. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5340. * top-level elements such as `<svg>` or `<math>`.
  5341. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5342. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5343. *
  5344. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5345. *
  5346. * #### `template`
  5347. * HTML markup that may:
  5348. * * Replace the contents of the directive's element (default).
  5349. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5350. * * Wrap the contents of the directive's element (if `transclude` is true).
  5351. *
  5352. * Value may be:
  5353. *
  5354. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5355. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5356. * function api below) and returns a string value.
  5357. *
  5358. *
  5359. * #### `templateUrl`
  5360. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5361. *
  5362. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5363. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5364. * sibling and parent elements as though this element had not contained any directives.
  5365. *
  5366. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5367. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5368. * case when only one deeply nested directive has `templateUrl`.
  5369. *
  5370. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5371. *
  5372. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5373. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5374. * a string value representing the url. In either case, the template URL is passed through {@link
  5375. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5376. *
  5377. *
  5378. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5379. * specify what the template should replace. Defaults to `false`.
  5380. *
  5381. * * `true` - the template will replace the directive's element.
  5382. * * `false` - the template will replace the contents of the directive's element.
  5383. *
  5384. * The replacement process migrates all of the attributes / classes from the old element to the new
  5385. * one. See the {@link guide/directive#template-expanding-directive
  5386. * Directives Guide} for an example.
  5387. *
  5388. * There are very few scenarios where element replacement is required for the application function,
  5389. * the main one being reusable custom components that are used within SVG contexts
  5390. * (because SVG doesn't work with custom elements in the DOM tree).
  5391. *
  5392. * #### `transclude`
  5393. * Extract the contents of the element where the directive appears and make it available to the directive.
  5394. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5395. * {@link $compile#transclusion Transclusion} section below.
  5396. *
  5397. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5398. * directive's element or the entire element:
  5399. *
  5400. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5401. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5402. * element that defined at a lower priority than this directive. When used, the `template`
  5403. * property is ignored.
  5404. *
  5405. *
  5406. * #### `compile`
  5407. *
  5408. * ```js
  5409. * function compile(tElement, tAttrs, transclude) { ... }
  5410. * ```
  5411. *
  5412. * The compile function deals with transforming the template DOM. Since most directives do not do
  5413. * template transformation, it is not used often. The compile function takes the following arguments:
  5414. *
  5415. * * `tElement` - template element - The element where the directive has been declared. It is
  5416. * safe to do template transformation on the element and child elements only.
  5417. *
  5418. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5419. * between all directive compile functions.
  5420. *
  5421. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5422. *
  5423. * <div class="alert alert-warning">
  5424. * **Note:** The template instance and the link instance may be different objects if the template has
  5425. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5426. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5427. * should be done in a linking function rather than in a compile function.
  5428. * </div>
  5429. * <div class="alert alert-warning">
  5430. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5431. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5432. * stack overflow errors.
  5433. *
  5434. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  5435. * a directive's template instead of relying on automatic template compilation via `template` or
  5436. * `templateUrl` declaration or manual compilation inside the compile function.
  5437. * </div>
  5438. *
  5439. * <div class="alert alert-error">
  5440. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  5441. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  5442. * to the link function instead.
  5443. * </div>
  5444. * A compile function can have a return value which can be either a function or an object.
  5445. *
  5446. * * returning a (post-link) function - is equivalent to registering the linking function via the
  5447. * `link` property of the config object when the compile function is empty.
  5448. *
  5449. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  5450. * control when a linking function should be called during the linking phase. See info about
  5451. * pre-linking and post-linking functions below.
  5452. *
  5453. *
  5454. * #### `link`
  5455. * This property is used only if the `compile` property is not defined.
  5456. *
  5457. * ```js
  5458. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  5459. * ```
  5460. *
  5461. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  5462. * executed after the template has been cloned. This is where most of the directive logic will be
  5463. * put.
  5464. *
  5465. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  5466. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  5467. *
  5468. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  5469. * manipulate the children of the element only in `postLink` function since the children have
  5470. * already been linked.
  5471. *
  5472. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  5473. * between all directive linking functions.
  5474. *
  5475. * * `controller` - a controller instance - A controller instance if at least one directive on the
  5476. * element defines a controller. The controller is shared among all the directives, which allows
  5477. * the directives to use the controllers as a communication channel.
  5478. *
  5479. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  5480. * This is the same as the `$transclude`
  5481. * parameter of directive controllers, see there for details.
  5482. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5483. *
  5484. * #### Pre-linking function
  5485. *
  5486. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  5487. * compiler linking function will fail to locate the correct elements for linking.
  5488. *
  5489. * #### Post-linking function
  5490. *
  5491. * Executed after the child elements are linked.
  5492. *
  5493. * Note that child elements that contain `templateUrl` directives will not have been compiled
  5494. * and linked since they are waiting for their template to load asynchronously and their own
  5495. * compilation and linking has been suspended until that occurs.
  5496. *
  5497. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  5498. * for their async templates to be resolved.
  5499. *
  5500. *
  5501. * ### Transclusion
  5502. *
  5503. * Transclusion is the process of extracting a collection of DOM element from one part of the DOM and
  5504. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  5505. * scope from where they were taken.
  5506. *
  5507. * Transclusion is used (often with {@link ngTransclude}) to insert the
  5508. * original contents of a directive's element into a specified place in the template of the directive.
  5509. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  5510. * content has access to the properties on the scope from which it was taken, even if the directive
  5511. * has isolated scope.
  5512. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  5513. *
  5514. * This makes it possible for the widget to have private state for its template, while the transcluded
  5515. * content has access to its originating scope.
  5516. *
  5517. * <div class="alert alert-warning">
  5518. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  5519. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  5520. * Testing Transclusion Directives}.
  5521. * </div>
  5522. *
  5523. * #### Transclusion Functions
  5524. *
  5525. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  5526. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  5527. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  5528. *
  5529. * <div class="alert alert-info">
  5530. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  5531. * ngTransclude will deal with it for us.
  5532. * </div>
  5533. *
  5534. * If you want to manually control the insertion and removal of the transcluded content in your directive
  5535. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  5536. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  5537. *
  5538. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  5539. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  5540. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  5541. *
  5542. * <div class="alert alert-info">
  5543. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  5544. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  5545. * </div>
  5546. *
  5547. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  5548. * attach function**:
  5549. *
  5550. * ```js
  5551. * var transcludedContent, transclusionScope;
  5552. *
  5553. * $transclude(function(clone, scope) {
  5554. * element.append(clone);
  5555. * transcludedContent = clone;
  5556. * transclusionScope = scope;
  5557. * });
  5558. * ```
  5559. *
  5560. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  5561. * associated transclusion scope:
  5562. *
  5563. * ```js
  5564. * transcludedContent.remove();
  5565. * transclusionScope.$destroy();
  5566. * ```
  5567. *
  5568. * <div class="alert alert-info">
  5569. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  5570. * (by calling the transclude function to get the DOM and and calling `element.remove()` to remove it),
  5571. * then you are also responsible for calling `$destroy` on the transclusion scope.
  5572. * </div>
  5573. *
  5574. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  5575. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  5576. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  5577. *
  5578. *
  5579. * #### Transclusion Scopes
  5580. *
  5581. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  5582. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  5583. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  5584. * was taken.
  5585. *
  5586. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  5587. * like this:
  5588. *
  5589. * ```html
  5590. * <div ng-app>
  5591. * <div isolate>
  5592. * <div transclusion>
  5593. * </div>
  5594. * </div>
  5595. * </div>
  5596. * ```
  5597. *
  5598. * The `$parent` scope hierarchy will look like this:
  5599. *
  5600. * ```
  5601. * - $rootScope
  5602. * - isolate
  5603. * - transclusion
  5604. * ```
  5605. *
  5606. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  5607. *
  5608. * ```
  5609. * - $rootScope
  5610. * - transclusion
  5611. * - isolate
  5612. * ```
  5613. *
  5614. *
  5615. * ### Attributes
  5616. *
  5617. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  5618. * `link()` or `compile()` functions. It has a variety of uses.
  5619. *
  5620. * accessing *Normalized attribute names:*
  5621. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  5622. * the attributes object allows for normalized access to
  5623. * the attributes.
  5624. *
  5625. * * *Directive inter-communication:* All directives share the same instance of the attributes
  5626. * object which allows the directives to use the attributes object as inter directive
  5627. * communication.
  5628. *
  5629. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  5630. * allowing other directives to read the interpolated value.
  5631. *
  5632. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  5633. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  5634. * the only way to easily get the actual value because during the linking phase the interpolation
  5635. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  5636. *
  5637. * ```js
  5638. * function linkingFn(scope, elm, attrs, ctrl) {
  5639. * // get the attribute value
  5640. * console.log(attrs.ngModel);
  5641. *
  5642. * // change the attribute
  5643. * attrs.$set('ngModel', 'new value');
  5644. *
  5645. * // observe changes to interpolated attribute
  5646. * attrs.$observe('ngModel', function(value) {
  5647. * console.log('ngModel has changed value to ' + value);
  5648. * });
  5649. * }
  5650. * ```
  5651. *
  5652. * ## Example
  5653. *
  5654. * <div class="alert alert-warning">
  5655. * **Note**: Typically directives are registered with `module.directive`. The example below is
  5656. * to illustrate how `$compile` works.
  5657. * </div>
  5658. *
  5659. <example module="compileExample">
  5660. <file name="index.html">
  5661. <script>
  5662. angular.module('compileExample', [], function($compileProvider) {
  5663. // configure new 'compile' directive by passing a directive
  5664. // factory function. The factory function injects the '$compile'
  5665. $compileProvider.directive('compile', function($compile) {
  5666. // directive factory creates a link function
  5667. return function(scope, element, attrs) {
  5668. scope.$watch(
  5669. function(scope) {
  5670. // watch the 'compile' expression for changes
  5671. return scope.$eval(attrs.compile);
  5672. },
  5673. function(value) {
  5674. // when the 'compile' expression changes
  5675. // assign it into the current DOM
  5676. element.html(value);
  5677. // compile the new DOM and link it to the current
  5678. // scope.
  5679. // NOTE: we only compile .childNodes so that
  5680. // we don't get into infinite loop compiling ourselves
  5681. $compile(element.contents())(scope);
  5682. }
  5683. );
  5684. };
  5685. });
  5686. })
  5687. .controller('GreeterController', ['$scope', function($scope) {
  5688. $scope.name = 'Angular';
  5689. $scope.html = 'Hello {{name}}';
  5690. }]);
  5691. </script>
  5692. <div ng-controller="GreeterController">
  5693. <input ng-model="name"> <br>
  5694. <textarea ng-model="html"></textarea> <br>
  5695. <div compile="html"></div>
  5696. </div>
  5697. </file>
  5698. <file name="protractor.js" type="protractor">
  5699. it('should auto compile', function() {
  5700. var textarea = $('textarea');
  5701. var output = $('div[compile]');
  5702. // The initial state reads 'Hello Angular'.
  5703. expect(output.getText()).toBe('Hello Angular');
  5704. textarea.clear();
  5705. textarea.sendKeys('{{name}}!');
  5706. expect(output.getText()).toBe('Angular!');
  5707. });
  5708. </file>
  5709. </example>
  5710. *
  5711. *
  5712. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  5713. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives.
  5714. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  5715. * root element(s), not their children)
  5716. * @returns {function(scope, cloneAttachFn=)} a link function which is used to bind template
  5717. * (a DOM element/tree) to a scope. Where:
  5718. *
  5719. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  5720. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  5721. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  5722. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  5723. * called as: <br> `cloneAttachFn(clonedElement, scope)` where:
  5724. *
  5725. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  5726. * * `scope` - is the current scope with which the linking function is working with.
  5727. *
  5728. * Calling the linking function returns the element of the template. It is either the original
  5729. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  5730. *
  5731. * After linking the view is not updated until after a call to $digest which typically is done by
  5732. * Angular automatically.
  5733. *
  5734. * If you need access to the bound view, there are two ways to do it:
  5735. *
  5736. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  5737. * before you send them to the compiler and keep this reference around.
  5738. * ```js
  5739. * var element = $compile('<p>{{total}}</p>')(scope);
  5740. * ```
  5741. *
  5742. * - if on the other hand, you need the element to be cloned, the view reference from the original
  5743. * example would not point to the clone, but rather to the original template that was cloned. In
  5744. * this case, you can access the clone via the cloneAttachFn:
  5745. * ```js
  5746. * var templateElement = angular.element('<p>{{total}}</p>'),
  5747. * scope = ....;
  5748. *
  5749. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  5750. * //attach the clone to DOM document at the right place
  5751. * });
  5752. *
  5753. * //now we have reference to the cloned DOM via `clonedElement`
  5754. * ```
  5755. *
  5756. *
  5757. * For information on how the compiler works, see the
  5758. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  5759. */
  5760. var $compileMinErr = minErr('$compile');
  5761. /**
  5762. * @ngdoc provider
  5763. * @name $compileProvider
  5764. *
  5765. * @description
  5766. */
  5767. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  5768. function $CompileProvider($provide, $$sanitizeUriProvider) {
  5769. var hasDirectives = {},
  5770. Suffix = 'Directive',
  5771. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w_\-]+)\s+(.*)$/,
  5772. CLASS_DIRECTIVE_REGEXP = /(([\d\w_\-]+)(?:\:([^;]+))?;?)/,
  5773. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  5774. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  5775. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  5776. // The assumption is that future DOM event attribute names will begin with
  5777. // 'on' and be composed of only English letters.
  5778. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  5779. function parseIsolateBindings(scope, directiveName) {
  5780. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  5781. var bindings = {};
  5782. forEach(scope, function(definition, scopeName) {
  5783. var match = definition.match(LOCAL_REGEXP);
  5784. if (!match) {
  5785. throw $compileMinErr('iscp',
  5786. "Invalid isolate scope definition for directive '{0}'." +
  5787. " Definition: {... {1}: '{2}' ...}",
  5788. directiveName, scopeName, definition);
  5789. }
  5790. bindings[scopeName] = {
  5791. attrName: match[3] || scopeName,
  5792. mode: match[1],
  5793. optional: match[2] === '?'
  5794. };
  5795. });
  5796. return bindings;
  5797. }
  5798. /**
  5799. * @ngdoc method
  5800. * @name $compileProvider#directive
  5801. * @kind function
  5802. *
  5803. * @description
  5804. * Register a new directive with the compiler.
  5805. *
  5806. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  5807. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  5808. * names and the values are the factories.
  5809. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  5810. * {@link guide/directive} for more info.
  5811. * @returns {ng.$compileProvider} Self for chaining.
  5812. */
  5813. this.directive = function registerDirective(name, directiveFactory) {
  5814. assertNotHasOwnProperty(name, 'directive');
  5815. if (isString(name)) {
  5816. assertArg(directiveFactory, 'directiveFactory');
  5817. if (!hasDirectives.hasOwnProperty(name)) {
  5818. hasDirectives[name] = [];
  5819. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  5820. function($injector, $exceptionHandler) {
  5821. var directives = [];
  5822. forEach(hasDirectives[name], function(directiveFactory, index) {
  5823. try {
  5824. var directive = $injector.invoke(directiveFactory);
  5825. if (isFunction(directive)) {
  5826. directive = { compile: valueFn(directive) };
  5827. } else if (!directive.compile && directive.link) {
  5828. directive.compile = valueFn(directive.link);
  5829. }
  5830. directive.priority = directive.priority || 0;
  5831. directive.index = index;
  5832. directive.name = directive.name || name;
  5833. directive.require = directive.require || (directive.controller && directive.name);
  5834. directive.restrict = directive.restrict || 'EA';
  5835. if (isObject(directive.scope)) {
  5836. directive.$$isolateBindings = parseIsolateBindings(directive.scope, directive.name);
  5837. }
  5838. directives.push(directive);
  5839. } catch (e) {
  5840. $exceptionHandler(e);
  5841. }
  5842. });
  5843. return directives;
  5844. }]);
  5845. }
  5846. hasDirectives[name].push(directiveFactory);
  5847. } else {
  5848. forEach(name, reverseParams(registerDirective));
  5849. }
  5850. return this;
  5851. };
  5852. /**
  5853. * @ngdoc method
  5854. * @name $compileProvider#aHrefSanitizationWhitelist
  5855. * @kind function
  5856. *
  5857. * @description
  5858. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5859. * urls during a[href] sanitization.
  5860. *
  5861. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5862. *
  5863. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  5864. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  5865. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5866. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5867. *
  5868. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5869. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5870. * chaining otherwise.
  5871. */
  5872. this.aHrefSanitizationWhitelist = function(regexp) {
  5873. if (isDefined(regexp)) {
  5874. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  5875. return this;
  5876. } else {
  5877. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  5878. }
  5879. };
  5880. /**
  5881. * @ngdoc method
  5882. * @name $compileProvider#imgSrcSanitizationWhitelist
  5883. * @kind function
  5884. *
  5885. * @description
  5886. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  5887. * urls during img[src] sanitization.
  5888. *
  5889. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  5890. *
  5891. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  5892. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  5893. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  5894. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  5895. *
  5896. * @param {RegExp=} regexp New regexp to whitelist urls with.
  5897. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  5898. * chaining otherwise.
  5899. */
  5900. this.imgSrcSanitizationWhitelist = function(regexp) {
  5901. if (isDefined(regexp)) {
  5902. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  5903. return this;
  5904. } else {
  5905. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  5906. }
  5907. };
  5908. /**
  5909. * @ngdoc method
  5910. * @name $compileProvider#debugInfoEnabled
  5911. *
  5912. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  5913. * current debugInfoEnabled state
  5914. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  5915. *
  5916. * @kind function
  5917. *
  5918. * @description
  5919. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  5920. * binding information and a reference to the current scope on to DOM elements.
  5921. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  5922. * * `ng-binding` CSS class
  5923. * * `$binding` data property containing an array of the binding expressions
  5924. *
  5925. * You may want to use this in production for a significant performance boost. See
  5926. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  5927. *
  5928. * The default value is true.
  5929. */
  5930. var debugInfoEnabled = true;
  5931. this.debugInfoEnabled = function(enabled) {
  5932. if(isDefined(enabled)) {
  5933. debugInfoEnabled = enabled;
  5934. return this;
  5935. }
  5936. return debugInfoEnabled;
  5937. };
  5938. this.$get = [
  5939. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  5940. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  5941. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  5942. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  5943. var Attributes = function(element, attributesToCopy) {
  5944. if (attributesToCopy) {
  5945. var keys = Object.keys(attributesToCopy);
  5946. var i, l, key;
  5947. for (i = 0, l = keys.length; i < l; i++) {
  5948. key = keys[i];
  5949. this[key] = attributesToCopy[key];
  5950. }
  5951. } else {
  5952. this.$attr = {};
  5953. }
  5954. this.$$element = element;
  5955. };
  5956. Attributes.prototype = {
  5957. $normalize: directiveNormalize,
  5958. /**
  5959. * @ngdoc method
  5960. * @name $compile.directive.Attributes#$addClass
  5961. * @kind function
  5962. *
  5963. * @description
  5964. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  5965. * are enabled then an animation will be triggered for the class addition.
  5966. *
  5967. * @param {string} classVal The className value that will be added to the element
  5968. */
  5969. $addClass : function(classVal) {
  5970. if(classVal && classVal.length > 0) {
  5971. $animate.addClass(this.$$element, classVal);
  5972. }
  5973. },
  5974. /**
  5975. * @ngdoc method
  5976. * @name $compile.directive.Attributes#$removeClass
  5977. * @kind function
  5978. *
  5979. * @description
  5980. * Removes the CSS class value specified by the classVal parameter from the element. If
  5981. * animations are enabled then an animation will be triggered for the class removal.
  5982. *
  5983. * @param {string} classVal The className value that will be removed from the element
  5984. */
  5985. $removeClass : function(classVal) {
  5986. if(classVal && classVal.length > 0) {
  5987. $animate.removeClass(this.$$element, classVal);
  5988. }
  5989. },
  5990. /**
  5991. * @ngdoc method
  5992. * @name $compile.directive.Attributes#$updateClass
  5993. * @kind function
  5994. *
  5995. * @description
  5996. * Adds and removes the appropriate CSS class values to the element based on the difference
  5997. * between the new and old CSS class values (specified as newClasses and oldClasses).
  5998. *
  5999. * @param {string} newClasses The current CSS className value
  6000. * @param {string} oldClasses The former CSS className value
  6001. */
  6002. $updateClass : function(newClasses, oldClasses) {
  6003. var toAdd = tokenDifference(newClasses, oldClasses);
  6004. if (toAdd && toAdd.length) {
  6005. $animate.addClass(this.$$element, toAdd);
  6006. }
  6007. var toRemove = tokenDifference(oldClasses, newClasses);
  6008. if (toRemove && toRemove.length) {
  6009. $animate.removeClass(this.$$element, toRemove);
  6010. }
  6011. },
  6012. /**
  6013. * Set a normalized attribute on the element in a way such that all directives
  6014. * can share the attribute. This function properly handles boolean attributes.
  6015. * @param {string} key Normalized key. (ie ngAttribute)
  6016. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6017. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6018. * Defaults to true.
  6019. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6020. */
  6021. $set: function(key, value, writeAttr, attrName) {
  6022. // TODO: decide whether or not to throw an error if "class"
  6023. //is set through this function since it may cause $updateClass to
  6024. //become unstable.
  6025. var node = this.$$element[0],
  6026. booleanKey = getBooleanAttrName(node, key),
  6027. aliasedKey = getAliasedAttrName(node, key),
  6028. observer = key,
  6029. normalizedVal,
  6030. nodeName;
  6031. if (booleanKey) {
  6032. this.$$element.prop(key, value);
  6033. attrName = booleanKey;
  6034. } else if(aliasedKey) {
  6035. this[aliasedKey] = value;
  6036. observer = aliasedKey;
  6037. }
  6038. this[key] = value;
  6039. // translate normalized key to actual key
  6040. if (attrName) {
  6041. this.$attr[key] = attrName;
  6042. } else {
  6043. attrName = this.$attr[key];
  6044. if (!attrName) {
  6045. this.$attr[key] = attrName = snake_case(key, '-');
  6046. }
  6047. }
  6048. nodeName = nodeName_(this.$$element);
  6049. if ((nodeName === 'a' && key === 'href') ||
  6050. (nodeName === 'img' && key === 'src')) {
  6051. // sanitize a[href] and img[src] values
  6052. this[key] = value = $$sanitizeUri(value, key === 'src');
  6053. } else if (nodeName === 'img' && key === 'srcset') {
  6054. // sanitize img[srcset] values
  6055. var result = "";
  6056. // first check if there are spaces because it's not the same pattern
  6057. var trimmedSrcset = trim(value);
  6058. // ( 999x ,| 999w ,| ,|, )
  6059. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6060. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6061. // split srcset into tuple of uri and descriptor except for the last item
  6062. var rawUris = trimmedSrcset.split(pattern);
  6063. // for each tuples
  6064. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6065. for (var i=0; i<nbrUrisWith2parts; i++) {
  6066. var innerIdx = i*2;
  6067. // sanitize the uri
  6068. result += $$sanitizeUri(trim( rawUris[innerIdx]), true);
  6069. // add the descriptor
  6070. result += ( " " + trim(rawUris[innerIdx+1]));
  6071. }
  6072. // split the last item into uri and descriptor
  6073. var lastTuple = trim(rawUris[i*2]).split(/\s/);
  6074. // sanitize the last uri
  6075. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6076. // and add the last descriptor if any
  6077. if( lastTuple.length === 2) {
  6078. result += (" " + trim(lastTuple[1]));
  6079. }
  6080. this[key] = value = result;
  6081. }
  6082. if (writeAttr !== false) {
  6083. if (value === null || value === undefined) {
  6084. this.$$element.removeAttr(attrName);
  6085. } else {
  6086. this.$$element.attr(attrName, value);
  6087. }
  6088. }
  6089. // fire observers
  6090. var $$observers = this.$$observers;
  6091. $$observers && forEach($$observers[observer], function(fn) {
  6092. try {
  6093. fn(value);
  6094. } catch (e) {
  6095. $exceptionHandler(e);
  6096. }
  6097. });
  6098. },
  6099. /**
  6100. * @ngdoc method
  6101. * @name $compile.directive.Attributes#$observe
  6102. * @kind function
  6103. *
  6104. * @description
  6105. * Observes an interpolated attribute.
  6106. *
  6107. * The observer function will be invoked once during the next `$digest` following
  6108. * compilation. The observer is then invoked whenever the interpolated value
  6109. * changes.
  6110. *
  6111. * @param {string} key Normalized key. (ie ngAttribute) .
  6112. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6113. the interpolated value of the attribute changes.
  6114. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6115. * @returns {function()} Returns a deregistration function for this observer.
  6116. */
  6117. $observe: function(key, fn) {
  6118. var attrs = this,
  6119. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6120. listeners = ($$observers[key] || ($$observers[key] = []));
  6121. listeners.push(fn);
  6122. $rootScope.$evalAsync(function() {
  6123. if (!listeners.$$inter) {
  6124. // no one registered attribute interpolation function, so lets call it manually
  6125. fn(attrs[key]);
  6126. }
  6127. });
  6128. return function() {
  6129. arrayRemove(listeners, fn);
  6130. };
  6131. }
  6132. };
  6133. function safeAddClass($element, className) {
  6134. try {
  6135. $element.addClass(className);
  6136. } catch(e) {
  6137. // ignore, since it means that we are trying to set class on
  6138. // SVG element, where class name is read-only.
  6139. }
  6140. }
  6141. var startSymbol = $interpolate.startSymbol(),
  6142. endSymbol = $interpolate.endSymbol(),
  6143. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6144. ? identity
  6145. : function denormalizeTemplate(template) {
  6146. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6147. },
  6148. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6149. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6150. var bindings = $element.data('$binding') || [];
  6151. if (isArray(binding)) {
  6152. bindings = bindings.concat(binding);
  6153. } else {
  6154. bindings.push(binding);
  6155. }
  6156. $element.data('$binding', bindings);
  6157. } : noop;
  6158. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6159. safeAddClass($element, 'ng-binding');
  6160. } : noop;
  6161. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6162. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6163. $element.data(dataName, scope);
  6164. } : noop;
  6165. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6166. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6167. } : noop;
  6168. return compile;
  6169. //================================
  6170. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6171. previousCompileContext) {
  6172. if (!($compileNodes instanceof jqLite)) {
  6173. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6174. // modify it.
  6175. $compileNodes = jqLite($compileNodes);
  6176. }
  6177. // We can not compile top level text elements since text nodes can be merged and we will
  6178. // not be able to attach scope data to them, so we will wrap them in <span>
  6179. forEach($compileNodes, function(node, index){
  6180. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6181. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6182. }
  6183. });
  6184. var compositeLinkFn =
  6185. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6186. maxPriority, ignoreDirective, previousCompileContext);
  6187. compile.$$addScopeClass($compileNodes);
  6188. var namespace = null;
  6189. return function publicLinkFn(scope, cloneConnectFn, transcludeControllers, parentBoundTranscludeFn, futureParentElement){
  6190. assertArg(scope, 'scope');
  6191. if (!namespace) {
  6192. namespace = detectNamespaceForChildElements(futureParentElement);
  6193. }
  6194. var $linkNode;
  6195. if (namespace !== 'html') {
  6196. // When using a directive with replace:true and templateUrl the $compileNodes
  6197. // (or a child element inside of them)
  6198. // might change, so we need to recreate the namespace adapted compileNodes
  6199. // for call to the link function.
  6200. // Note: This will already clone the nodes...
  6201. $linkNode = jqLite(
  6202. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6203. );
  6204. } else if (cloneConnectFn) {
  6205. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6206. // and sometimes changes the structure of the DOM.
  6207. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6208. } else {
  6209. $linkNode = $compileNodes;
  6210. }
  6211. if (transcludeControllers) {
  6212. for (var controllerName in transcludeControllers) {
  6213. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6214. }
  6215. }
  6216. compile.$$addScopeInfo($linkNode, scope);
  6217. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6218. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6219. return $linkNode;
  6220. };
  6221. }
  6222. function detectNamespaceForChildElements(parentElement) {
  6223. // TODO: Make this detect MathML as well...
  6224. var node = parentElement && parentElement[0];
  6225. if (!node) {
  6226. return 'html';
  6227. } else {
  6228. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg': 'html';
  6229. }
  6230. }
  6231. /**
  6232. * Compile function matches each node in nodeList against the directives. Once all directives
  6233. * for a particular node are collected their compile functions are executed. The compile
  6234. * functions return values - the linking functions - are combined into a composite linking
  6235. * function, which is the a linking function for the node.
  6236. *
  6237. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6238. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6239. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6240. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6241. * the rootElement must be set the jqLite collection of the compile root. This is
  6242. * needed so that the jqLite collection items can be replaced with widgets.
  6243. * @param {number=} maxPriority Max directive priority.
  6244. * @returns {Function} A composite linking function of all of the matched directives or null.
  6245. */
  6246. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6247. previousCompileContext) {
  6248. var linkFns = [],
  6249. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6250. for (var i = 0; i < nodeList.length; i++) {
  6251. attrs = new Attributes();
  6252. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6253. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6254. ignoreDirective);
  6255. nodeLinkFn = (directives.length)
  6256. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6257. null, [], [], previousCompileContext)
  6258. : null;
  6259. if (nodeLinkFn && nodeLinkFn.scope) {
  6260. compile.$$addScopeClass(attrs.$$element);
  6261. }
  6262. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6263. !(childNodes = nodeList[i].childNodes) ||
  6264. !childNodes.length)
  6265. ? null
  6266. : compileNodes(childNodes,
  6267. nodeLinkFn ? (
  6268. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6269. && nodeLinkFn.transclude) : transcludeFn);
  6270. if (nodeLinkFn || childLinkFn) {
  6271. linkFns.push(i, nodeLinkFn, childLinkFn);
  6272. linkFnFound = true;
  6273. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6274. }
  6275. //use the previous context only for the first element in the virtual group
  6276. previousCompileContext = null;
  6277. }
  6278. // return a linking function if we have found anything, null otherwise
  6279. return linkFnFound ? compositeLinkFn : null;
  6280. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6281. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6282. var stableNodeList;
  6283. if (nodeLinkFnFound) {
  6284. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6285. // offsets don't get screwed up
  6286. var nodeListLength = nodeList.length;
  6287. stableNodeList = new Array(nodeListLength);
  6288. // create a sparse array by only copying the elements which have a linkFn
  6289. for (i = 0; i < linkFns.length; i+=3) {
  6290. idx = linkFns[i];
  6291. stableNodeList[idx] = nodeList[idx];
  6292. }
  6293. } else {
  6294. stableNodeList = nodeList;
  6295. }
  6296. for(i = 0, ii = linkFns.length; i < ii;) {
  6297. node = stableNodeList[linkFns[i++]];
  6298. nodeLinkFn = linkFns[i++];
  6299. childLinkFn = linkFns[i++];
  6300. if (nodeLinkFn) {
  6301. if (nodeLinkFn.scope) {
  6302. childScope = scope.$new();
  6303. compile.$$addScopeInfo(jqLite(node), childScope);
  6304. } else {
  6305. childScope = scope;
  6306. }
  6307. if ( nodeLinkFn.transcludeOnThisElement ) {
  6308. childBoundTranscludeFn = createBoundTranscludeFn(
  6309. scope, nodeLinkFn.transclude, parentBoundTranscludeFn,
  6310. nodeLinkFn.elementTranscludeOnThisElement);
  6311. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6312. childBoundTranscludeFn = parentBoundTranscludeFn;
  6313. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6314. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6315. } else {
  6316. childBoundTranscludeFn = null;
  6317. }
  6318. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  6319. } else if (childLinkFn) {
  6320. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  6321. }
  6322. }
  6323. }
  6324. }
  6325. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn, elementTransclusion) {
  6326. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  6327. if (!transcludedScope) {
  6328. transcludedScope = scope.$new(false, containingScope);
  6329. transcludedScope.$$transcluded = true;
  6330. }
  6331. return transcludeFn(transcludedScope, cloneFn, controllers, previousBoundTranscludeFn, futureParentElement);
  6332. };
  6333. return boundTranscludeFn;
  6334. }
  6335. /**
  6336. * Looks for directives on the given node and adds them to the directive collection which is
  6337. * sorted.
  6338. *
  6339. * @param node Node to search.
  6340. * @param directives An array to which the directives are added to. This array is sorted before
  6341. * the function returns.
  6342. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  6343. * @param {number=} maxPriority Max directive priority.
  6344. */
  6345. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  6346. var nodeType = node.nodeType,
  6347. attrsMap = attrs.$attr,
  6348. match,
  6349. className;
  6350. switch(nodeType) {
  6351. case NODE_TYPE_ELEMENT: /* Element */
  6352. // use the node name: <directive>
  6353. addDirective(directives,
  6354. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  6355. // iterate over the attributes
  6356. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  6357. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  6358. var attrStartName = false;
  6359. var attrEndName = false;
  6360. attr = nAttrs[j];
  6361. name = attr.name;
  6362. value = trim(attr.value);
  6363. // support ngAttr attribute binding
  6364. ngAttrName = directiveNormalize(name);
  6365. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  6366. name = snake_case(ngAttrName.substr(6), '-');
  6367. }
  6368. var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
  6369. if (directiveIsMultiElement(directiveNName)) {
  6370. if (ngAttrName === directiveNName + 'Start') {
  6371. attrStartName = name;
  6372. attrEndName = name.substr(0, name.length - 5) + 'end';
  6373. name = name.substr(0, name.length - 6);
  6374. }
  6375. }
  6376. nName = directiveNormalize(name.toLowerCase());
  6377. attrsMap[nName] = name;
  6378. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  6379. attrs[nName] = value;
  6380. if (getBooleanAttrName(node, nName)) {
  6381. attrs[nName] = true; // presence means true
  6382. }
  6383. }
  6384. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  6385. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  6386. attrEndName);
  6387. }
  6388. // use class as directive
  6389. className = node.className;
  6390. if (isString(className) && className !== '') {
  6391. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  6392. nName = directiveNormalize(match[2]);
  6393. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  6394. attrs[nName] = trim(match[3]);
  6395. }
  6396. className = className.substr(match.index + match[0].length);
  6397. }
  6398. }
  6399. break;
  6400. case NODE_TYPE_TEXT: /* Text Node */
  6401. addTextInterpolateDirective(directives, node.nodeValue);
  6402. break;
  6403. case NODE_TYPE_COMMENT: /* Comment */
  6404. try {
  6405. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  6406. if (match) {
  6407. nName = directiveNormalize(match[1]);
  6408. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  6409. attrs[nName] = trim(match[2]);
  6410. }
  6411. }
  6412. } catch (e) {
  6413. // turns out that under some circumstances IE9 throws errors when one attempts to read
  6414. // comment's node value.
  6415. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  6416. }
  6417. break;
  6418. }
  6419. directives.sort(byPriority);
  6420. return directives;
  6421. }
  6422. /**
  6423. * Given a node with an directive-start it collects all of the siblings until it finds
  6424. * directive-end.
  6425. * @param node
  6426. * @param attrStart
  6427. * @param attrEnd
  6428. * @returns {*}
  6429. */
  6430. function groupScan(node, attrStart, attrEnd) {
  6431. var nodes = [];
  6432. var depth = 0;
  6433. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  6434. var startNode = node;
  6435. do {
  6436. if (!node) {
  6437. throw $compileMinErr('uterdir',
  6438. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  6439. attrStart, attrEnd);
  6440. }
  6441. if (node.nodeType == NODE_TYPE_ELEMENT) {
  6442. if (node.hasAttribute(attrStart)) depth++;
  6443. if (node.hasAttribute(attrEnd)) depth--;
  6444. }
  6445. nodes.push(node);
  6446. node = node.nextSibling;
  6447. } while (depth > 0);
  6448. } else {
  6449. nodes.push(node);
  6450. }
  6451. return jqLite(nodes);
  6452. }
  6453. /**
  6454. * Wrapper for linking function which converts normal linking function into a grouped
  6455. * linking function.
  6456. * @param linkFn
  6457. * @param attrStart
  6458. * @param attrEnd
  6459. * @returns {Function}
  6460. */
  6461. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  6462. return function(scope, element, attrs, controllers, transcludeFn) {
  6463. element = groupScan(element[0], attrStart, attrEnd);
  6464. return linkFn(scope, element, attrs, controllers, transcludeFn);
  6465. };
  6466. }
  6467. /**
  6468. * Once the directives have been collected, their compile functions are executed. This method
  6469. * is responsible for inlining directive templates as well as terminating the application
  6470. * of the directives if the terminal directive has been reached.
  6471. *
  6472. * @param {Array} directives Array of collected directives to execute their compile function.
  6473. * this needs to be pre-sorted by priority order.
  6474. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  6475. * @param {Object} templateAttrs The shared attribute function
  6476. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6477. * scope argument is auto-generated to the new
  6478. * child of the transcluded parent scope.
  6479. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  6480. * argument has the root jqLite array so that we can replace nodes
  6481. * on it.
  6482. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  6483. * compiling the transclusion.
  6484. * @param {Array.<Function>} preLinkFns
  6485. * @param {Array.<Function>} postLinkFns
  6486. * @param {Object} previousCompileContext Context used for previous compilation of the current
  6487. * node
  6488. * @returns {Function} linkFn
  6489. */
  6490. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  6491. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  6492. previousCompileContext) {
  6493. previousCompileContext = previousCompileContext || {};
  6494. var terminalPriority = -Number.MAX_VALUE,
  6495. newScopeDirective,
  6496. controllerDirectives = previousCompileContext.controllerDirectives,
  6497. controllers,
  6498. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  6499. templateDirective = previousCompileContext.templateDirective,
  6500. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  6501. hasTranscludeDirective = false,
  6502. hasTemplate = false,
  6503. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  6504. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  6505. directive,
  6506. directiveName,
  6507. $template,
  6508. replaceDirective = originalReplaceDirective,
  6509. childTranscludeFn = transcludeFn,
  6510. linkFn,
  6511. directiveValue;
  6512. // executes all directives on the current element
  6513. for(var i = 0, ii = directives.length; i < ii; i++) {
  6514. directive = directives[i];
  6515. var attrStart = directive.$$start;
  6516. var attrEnd = directive.$$end;
  6517. // collect multiblock sections
  6518. if (attrStart) {
  6519. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  6520. }
  6521. $template = undefined;
  6522. if (terminalPriority > directive.priority) {
  6523. break; // prevent further processing of directives
  6524. }
  6525. if (directiveValue = directive.scope) {
  6526. // skip the check for directives with async templates, we'll check the derived sync
  6527. // directive when the template arrives
  6528. if (!directive.templateUrl) {
  6529. if (isObject(directiveValue)) {
  6530. // This directive is trying to add an isolated scope.
  6531. // Check that there is no scope of any kind already
  6532. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  6533. directive, $compileNode);
  6534. newIsolateScopeDirective = directive;
  6535. } else {
  6536. // This directive is trying to add a child scope.
  6537. // Check that there is no isolated scope already
  6538. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  6539. $compileNode);
  6540. }
  6541. }
  6542. newScopeDirective = newScopeDirective || directive;
  6543. }
  6544. directiveName = directive.name;
  6545. if (!directive.templateUrl && directive.controller) {
  6546. directiveValue = directive.controller;
  6547. controllerDirectives = controllerDirectives || {};
  6548. assertNoDuplicate("'" + directiveName + "' controller",
  6549. controllerDirectives[directiveName], directive, $compileNode);
  6550. controllerDirectives[directiveName] = directive;
  6551. }
  6552. if (directiveValue = directive.transclude) {
  6553. hasTranscludeDirective = true;
  6554. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  6555. // This option should only be used by directives that know how to safely handle element transclusion,
  6556. // where the transcluded nodes are added or replaced after linking.
  6557. if (!directive.$$tlb) {
  6558. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  6559. nonTlbTranscludeDirective = directive;
  6560. }
  6561. if (directiveValue == 'element') {
  6562. hasElementTranscludeDirective = true;
  6563. terminalPriority = directive.priority;
  6564. $template = $compileNode;
  6565. $compileNode = templateAttrs.$$element =
  6566. jqLite(document.createComment(' ' + directiveName + ': ' +
  6567. templateAttrs[directiveName] + ' '));
  6568. compileNode = $compileNode[0];
  6569. replaceWith(jqCollection, sliceArgs($template), compileNode);
  6570. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  6571. replaceDirective && replaceDirective.name, {
  6572. // Don't pass in:
  6573. // - controllerDirectives - otherwise we'll create duplicates controllers
  6574. // - newIsolateScopeDirective or templateDirective - combining templates with
  6575. // element transclusion doesn't make sense.
  6576. //
  6577. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  6578. // on the same element more than once.
  6579. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6580. });
  6581. } else {
  6582. $template = jqLite(jqLiteClone(compileNode)).contents();
  6583. $compileNode.empty(); // clear contents
  6584. childTranscludeFn = compile($template, transcludeFn);
  6585. }
  6586. }
  6587. if (directive.template) {
  6588. hasTemplate = true;
  6589. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6590. templateDirective = directive;
  6591. directiveValue = (isFunction(directive.template))
  6592. ? directive.template($compileNode, templateAttrs)
  6593. : directive.template;
  6594. directiveValue = denormalizeTemplate(directiveValue);
  6595. if (directive.replace) {
  6596. replaceDirective = directive;
  6597. if (jqLiteIsTextNode(directiveValue)) {
  6598. $template = [];
  6599. } else {
  6600. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  6601. }
  6602. compileNode = $template[0];
  6603. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  6604. throw $compileMinErr('tplrt',
  6605. "Template for directive '{0}' must have exactly one root element. {1}",
  6606. directiveName, '');
  6607. }
  6608. replaceWith(jqCollection, $compileNode, compileNode);
  6609. var newTemplateAttrs = {$attr: {}};
  6610. // combine directives from the original node and from the template:
  6611. // - take the array of directives for this element
  6612. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  6613. // - collect directives from the template and sort them by priority
  6614. // - combine directives as: processed + template + unprocessed
  6615. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  6616. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  6617. if (newIsolateScopeDirective) {
  6618. markDirectivesAsIsolate(templateDirectives);
  6619. }
  6620. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  6621. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  6622. ii = directives.length;
  6623. } else {
  6624. $compileNode.html(directiveValue);
  6625. }
  6626. }
  6627. if (directive.templateUrl) {
  6628. hasTemplate = true;
  6629. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  6630. templateDirective = directive;
  6631. if (directive.replace) {
  6632. replaceDirective = directive;
  6633. }
  6634. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  6635. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  6636. controllerDirectives: controllerDirectives,
  6637. newIsolateScopeDirective: newIsolateScopeDirective,
  6638. templateDirective: templateDirective,
  6639. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  6640. });
  6641. ii = directives.length;
  6642. } else if (directive.compile) {
  6643. try {
  6644. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  6645. if (isFunction(linkFn)) {
  6646. addLinkFns(null, linkFn, attrStart, attrEnd);
  6647. } else if (linkFn) {
  6648. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  6649. }
  6650. } catch (e) {
  6651. $exceptionHandler(e, startingTag($compileNode));
  6652. }
  6653. }
  6654. if (directive.terminal) {
  6655. nodeLinkFn.terminal = true;
  6656. terminalPriority = Math.max(terminalPriority, directive.priority);
  6657. }
  6658. }
  6659. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  6660. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  6661. nodeLinkFn.elementTranscludeOnThisElement = hasElementTranscludeDirective;
  6662. nodeLinkFn.templateOnThisElement = hasTemplate;
  6663. nodeLinkFn.transclude = childTranscludeFn;
  6664. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  6665. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  6666. return nodeLinkFn;
  6667. ////////////////////
  6668. function addLinkFns(pre, post, attrStart, attrEnd) {
  6669. if (pre) {
  6670. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  6671. pre.require = directive.require;
  6672. pre.directiveName = directiveName;
  6673. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6674. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  6675. }
  6676. preLinkFns.push(pre);
  6677. }
  6678. if (post) {
  6679. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  6680. post.require = directive.require;
  6681. post.directiveName = directiveName;
  6682. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  6683. post = cloneAndAnnotateFn(post, {isolateScope: true});
  6684. }
  6685. postLinkFns.push(post);
  6686. }
  6687. }
  6688. function getControllers(directiveName, require, $element, elementControllers) {
  6689. var value, retrievalMethod = 'data', optional = false;
  6690. var $searchElement = $element;
  6691. var match;
  6692. if (isString(require)) {
  6693. match = require.match(REQUIRE_PREFIX_REGEXP);
  6694. require = require.substring(match[0].length);
  6695. if (match[3]) {
  6696. if (match[1]) match[3] = null;
  6697. else match[1] = match[3];
  6698. }
  6699. if (match[1] === '^') {
  6700. retrievalMethod = 'inheritedData';
  6701. } else if (match[1] === '^^') {
  6702. retrievalMethod = 'inheritedData';
  6703. $searchElement = $element.parent();
  6704. }
  6705. if (match[2] === '?') {
  6706. optional = true;
  6707. }
  6708. value = null;
  6709. if (elementControllers && retrievalMethod === 'data') {
  6710. if (value = elementControllers[require]) {
  6711. value = value.instance;
  6712. }
  6713. }
  6714. value = value || $searchElement[retrievalMethod]('$' + require + 'Controller');
  6715. if (!value && !optional) {
  6716. throw $compileMinErr('ctreq',
  6717. "Controller '{0}', required by directive '{1}', can't be found!",
  6718. require, directiveName);
  6719. }
  6720. return value;
  6721. } else if (isArray(require)) {
  6722. value = [];
  6723. forEach(require, function(require) {
  6724. value.push(getControllers(directiveName, require, $element, elementControllers));
  6725. });
  6726. }
  6727. return value;
  6728. }
  6729. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  6730. var i, ii, linkFn, controller, isolateScope, elementControllers, transcludeFn, $element,
  6731. attrs;
  6732. if (compileNode === linkNode) {
  6733. attrs = templateAttrs;
  6734. $element = templateAttrs.$$element;
  6735. } else {
  6736. $element = jqLite(linkNode);
  6737. attrs = new Attributes($element, templateAttrs);
  6738. }
  6739. if (newIsolateScopeDirective) {
  6740. isolateScope = scope.$new(true);
  6741. }
  6742. transcludeFn = boundTranscludeFn && controllersBoundTransclude;
  6743. if (controllerDirectives) {
  6744. // TODO: merge `controllers` and `elementControllers` into single object.
  6745. controllers = {};
  6746. elementControllers = {};
  6747. forEach(controllerDirectives, function(directive) {
  6748. var locals = {
  6749. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  6750. $element: $element,
  6751. $attrs: attrs,
  6752. $transclude: transcludeFn
  6753. }, controllerInstance;
  6754. controller = directive.controller;
  6755. if (controller == '@') {
  6756. controller = attrs[directive.name];
  6757. }
  6758. controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  6759. // For directives with element transclusion the element is a comment,
  6760. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  6761. // clean up (http://bugs.jquery.com/ticket/8335).
  6762. // Instead, we save the controllers for the element in a local hash and attach to .data
  6763. // later, once we have the actual element.
  6764. elementControllers[directive.name] = controllerInstance;
  6765. if (!hasElementTranscludeDirective) {
  6766. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  6767. }
  6768. controllers[directive.name] = controllerInstance;
  6769. });
  6770. }
  6771. if (newIsolateScopeDirective) {
  6772. var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
  6773. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  6774. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  6775. compile.$$addScopeClass($element, true);
  6776. var isolateScopeController = controllers && controllers[newIsolateScopeDirective.name];
  6777. var isolateBindingContext = isolateScope;
  6778. if (isolateScopeController && isolateScopeController.identifier &&
  6779. newIsolateScopeDirective.bindToController === true) {
  6780. isolateBindingContext = isolateScopeController.instance;
  6781. }
  6782. forEach(isolateScope.$$isolateBindings = newIsolateScopeDirective.$$isolateBindings, function(definition, scopeName) {
  6783. var attrName = definition.attrName,
  6784. optional = definition.optional,
  6785. mode = definition.mode, // @, =, or &
  6786. lastValue,
  6787. parentGet, parentSet, compare;
  6788. switch (mode) {
  6789. case '@':
  6790. attrs.$observe(attrName, function(value) {
  6791. isolateBindingContext[scopeName] = value;
  6792. });
  6793. attrs.$$observers[attrName].$$scope = scope;
  6794. if( attrs[attrName] ) {
  6795. // If the attribute has been provided then we trigger an interpolation to ensure
  6796. // the value is there for use in the link fn
  6797. isolateBindingContext[scopeName] = $interpolate(attrs[attrName])(scope);
  6798. }
  6799. break;
  6800. case '=':
  6801. if (optional && !attrs[attrName]) {
  6802. return;
  6803. }
  6804. parentGet = $parse(attrs[attrName]);
  6805. if (parentGet.literal) {
  6806. compare = equals;
  6807. } else {
  6808. compare = function(a,b) { return a === b || (a !== a && b !== b); };
  6809. }
  6810. parentSet = parentGet.assign || function() {
  6811. // reset the change, or we will throw this exception on every $digest
  6812. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6813. throw $compileMinErr('nonassign',
  6814. "Expression '{0}' used with directive '{1}' is non-assignable!",
  6815. attrs[attrName], newIsolateScopeDirective.name);
  6816. };
  6817. lastValue = isolateBindingContext[scopeName] = parentGet(scope);
  6818. var parentValueWatch = function parentValueWatch(parentValue) {
  6819. if (!compare(parentValue, isolateBindingContext[scopeName])) {
  6820. // we are out of sync and need to copy
  6821. if (!compare(parentValue, lastValue)) {
  6822. // parent changed and it has precedence
  6823. isolateBindingContext[scopeName] = parentValue;
  6824. } else {
  6825. // if the parent can be assigned then do so
  6826. parentSet(scope, parentValue = isolateBindingContext[scopeName]);
  6827. }
  6828. }
  6829. return lastValue = parentValue;
  6830. };
  6831. parentValueWatch.$stateful = true;
  6832. var unwatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  6833. isolateScope.$on('$destroy', unwatch);
  6834. break;
  6835. case '&':
  6836. parentGet = $parse(attrs[attrName]);
  6837. isolateBindingContext[scopeName] = function(locals) {
  6838. return parentGet(scope, locals);
  6839. };
  6840. break;
  6841. }
  6842. });
  6843. }
  6844. if (controllers) {
  6845. forEach(controllers, function(controller) {
  6846. controller();
  6847. });
  6848. controllers = null;
  6849. }
  6850. // PRELINKING
  6851. for(i = 0, ii = preLinkFns.length; i < ii; i++) {
  6852. linkFn = preLinkFns[i];
  6853. invokeLinkFn(linkFn,
  6854. linkFn.isolateScope ? isolateScope : scope,
  6855. $element,
  6856. attrs,
  6857. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6858. transcludeFn
  6859. );
  6860. }
  6861. // RECURSION
  6862. // We only pass the isolate scope, if the isolate directive has a template,
  6863. // otherwise the child elements do not belong to the isolate directive.
  6864. var scopeToChild = scope;
  6865. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  6866. scopeToChild = isolateScope;
  6867. }
  6868. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  6869. // POSTLINKING
  6870. for(i = postLinkFns.length - 1; i >= 0; i--) {
  6871. linkFn = postLinkFns[i];
  6872. invokeLinkFn(linkFn,
  6873. linkFn.isolateScope ? isolateScope : scope,
  6874. $element,
  6875. attrs,
  6876. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  6877. transcludeFn
  6878. );
  6879. }
  6880. // This is the function that is injected as `$transclude`.
  6881. // Note: all arguments are optional!
  6882. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  6883. var transcludeControllers;
  6884. // No scope passed in:
  6885. if (!isScope(scope)) {
  6886. futureParentElement = cloneAttachFn;
  6887. cloneAttachFn = scope;
  6888. scope = undefined;
  6889. }
  6890. if (hasElementTranscludeDirective) {
  6891. transcludeControllers = elementControllers;
  6892. }
  6893. if (!futureParentElement) {
  6894. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  6895. }
  6896. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  6897. }
  6898. }
  6899. }
  6900. function markDirectivesAsIsolate(directives) {
  6901. // mark all directives as needing isolate scope.
  6902. for (var j = 0, jj = directives.length; j < jj; j++) {
  6903. directives[j] = inherit(directives[j], {$$isolateScope: true});
  6904. }
  6905. }
  6906. /**
  6907. * looks up the directive and decorates it with exception handling and proper parameters. We
  6908. * call this the boundDirective.
  6909. *
  6910. * @param {string} name name of the directive to look up.
  6911. * @param {string} location The directive must be found in specific format.
  6912. * String containing any of theses characters:
  6913. *
  6914. * * `E`: element name
  6915. * * `A': attribute
  6916. * * `C`: class
  6917. * * `M`: comment
  6918. * @returns {boolean} true if directive was added.
  6919. */
  6920. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  6921. endAttrName) {
  6922. if (name === ignoreDirective) return null;
  6923. var match = null;
  6924. if (hasDirectives.hasOwnProperty(name)) {
  6925. for(var directive, directives = $injector.get(name + Suffix),
  6926. i = 0, ii = directives.length; i<ii; i++) {
  6927. try {
  6928. directive = directives[i];
  6929. if ( (maxPriority === undefined || maxPriority > directive.priority) &&
  6930. directive.restrict.indexOf(location) != -1) {
  6931. if (startAttrName) {
  6932. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  6933. }
  6934. tDirectives.push(directive);
  6935. match = directive;
  6936. }
  6937. } catch(e) { $exceptionHandler(e); }
  6938. }
  6939. }
  6940. return match;
  6941. }
  6942. /**
  6943. * looks up the directive and returns true if it is a multi-element directive,
  6944. * and therefore requires DOM nodes between -start and -end markers to be grouped
  6945. * together.
  6946. *
  6947. * @param {string} name name of the directive to look up.
  6948. * @returns true if directive was registered as multi-element.
  6949. */
  6950. function directiveIsMultiElement(name) {
  6951. if (hasDirectives.hasOwnProperty(name)) {
  6952. for(var directive, directives = $injector.get(name + Suffix),
  6953. i = 0, ii = directives.length; i<ii; i++) {
  6954. directive = directives[i];
  6955. if (directive.multiElement) {
  6956. return true;
  6957. }
  6958. }
  6959. }
  6960. return false;
  6961. }
  6962. /**
  6963. * When the element is replaced with HTML template then the new attributes
  6964. * on the template need to be merged with the existing attributes in the DOM.
  6965. * The desired effect is to have both of the attributes present.
  6966. *
  6967. * @param {object} dst destination attributes (original DOM)
  6968. * @param {object} src source attributes (from the directive template)
  6969. */
  6970. function mergeTemplateAttributes(dst, src) {
  6971. var srcAttr = src.$attr,
  6972. dstAttr = dst.$attr,
  6973. $element = dst.$$element;
  6974. // reapply the old attributes to the new element
  6975. forEach(dst, function(value, key) {
  6976. if (key.charAt(0) != '$') {
  6977. if (src[key] && src[key] !== value) {
  6978. value += (key === 'style' ? ';' : ' ') + src[key];
  6979. }
  6980. dst.$set(key, value, true, srcAttr[key]);
  6981. }
  6982. });
  6983. // copy the new attributes on the old attrs object
  6984. forEach(src, function(value, key) {
  6985. if (key == 'class') {
  6986. safeAddClass($element, value);
  6987. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  6988. } else if (key == 'style') {
  6989. $element.attr('style', $element.attr('style') + ';' + value);
  6990. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  6991. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  6992. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  6993. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  6994. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  6995. dst[key] = value;
  6996. dstAttr[key] = srcAttr[key];
  6997. }
  6998. });
  6999. }
  7000. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7001. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7002. var linkQueue = [],
  7003. afterTemplateNodeLinkFn,
  7004. afterTemplateChildLinkFn,
  7005. beforeTemplateCompileNode = $compileNode[0],
  7006. origAsyncDirective = directives.shift(),
  7007. // The fact that we have to copy and patch the directive seems wrong!
  7008. derivedSyncDirective = extend({}, origAsyncDirective, {
  7009. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7010. }),
  7011. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7012. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7013. : origAsyncDirective.templateUrl,
  7014. templateNamespace = origAsyncDirective.templateNamespace;
  7015. $compileNode.empty();
  7016. $templateRequest($sce.getTrustedResourceUrl(templateUrl))
  7017. .then(function(content) {
  7018. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7019. content = denormalizeTemplate(content);
  7020. if (origAsyncDirective.replace) {
  7021. if (jqLiteIsTextNode(content)) {
  7022. $template = [];
  7023. } else {
  7024. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7025. }
  7026. compileNode = $template[0];
  7027. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7028. throw $compileMinErr('tplrt',
  7029. "Template for directive '{0}' must have exactly one root element. {1}",
  7030. origAsyncDirective.name, templateUrl);
  7031. }
  7032. tempTemplateAttrs = {$attr: {}};
  7033. replaceWith($rootElement, $compileNode, compileNode);
  7034. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7035. if (isObject(origAsyncDirective.scope)) {
  7036. markDirectivesAsIsolate(templateDirectives);
  7037. }
  7038. directives = templateDirectives.concat(directives);
  7039. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7040. } else {
  7041. compileNode = beforeTemplateCompileNode;
  7042. $compileNode.html(content);
  7043. }
  7044. directives.unshift(derivedSyncDirective);
  7045. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7046. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7047. previousCompileContext);
  7048. forEach($rootElement, function(node, i) {
  7049. if (node == compileNode) {
  7050. $rootElement[i] = $compileNode[0];
  7051. }
  7052. });
  7053. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7054. while(linkQueue.length) {
  7055. var scope = linkQueue.shift(),
  7056. beforeTemplateLinkNode = linkQueue.shift(),
  7057. linkRootElement = linkQueue.shift(),
  7058. boundTranscludeFn = linkQueue.shift(),
  7059. linkNode = $compileNode[0];
  7060. if (scope.$$destroyed) continue;
  7061. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7062. var oldClasses = beforeTemplateLinkNode.className;
  7063. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7064. origAsyncDirective.replace)) {
  7065. // it was cloned therefore we have to clone as well.
  7066. linkNode = jqLiteClone(compileNode);
  7067. }
  7068. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7069. // Copy in CSS classes from original node
  7070. safeAddClass(jqLite(linkNode), oldClasses);
  7071. }
  7072. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7073. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7074. } else {
  7075. childBoundTranscludeFn = boundTranscludeFn;
  7076. }
  7077. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7078. childBoundTranscludeFn);
  7079. }
  7080. linkQueue = null;
  7081. });
  7082. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7083. var childBoundTranscludeFn = boundTranscludeFn;
  7084. if (scope.$$destroyed) return;
  7085. if (linkQueue) {
  7086. linkQueue.push(scope);
  7087. linkQueue.push(node);
  7088. linkQueue.push(rootElement);
  7089. linkQueue.push(childBoundTranscludeFn);
  7090. } else {
  7091. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7092. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7093. }
  7094. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  7095. }
  7096. };
  7097. }
  7098. /**
  7099. * Sorting function for bound directives.
  7100. */
  7101. function byPriority(a, b) {
  7102. var diff = b.priority - a.priority;
  7103. if (diff !== 0) return diff;
  7104. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7105. return a.index - b.index;
  7106. }
  7107. function assertNoDuplicate(what, previousDirective, directive, element) {
  7108. if (previousDirective) {
  7109. throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
  7110. previousDirective.name, directive.name, what, startingTag(element));
  7111. }
  7112. }
  7113. function addTextInterpolateDirective(directives, text) {
  7114. var interpolateFn = $interpolate(text, true);
  7115. if (interpolateFn) {
  7116. directives.push({
  7117. priority: 0,
  7118. compile: function textInterpolateCompileFn(templateNode) {
  7119. var templateNodeParent = templateNode.parent(),
  7120. hasCompileParent = !!templateNodeParent.length;
  7121. // When transcluding a template that has bindings in the root
  7122. // we don't have a parent and thus need to add the class during linking fn.
  7123. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7124. return function textInterpolateLinkFn(scope, node) {
  7125. var parent = node.parent();
  7126. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7127. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7128. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7129. node[0].nodeValue = value;
  7130. });
  7131. };
  7132. }
  7133. });
  7134. }
  7135. }
  7136. function wrapTemplate(type, template) {
  7137. type = lowercase(type || 'html');
  7138. switch(type) {
  7139. case 'svg':
  7140. case 'math':
  7141. var wrapper = document.createElement('div');
  7142. wrapper.innerHTML = '<'+type+'>'+template+'</'+type+'>';
  7143. return wrapper.childNodes[0].childNodes;
  7144. default:
  7145. return template;
  7146. }
  7147. }
  7148. function getTrustedContext(node, attrNormalizedName) {
  7149. if (attrNormalizedName == "srcdoc") {
  7150. return $sce.HTML;
  7151. }
  7152. var tag = nodeName_(node);
  7153. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7154. if (attrNormalizedName == "xlinkHref" ||
  7155. (tag == "form" && attrNormalizedName == "action") ||
  7156. (tag != "img" && (attrNormalizedName == "src" ||
  7157. attrNormalizedName == "ngSrc"))) {
  7158. return $sce.RESOURCE_URL;
  7159. }
  7160. }
  7161. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7162. var interpolateFn = $interpolate(value, true);
  7163. // no interpolation found -> ignore
  7164. if (!interpolateFn) return;
  7165. if (name === "multiple" && nodeName_(node) === "select") {
  7166. throw $compileMinErr("selmulti",
  7167. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7168. startingTag(node));
  7169. }
  7170. directives.push({
  7171. priority: 100,
  7172. compile: function() {
  7173. return {
  7174. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7175. var $$observers = (attr.$$observers || (attr.$$observers = {}));
  7176. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7177. throw $compileMinErr('nodomevents',
  7178. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7179. "ng- versions (such as ng-click instead of onclick) instead.");
  7180. }
  7181. // If the attribute was removed, then we are done
  7182. if (!attr[name]) {
  7183. return;
  7184. }
  7185. // we need to interpolate again, in case the attribute value has been updated
  7186. // (e.g. by another directive's compile function)
  7187. interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name),
  7188. ALL_OR_NOTHING_ATTRS[name] || allOrNothing);
  7189. // if attribute was updated so that there is no interpolation going on we don't want to
  7190. // register any observers
  7191. if (!interpolateFn) return;
  7192. // initialize attr object so that it's ready in case we need the value for isolate
  7193. // scope initialization, otherwise the value would not be available from isolate
  7194. // directive's linking fn during linking phase
  7195. attr[name] = interpolateFn(scope);
  7196. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7197. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7198. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7199. //special case for class attribute addition + removal
  7200. //so that class changes can tap into the animation
  7201. //hooks provided by the $animate service. Be sure to
  7202. //skip animations when the first digest occurs (when
  7203. //both the new and the old values are the same) since
  7204. //the CSS classes are the non-interpolated values
  7205. if(name === 'class' && newValue != oldValue) {
  7206. attr.$updateClass(newValue, oldValue);
  7207. } else {
  7208. attr.$set(name, newValue);
  7209. }
  7210. });
  7211. }
  7212. };
  7213. }
  7214. });
  7215. }
  7216. /**
  7217. * This is a special jqLite.replaceWith, which can replace items which
  7218. * have no parents, provided that the containing jqLite collection is provided.
  7219. *
  7220. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7221. * in the root of the tree.
  7222. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7223. * the shell, but replace its DOM node reference.
  7224. * @param {Node} newNode The new DOM node.
  7225. */
  7226. function replaceWith($rootElement, elementsToRemove, newNode) {
  7227. var firstElementToRemove = elementsToRemove[0],
  7228. removeCount = elementsToRemove.length,
  7229. parent = firstElementToRemove.parentNode,
  7230. i, ii;
  7231. if ($rootElement) {
  7232. for(i = 0, ii = $rootElement.length; i < ii; i++) {
  7233. if ($rootElement[i] == firstElementToRemove) {
  7234. $rootElement[i++] = newNode;
  7235. for (var j = i, j2 = j + removeCount - 1,
  7236. jj = $rootElement.length;
  7237. j < jj; j++, j2++) {
  7238. if (j2 < jj) {
  7239. $rootElement[j] = $rootElement[j2];
  7240. } else {
  7241. delete $rootElement[j];
  7242. }
  7243. }
  7244. $rootElement.length -= removeCount - 1;
  7245. // If the replaced element is also the jQuery .context then replace it
  7246. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7247. // http://api.jquery.com/context/
  7248. if ($rootElement.context === firstElementToRemove) {
  7249. $rootElement.context = newNode;
  7250. }
  7251. break;
  7252. }
  7253. }
  7254. }
  7255. if (parent) {
  7256. parent.replaceChild(newNode, firstElementToRemove);
  7257. }
  7258. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7259. var fragment = document.createDocumentFragment();
  7260. fragment.appendChild(firstElementToRemove);
  7261. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7262. // data here because there's no public interface in jQuery to do that and copying over
  7263. // event listeners (which is the main use of private data) wouldn't work anyway.
  7264. jqLite(newNode).data(jqLite(firstElementToRemove).data());
  7265. // Remove data of the replaced element. We cannot just call .remove()
  7266. // on the element it since that would deallocate scope that is needed
  7267. // for the new node. Instead, remove the data "manually".
  7268. if (!jQuery) {
  7269. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7270. } else {
  7271. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7272. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7273. // the scope to be trashed and we do need the very same scope to work with the new
  7274. // element. However, we cannot just cache the non-patched version and use it here as
  7275. // that would break if another library patches the method after Angular does (one
  7276. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7277. // skipped this one time.
  7278. skipDestroyOnNextJQueryCleanData = true;
  7279. jQuery.cleanData([firstElementToRemove]);
  7280. }
  7281. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7282. var element = elementsToRemove[k];
  7283. jqLite(element).remove(); // must do this way to clean up expando
  7284. fragment.appendChild(element);
  7285. delete elementsToRemove[k];
  7286. }
  7287. elementsToRemove[0] = newNode;
  7288. elementsToRemove.length = 1;
  7289. }
  7290. function cloneAndAnnotateFn(fn, annotation) {
  7291. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7292. }
  7293. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7294. try {
  7295. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7296. } catch(e) {
  7297. $exceptionHandler(e, startingTag($element));
  7298. }
  7299. }
  7300. }];
  7301. }
  7302. var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
  7303. /**
  7304. * Converts all accepted directives format into proper directive name.
  7305. * All of these will become 'myDirective':
  7306. * my:Directive
  7307. * my-directive
  7308. * x-my-directive
  7309. * data-my:directive
  7310. *
  7311. * Also there is special case for Moz prefix starting with upper case letter.
  7312. * @param name Name to normalize
  7313. */
  7314. function directiveNormalize(name) {
  7315. return camelCase(name.replace(PREFIX_REGEXP, ''));
  7316. }
  7317. /**
  7318. * @ngdoc type
  7319. * @name $compile.directive.Attributes
  7320. *
  7321. * @description
  7322. * A shared object between directive compile / linking functions which contains normalized DOM
  7323. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  7324. * needed since all of these are treated as equivalent in Angular:
  7325. *
  7326. * ```
  7327. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  7328. * ```
  7329. */
  7330. /**
  7331. * @ngdoc property
  7332. * @name $compile.directive.Attributes#$attr
  7333. *
  7334. * @description
  7335. * A map of DOM element attribute names to the normalized name. This is
  7336. * needed to do reverse lookup from normalized name back to actual name.
  7337. */
  7338. /**
  7339. * @ngdoc method
  7340. * @name $compile.directive.Attributes#$set
  7341. * @kind function
  7342. *
  7343. * @description
  7344. * Set DOM element attribute value.
  7345. *
  7346. *
  7347. * @param {string} name Normalized element attribute name of the property to modify. The name is
  7348. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  7349. * property to the original name.
  7350. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  7351. */
  7352. /**
  7353. * Closure compiler type information
  7354. */
  7355. function nodesetLinkingFn(
  7356. /* angular.Scope */ scope,
  7357. /* NodeList */ nodeList,
  7358. /* Element */ rootElement,
  7359. /* function(Function) */ boundTranscludeFn
  7360. ){}
  7361. function directiveLinkingFn(
  7362. /* nodesetLinkingFn */ nodesetLinkingFn,
  7363. /* angular.Scope */ scope,
  7364. /* Node */ node,
  7365. /* Element */ rootElement,
  7366. /* function(Function) */ boundTranscludeFn
  7367. ){}
  7368. function tokenDifference(str1, str2) {
  7369. var values = '',
  7370. tokens1 = str1.split(/\s+/),
  7371. tokens2 = str2.split(/\s+/);
  7372. outer:
  7373. for(var i = 0; i < tokens1.length; i++) {
  7374. var token = tokens1[i];
  7375. for(var j = 0; j < tokens2.length; j++) {
  7376. if(token == tokens2[j]) continue outer;
  7377. }
  7378. values += (values.length > 0 ? ' ' : '') + token;
  7379. }
  7380. return values;
  7381. }
  7382. function removeComments(jqNodes) {
  7383. jqNodes = jqLite(jqNodes);
  7384. var i = jqNodes.length;
  7385. if (i <= 1) {
  7386. return jqNodes;
  7387. }
  7388. while (i--) {
  7389. var node = jqNodes[i];
  7390. if (node.nodeType === NODE_TYPE_COMMENT) {
  7391. splice.call(jqNodes, i, 1);
  7392. }
  7393. }
  7394. return jqNodes;
  7395. }
  7396. /**
  7397. * @ngdoc provider
  7398. * @name $controllerProvider
  7399. * @description
  7400. * The {@link ng.$controller $controller service} is used by Angular to create new
  7401. * controllers.
  7402. *
  7403. * This provider allows controller registration via the
  7404. * {@link ng.$controllerProvider#register register} method.
  7405. */
  7406. function $ControllerProvider() {
  7407. var controllers = {},
  7408. globals = false,
  7409. CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  7410. /**
  7411. * @ngdoc method
  7412. * @name $controllerProvider#register
  7413. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  7414. * the names and the values are the constructors.
  7415. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  7416. * annotations in the array notation).
  7417. */
  7418. this.register = function(name, constructor) {
  7419. assertNotHasOwnProperty(name, 'controller');
  7420. if (isObject(name)) {
  7421. extend(controllers, name);
  7422. } else {
  7423. controllers[name] = constructor;
  7424. }
  7425. };
  7426. /**
  7427. * @ngdoc method
  7428. * @name $controllerProvider#allowGlobals
  7429. * @description If called, allows `$controller` to find controller constructors on `window`
  7430. */
  7431. this.allowGlobals = function() {
  7432. globals = true;
  7433. };
  7434. this.$get = ['$injector', '$window', function($injector, $window) {
  7435. /**
  7436. * @ngdoc service
  7437. * @name $controller
  7438. * @requires $injector
  7439. *
  7440. * @param {Function|string} constructor If called with a function then it's considered to be the
  7441. * controller constructor function. Otherwise it's considered to be a string which is used
  7442. * to retrieve the controller constructor using the following steps:
  7443. *
  7444. * * check if a controller with given name is registered via `$controllerProvider`
  7445. * * check if evaluating the string on the current scope returns a constructor
  7446. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  7447. * `window` object (not recommended)
  7448. *
  7449. * @param {Object} locals Injection locals for Controller.
  7450. * @return {Object} Instance of given controller.
  7451. *
  7452. * @description
  7453. * `$controller` service is responsible for instantiating controllers.
  7454. *
  7455. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  7456. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  7457. */
  7458. return function(expression, locals, later, ident) {
  7459. // PRIVATE API:
  7460. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  7461. // If true, $controller will allocate the object with the correct
  7462. // prototype chain, but will not invoke the controller until a returned
  7463. // callback is invoked.
  7464. // param `ident` --- An optional label which overrides the label parsed from the controller
  7465. // expression, if any.
  7466. var instance, match, constructor, identifier;
  7467. later = later === true;
  7468. if (ident && isString(ident)) {
  7469. identifier = ident;
  7470. }
  7471. if(isString(expression)) {
  7472. match = expression.match(CNTRL_REG),
  7473. constructor = match[1],
  7474. identifier = identifier || match[3];
  7475. expression = controllers.hasOwnProperty(constructor)
  7476. ? controllers[constructor]
  7477. : getter(locals.$scope, constructor, true) ||
  7478. (globals ? getter($window, constructor, true) : undefined);
  7479. assertArgFn(expression, constructor, true);
  7480. }
  7481. if (later) {
  7482. // Instantiate controller later:
  7483. // This machinery is used to create an instance of the object before calling the
  7484. // controller's constructor itself.
  7485. //
  7486. // This allows properties to be added to the controller before the constructor is
  7487. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  7488. //
  7489. // This feature is not intended for use by applications, and is thus not documented
  7490. // publicly.
  7491. var Constructor = function() {};
  7492. Constructor.prototype = (isArray(expression) ?
  7493. expression[expression.length - 1] : expression).prototype;
  7494. instance = new Constructor();
  7495. if (identifier) {
  7496. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7497. }
  7498. return extend(function() {
  7499. $injector.invoke(expression, instance, locals, constructor);
  7500. return instance;
  7501. }, {
  7502. instance: instance,
  7503. identifier: identifier
  7504. });
  7505. }
  7506. instance = $injector.instantiate(expression, locals, constructor);
  7507. if (identifier) {
  7508. addIdentifier(locals, identifier, instance, constructor || expression.name);
  7509. }
  7510. return instance;
  7511. };
  7512. function addIdentifier(locals, identifier, instance, name) {
  7513. if (!(locals && isObject(locals.$scope))) {
  7514. throw minErr('$controller')('noscp',
  7515. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  7516. name, identifier);
  7517. }
  7518. locals.$scope[identifier] = instance;
  7519. }
  7520. }];
  7521. }
  7522. /**
  7523. * @ngdoc service
  7524. * @name $document
  7525. * @requires $window
  7526. *
  7527. * @description
  7528. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  7529. *
  7530. * @example
  7531. <example module="documentExample">
  7532. <file name="index.html">
  7533. <div ng-controller="ExampleController">
  7534. <p>$document title: <b ng-bind="title"></b></p>
  7535. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  7536. </div>
  7537. </file>
  7538. <file name="script.js">
  7539. angular.module('documentExample', [])
  7540. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  7541. $scope.title = $document[0].title;
  7542. $scope.windowTitle = angular.element(window.document)[0].title;
  7543. }]);
  7544. </file>
  7545. </example>
  7546. */
  7547. function $DocumentProvider(){
  7548. this.$get = ['$window', function(window){
  7549. return jqLite(window.document);
  7550. }];
  7551. }
  7552. /**
  7553. * @ngdoc service
  7554. * @name $exceptionHandler
  7555. * @requires ng.$log
  7556. *
  7557. * @description
  7558. * Any uncaught exception in angular expressions is delegated to this service.
  7559. * The default implementation simply delegates to `$log.error` which logs it into
  7560. * the browser console.
  7561. *
  7562. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  7563. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  7564. *
  7565. * ## Example:
  7566. *
  7567. * ```js
  7568. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
  7569. * return function (exception, cause) {
  7570. * exception.message += ' (caused by "' + cause + '")';
  7571. * throw exception;
  7572. * };
  7573. * });
  7574. * ```
  7575. *
  7576. * This example will override the normal action of `$exceptionHandler`, to make angular
  7577. * exceptions fail hard when they happen, instead of just logging to the console.
  7578. *
  7579. * <hr />
  7580. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  7581. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  7582. * (unless executed during a digest).
  7583. *
  7584. * If you wish, you can manually delegate exceptions, e.g.
  7585. * `try { ... } catch(e) { $exceptionHandler(e); }`
  7586. *
  7587. * @param {Error} exception Exception associated with the error.
  7588. * @param {string=} cause optional information about the context in which
  7589. * the error was thrown.
  7590. *
  7591. */
  7592. function $ExceptionHandlerProvider() {
  7593. this.$get = ['$log', function($log) {
  7594. return function(exception, cause) {
  7595. $log.error.apply($log, arguments);
  7596. };
  7597. }];
  7598. }
  7599. /**
  7600. * Parse headers into key value object
  7601. *
  7602. * @param {string} headers Raw headers as a string
  7603. * @returns {Object} Parsed headers as key value object
  7604. */
  7605. function parseHeaders(headers) {
  7606. var parsed = {}, key, val, i;
  7607. if (!headers) return parsed;
  7608. forEach(headers.split('\n'), function(line) {
  7609. i = line.indexOf(':');
  7610. key = lowercase(trim(line.substr(0, i)));
  7611. val = trim(line.substr(i + 1));
  7612. if (key) {
  7613. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  7614. }
  7615. });
  7616. return parsed;
  7617. }
  7618. /**
  7619. * Returns a function that provides access to parsed headers.
  7620. *
  7621. * Headers are lazy parsed when first requested.
  7622. * @see parseHeaders
  7623. *
  7624. * @param {(string|Object)} headers Headers to provide access to.
  7625. * @returns {function(string=)} Returns a getter function which if called with:
  7626. *
  7627. * - if called with single an argument returns a single header value or null
  7628. * - if called with no arguments returns an object containing all headers.
  7629. */
  7630. function headersGetter(headers) {
  7631. var headersObj = isObject(headers) ? headers : undefined;
  7632. return function(name) {
  7633. if (!headersObj) headersObj = parseHeaders(headers);
  7634. if (name) {
  7635. return headersObj[lowercase(name)] || null;
  7636. }
  7637. return headersObj;
  7638. };
  7639. }
  7640. /**
  7641. * Chain all given functions
  7642. *
  7643. * This function is used for both request and response transforming
  7644. *
  7645. * @param {*} data Data to transform.
  7646. * @param {function(string=)} headers Http headers getter fn.
  7647. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  7648. * @returns {*} Transformed data.
  7649. */
  7650. function transformData(data, headers, fns) {
  7651. if (isFunction(fns))
  7652. return fns(data, headers);
  7653. forEach(fns, function(fn) {
  7654. data = fn(data, headers);
  7655. });
  7656. return data;
  7657. }
  7658. function isSuccess(status) {
  7659. return 200 <= status && status < 300;
  7660. }
  7661. /**
  7662. * @ngdoc provider
  7663. * @name $httpProvider
  7664. * @description
  7665. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  7666. * */
  7667. function $HttpProvider() {
  7668. var JSON_START = /^\s*(\[|\{[^\{])/,
  7669. JSON_END = /[\}\]]\s*$/,
  7670. PROTECTION_PREFIX = /^\)\]\}',?\n/,
  7671. APPLICATION_JSON = 'application/json',
  7672. CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  7673. /**
  7674. * @ngdoc property
  7675. * @name $httpProvider#defaults
  7676. * @description
  7677. *
  7678. * Object containing default values for all {@link ng.$http $http} requests.
  7679. *
  7680. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  7681. * Defaults value is `'XSRF-TOKEN'`.
  7682. *
  7683. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  7684. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  7685. *
  7686. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  7687. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  7688. * setting default headers.
  7689. * - **`defaults.headers.common`**
  7690. * - **`defaults.headers.post`**
  7691. * - **`defaults.headers.put`**
  7692. * - **`defaults.headers.patch`**
  7693. **/
  7694. var defaults = this.defaults = {
  7695. // transform incoming response data
  7696. transformResponse: [function defaultHttpResponseTransform(data, headers) {
  7697. if (isString(data)) {
  7698. // strip json vulnerability protection prefix
  7699. data = data.replace(PROTECTION_PREFIX, '');
  7700. var contentType = headers('Content-Type');
  7701. if ((contentType && contentType.indexOf(APPLICATION_JSON) === 0) ||
  7702. (JSON_START.test(data) && JSON_END.test(data))) {
  7703. data = fromJson(data);
  7704. }
  7705. }
  7706. return data;
  7707. }],
  7708. // transform outgoing request data
  7709. transformRequest: [function(d) {
  7710. return isObject(d) && !isFile(d) && !isBlob(d) ? toJson(d) : d;
  7711. }],
  7712. // default headers
  7713. headers: {
  7714. common: {
  7715. 'Accept': 'application/json, text/plain, */*'
  7716. },
  7717. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7718. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  7719. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  7720. },
  7721. xsrfCookieName: 'XSRF-TOKEN',
  7722. xsrfHeaderName: 'X-XSRF-TOKEN'
  7723. };
  7724. var useApplyAsync = false;
  7725. /**
  7726. * @ngdoc method
  7727. * @name $httpProvider#useApplyAsync
  7728. * @description
  7729. *
  7730. * Configure $http service to combine processing of multiple http responses received at around
  7731. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  7732. * significant performance improvement for bigger applications that make many HTTP requests
  7733. * concurrently (common during application bootstrap).
  7734. *
  7735. * Defaults to false. If no value is specifed, returns the current configured value.
  7736. *
  7737. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  7738. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  7739. * to load and share the same digest cycle.
  7740. *
  7741. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  7742. * otherwise, returns the current configured value.
  7743. **/
  7744. this.useApplyAsync = function(value) {
  7745. if (isDefined(value)) {
  7746. useApplyAsync = !!value;
  7747. return this;
  7748. }
  7749. return useApplyAsync;
  7750. };
  7751. /**
  7752. * Are ordered by request, i.e. they are applied in the same order as the
  7753. * array, on request, but reverse order, on response.
  7754. */
  7755. var interceptorFactories = this.interceptors = [];
  7756. this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
  7757. function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
  7758. var defaultCache = $cacheFactory('$http');
  7759. /**
  7760. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  7761. * The reversal is needed so that we can build up the interception chain around the
  7762. * server request.
  7763. */
  7764. var reversedInterceptors = [];
  7765. forEach(interceptorFactories, function(interceptorFactory) {
  7766. reversedInterceptors.unshift(isString(interceptorFactory)
  7767. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  7768. });
  7769. /**
  7770. * @ngdoc service
  7771. * @kind function
  7772. * @name $http
  7773. * @requires ng.$httpBackend
  7774. * @requires $cacheFactory
  7775. * @requires $rootScope
  7776. * @requires $q
  7777. * @requires $injector
  7778. *
  7779. * @description
  7780. * The `$http` service is a core Angular service that facilitates communication with the remote
  7781. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  7782. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  7783. *
  7784. * For unit testing applications that use `$http` service, see
  7785. * {@link ngMock.$httpBackend $httpBackend mock}.
  7786. *
  7787. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  7788. * $resource} service.
  7789. *
  7790. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  7791. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  7792. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  7793. *
  7794. *
  7795. * ## General usage
  7796. * The `$http` service is a function which takes a single argument — a configuration object —
  7797. * that is used to generate an HTTP request and returns a {@link ng.$q promise}
  7798. * with two $http specific methods: `success` and `error`.
  7799. *
  7800. * ```js
  7801. * // Simple GET request example :
  7802. * $http.get('/someUrl').
  7803. * success(function(data, status, headers, config) {
  7804. * // this callback will be called asynchronously
  7805. * // when the response is available
  7806. * }).
  7807. * error(function(data, status, headers, config) {
  7808. * // called asynchronously if an error occurs
  7809. * // or server returns response with an error status.
  7810. * });
  7811. * ```
  7812. *
  7813. * ```js
  7814. * // Simple POST request example (passing data) :
  7815. * $http.post('/someUrl', {msg:'hello word!'}).
  7816. * success(function(data, status, headers, config) {
  7817. * // this callback will be called asynchronously
  7818. * // when the response is available
  7819. * }).
  7820. * error(function(data, status, headers, config) {
  7821. * // called asynchronously if an error occurs
  7822. * // or server returns response with an error status.
  7823. * });
  7824. * ```
  7825. *
  7826. *
  7827. * Since the returned value of calling the $http function is a `promise`, you can also use
  7828. * the `then` method to register callbacks, and these callbacks will receive a single argument –
  7829. * an object representing the response. See the API signature and type info below for more
  7830. * details.
  7831. *
  7832. * A response status code between 200 and 299 is considered a success status and
  7833. * will result in the success callback being called. Note that if the response is a redirect,
  7834. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  7835. * called for such responses.
  7836. *
  7837. * ## Writing Unit Tests that use $http
  7838. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  7839. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  7840. * request using trained responses.
  7841. *
  7842. * ```
  7843. * $httpBackend.expectGET(...);
  7844. * $http.get(...);
  7845. * $httpBackend.flush();
  7846. * ```
  7847. *
  7848. * ## Shortcut methods
  7849. *
  7850. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  7851. * request data must be passed in for POST/PUT requests.
  7852. *
  7853. * ```js
  7854. * $http.get('/someUrl').success(successCallback);
  7855. * $http.post('/someUrl', data).success(successCallback);
  7856. * ```
  7857. *
  7858. * Complete list of shortcut methods:
  7859. *
  7860. * - {@link ng.$http#get $http.get}
  7861. * - {@link ng.$http#head $http.head}
  7862. * - {@link ng.$http#post $http.post}
  7863. * - {@link ng.$http#put $http.put}
  7864. * - {@link ng.$http#delete $http.delete}
  7865. * - {@link ng.$http#jsonp $http.jsonp}
  7866. * - {@link ng.$http#patch $http.patch}
  7867. *
  7868. *
  7869. * ## Setting HTTP Headers
  7870. *
  7871. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  7872. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  7873. * object, which currently contains this default configuration:
  7874. *
  7875. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  7876. * - `Accept: application/json, text/plain, * / *`
  7877. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  7878. * - `Content-Type: application/json`
  7879. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  7880. * - `Content-Type: application/json`
  7881. *
  7882. * To add or overwrite these defaults, simply add or remove a property from these configuration
  7883. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  7884. * with the lowercased HTTP method name as the key, e.g.
  7885. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
  7886. *
  7887. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  7888. * fashion. For example:
  7889. *
  7890. * ```
  7891. * module.run(function($http) {
  7892. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  7893. * });
  7894. * ```
  7895. *
  7896. * In addition, you can supply a `headers` property in the config object passed when
  7897. * calling `$http(config)`, which overrides the defaults without changing them globally.
  7898. *
  7899. *
  7900. * ## Transforming Requests and Responses
  7901. *
  7902. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  7903. * and `transformResponse`. These properties can be a single function that returns
  7904. * the transformed value (`{function(data, headersGetter)`) or an array of such transformation functions,
  7905. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  7906. *
  7907. * ### Default Transformations
  7908. *
  7909. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  7910. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  7911. * then these will be applied.
  7912. *
  7913. * You can augment or replace the default transformations by modifying these properties by adding to or
  7914. * replacing the array.
  7915. *
  7916. * Angular provides the following default transformations:
  7917. *
  7918. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  7919. *
  7920. * - If the `data` property of the request configuration object contains an object, serialize it
  7921. * into JSON format.
  7922. *
  7923. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  7924. *
  7925. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  7926. * - If JSON response is detected, deserialize it using a JSON parser.
  7927. *
  7928. *
  7929. * ### Overriding the Default Transformations Per Request
  7930. *
  7931. * If you wish override the request/response transformations only for a single request then provide
  7932. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  7933. * into `$http`.
  7934. *
  7935. * Note that if you provide these properties on the config object the default transformations will be
  7936. * overwritten. If you wish to augment the default transformations then you must include them in your
  7937. * local transformation array.
  7938. *
  7939. * The following code demonstrates adding a new response transformation to be run after the default response
  7940. * transformations have been run.
  7941. *
  7942. * ```js
  7943. * function appendTransform(defaults, transform) {
  7944. *
  7945. * // We can't guarantee that the default transformation is an array
  7946. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  7947. *
  7948. * // Append the new transformation to the defaults
  7949. * return defaults.concat(transform);
  7950. * }
  7951. *
  7952. * $http({
  7953. * url: '...',
  7954. * method: 'GET',
  7955. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  7956. * return doTransform(value);
  7957. * })
  7958. * });
  7959. * ```
  7960. *
  7961. *
  7962. * ## Caching
  7963. *
  7964. * To enable caching, set the request configuration `cache` property to `true` (to use default
  7965. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  7966. * When the cache is enabled, `$http` stores the response from the server in the specified
  7967. * cache. The next time the same request is made, the response is served from the cache without
  7968. * sending a request to the server.
  7969. *
  7970. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  7971. * the same way that real requests are.
  7972. *
  7973. * If there are multiple GET requests for the same URL that should be cached using the same
  7974. * cache, but the cache is not populated yet, only one request to the server will be made and
  7975. * the remaining requests will be fulfilled using the response from the first request.
  7976. *
  7977. * You can change the default cache to a new object (built with
  7978. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  7979. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  7980. * their `cache` property to `true` will now use this cache object.
  7981. *
  7982. * If you set the default cache to `false` then only requests that specify their own custom
  7983. * cache object will be cached.
  7984. *
  7985. * ## Interceptors
  7986. *
  7987. * Before you start creating interceptors, be sure to understand the
  7988. * {@link ng.$q $q and deferred/promise APIs}.
  7989. *
  7990. * For purposes of global error handling, authentication, or any kind of synchronous or
  7991. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  7992. * able to intercept requests before they are handed to the server and
  7993. * responses before they are handed over to the application code that
  7994. * initiated these requests. The interceptors leverage the {@link ng.$q
  7995. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  7996. *
  7997. * The interceptors are service factories that are registered with the `$httpProvider` by
  7998. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  7999. * injected with dependencies (if specified) and returns the interceptor.
  8000. *
  8001. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  8002. *
  8003. * * `request`: interceptors get called with a http `config` object. The function is free to
  8004. * modify the `config` object or create a new one. The function needs to return the `config`
  8005. * object directly, or a promise containing the `config` or a new `config` object.
  8006. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  8007. * resolved with a rejection.
  8008. * * `response`: interceptors get called with http `response` object. The function is free to
  8009. * modify the `response` object or create a new one. The function needs to return the `response`
  8010. * object directly, or as a promise containing the `response` or a new `response` object.
  8011. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  8012. * resolved with a rejection.
  8013. *
  8014. *
  8015. * ```js
  8016. * // register the interceptor as a service
  8017. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  8018. * return {
  8019. * // optional method
  8020. * 'request': function(config) {
  8021. * // do something on success
  8022. * return config;
  8023. * },
  8024. *
  8025. * // optional method
  8026. * 'requestError': function(rejection) {
  8027. * // do something on error
  8028. * if (canRecover(rejection)) {
  8029. * return responseOrNewPromise
  8030. * }
  8031. * return $q.reject(rejection);
  8032. * },
  8033. *
  8034. *
  8035. *
  8036. * // optional method
  8037. * 'response': function(response) {
  8038. * // do something on success
  8039. * return response;
  8040. * },
  8041. *
  8042. * // optional method
  8043. * 'responseError': function(rejection) {
  8044. * // do something on error
  8045. * if (canRecover(rejection)) {
  8046. * return responseOrNewPromise
  8047. * }
  8048. * return $q.reject(rejection);
  8049. * }
  8050. * };
  8051. * });
  8052. *
  8053. * $httpProvider.interceptors.push('myHttpInterceptor');
  8054. *
  8055. *
  8056. * // alternatively, register the interceptor via an anonymous factory
  8057. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  8058. * return {
  8059. * 'request': function(config) {
  8060. * // same as above
  8061. * },
  8062. *
  8063. * 'response': function(response) {
  8064. * // same as above
  8065. * }
  8066. * };
  8067. * });
  8068. * ```
  8069. *
  8070. * ## Security Considerations
  8071. *
  8072. * When designing web applications, consider security threats from:
  8073. *
  8074. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8075. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  8076. *
  8077. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  8078. * pre-configured with strategies that address these issues, but for this to work backend server
  8079. * cooperation is required.
  8080. *
  8081. * ### JSON Vulnerability Protection
  8082. *
  8083. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  8084. * allows third party website to turn your JSON resource URL into
  8085. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  8086. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  8087. * Angular will automatically strip the prefix before processing it as JSON.
  8088. *
  8089. * For example if your server needs to return:
  8090. * ```js
  8091. * ['one','two']
  8092. * ```
  8093. *
  8094. * which is vulnerable to attack, your server can return:
  8095. * ```js
  8096. * )]}',
  8097. * ['one','two']
  8098. * ```
  8099. *
  8100. * Angular will strip the prefix, before processing the JSON.
  8101. *
  8102. *
  8103. * ### Cross Site Request Forgery (XSRF) Protection
  8104. *
  8105. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  8106. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  8107. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  8108. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  8109. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  8110. * the XHR came from JavaScript running on your domain. The header will not be set for
  8111. * cross-domain requests.
  8112. *
  8113. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  8114. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  8115. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  8116. * that only JavaScript running on your domain could have sent the request. The token must be
  8117. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  8118. * making up its own tokens). We recommend that the token is a digest of your site's
  8119. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  8120. * for added security.
  8121. *
  8122. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  8123. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  8124. * or the per-request config object.
  8125. *
  8126. *
  8127. * @param {object} config Object describing the request to be made and how it should be
  8128. * processed. The object has following properties:
  8129. *
  8130. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  8131. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  8132. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
  8133. * to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
  8134. * JSONified.
  8135. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  8136. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  8137. * HTTP headers to send to the server. If the return value of a function is null, the
  8138. * header will not be sent.
  8139. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  8140. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  8141. * - **transformRequest** –
  8142. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8143. * transform function or an array of such functions. The transform function takes the http
  8144. * request body and headers and returns its transformed (typically serialized) version.
  8145. * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations}
  8146. * - **transformResponse** –
  8147. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  8148. * transform function or an array of such functions. The transform function takes the http
  8149. * response body and headers and returns its transformed (typically deserialized) version.
  8150. * See {@link #overriding-the-default-transformations-per-request Overriding the Default Transformations}
  8151. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  8152. * GET request, otherwise if a cache instance built with
  8153. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  8154. * caching.
  8155. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  8156. * that should abort the request when resolved.
  8157. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  8158. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  8159. * for more information.
  8160. * - **responseType** - `{string}` - see
  8161. * [requestType](https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType).
  8162. *
  8163. * @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
  8164. * standard `then` method and two http specific methods: `success` and `error`. The `then`
  8165. * method takes two arguments a success and an error callback which will be called with a
  8166. * response object. The `success` and `error` methods take a single argument - a function that
  8167. * will be called when the request succeeds or fails respectively. The arguments passed into
  8168. * these functions are destructured representation of the response object passed into the
  8169. * `then` method. The response object has these properties:
  8170. *
  8171. * - **data** – `{string|Object}` – The response body transformed with the transform
  8172. * functions.
  8173. * - **status** – `{number}` – HTTP status code of the response.
  8174. * - **headers** – `{function([headerName])}` – Header getter function.
  8175. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8176. * - **statusText** – `{string}` – HTTP status text of the response.
  8177. *
  8178. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  8179. * requests. This is primarily meant to be used for debugging purposes.
  8180. *
  8181. *
  8182. * @example
  8183. <example module="httpExample">
  8184. <file name="index.html">
  8185. <div ng-controller="FetchController">
  8186. <select ng-model="method">
  8187. <option>GET</option>
  8188. <option>JSONP</option>
  8189. </select>
  8190. <input type="text" ng-model="url" size="80"/>
  8191. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  8192. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  8193. <button id="samplejsonpbtn"
  8194. ng-click="updateModel('JSONP',
  8195. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  8196. Sample JSONP
  8197. </button>
  8198. <button id="invalidjsonpbtn"
  8199. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  8200. Invalid JSONP
  8201. </button>
  8202. <pre>http status code: {{status}}</pre>
  8203. <pre>http response data: {{data}}</pre>
  8204. </div>
  8205. </file>
  8206. <file name="script.js">
  8207. angular.module('httpExample', [])
  8208. .controller('FetchController', ['$scope', '$http', '$templateCache',
  8209. function($scope, $http, $templateCache) {
  8210. $scope.method = 'GET';
  8211. $scope.url = 'http-hello.html';
  8212. $scope.fetch = function() {
  8213. $scope.code = null;
  8214. $scope.response = null;
  8215. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  8216. success(function(data, status) {
  8217. $scope.status = status;
  8218. $scope.data = data;
  8219. }).
  8220. error(function(data, status) {
  8221. $scope.data = data || "Request failed";
  8222. $scope.status = status;
  8223. });
  8224. };
  8225. $scope.updateModel = function(method, url) {
  8226. $scope.method = method;
  8227. $scope.url = url;
  8228. };
  8229. }]);
  8230. </file>
  8231. <file name="http-hello.html">
  8232. Hello, $http!
  8233. </file>
  8234. <file name="protractor.js" type="protractor">
  8235. var status = element(by.binding('status'));
  8236. var data = element(by.binding('data'));
  8237. var fetchBtn = element(by.id('fetchbtn'));
  8238. var sampleGetBtn = element(by.id('samplegetbtn'));
  8239. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  8240. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  8241. it('should make an xhr GET request', function() {
  8242. sampleGetBtn.click();
  8243. fetchBtn.click();
  8244. expect(status.getText()).toMatch('200');
  8245. expect(data.getText()).toMatch(/Hello, \$http!/);
  8246. });
  8247. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  8248. // it('should make a JSONP request to angularjs.org', function() {
  8249. // sampleJsonpBtn.click();
  8250. // fetchBtn.click();
  8251. // expect(status.getText()).toMatch('200');
  8252. // expect(data.getText()).toMatch(/Super Hero!/);
  8253. // });
  8254. it('should make JSONP request to invalid URL and invoke the error handler',
  8255. function() {
  8256. invalidJsonpBtn.click();
  8257. fetchBtn.click();
  8258. expect(status.getText()).toMatch('0');
  8259. expect(data.getText()).toMatch('Request failed');
  8260. });
  8261. </file>
  8262. </example>
  8263. */
  8264. function $http(requestConfig) {
  8265. var config = {
  8266. method: 'get',
  8267. transformRequest: defaults.transformRequest,
  8268. transformResponse: defaults.transformResponse
  8269. };
  8270. var headers = mergeHeaders(requestConfig);
  8271. extend(config, requestConfig);
  8272. config.headers = headers;
  8273. config.method = uppercase(config.method);
  8274. var serverRequest = function(config) {
  8275. headers = config.headers;
  8276. var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
  8277. // strip content-type if data is undefined
  8278. if (isUndefined(reqData)) {
  8279. forEach(headers, function(value, header) {
  8280. if (lowercase(header) === 'content-type') {
  8281. delete headers[header];
  8282. }
  8283. });
  8284. }
  8285. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  8286. config.withCredentials = defaults.withCredentials;
  8287. }
  8288. // send request
  8289. return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
  8290. };
  8291. var chain = [serverRequest, undefined];
  8292. var promise = $q.when(config);
  8293. // apply interceptors
  8294. forEach(reversedInterceptors, function(interceptor) {
  8295. if (interceptor.request || interceptor.requestError) {
  8296. chain.unshift(interceptor.request, interceptor.requestError);
  8297. }
  8298. if (interceptor.response || interceptor.responseError) {
  8299. chain.push(interceptor.response, interceptor.responseError);
  8300. }
  8301. });
  8302. while(chain.length) {
  8303. var thenFn = chain.shift();
  8304. var rejectFn = chain.shift();
  8305. promise = promise.then(thenFn, rejectFn);
  8306. }
  8307. promise.success = function(fn) {
  8308. promise.then(function(response) {
  8309. fn(response.data, response.status, response.headers, config);
  8310. });
  8311. return promise;
  8312. };
  8313. promise.error = function(fn) {
  8314. promise.then(null, function(response) {
  8315. fn(response.data, response.status, response.headers, config);
  8316. });
  8317. return promise;
  8318. };
  8319. return promise;
  8320. function transformResponse(response) {
  8321. // make a copy since the response must be cacheable
  8322. var resp = extend({}, response);
  8323. if (!response.data) {
  8324. resp.data = response.data;
  8325. } else {
  8326. resp.data = transformData(response.data, response.headers, config.transformResponse);
  8327. }
  8328. return (isSuccess(response.status))
  8329. ? resp
  8330. : $q.reject(resp);
  8331. }
  8332. function mergeHeaders(config) {
  8333. var defHeaders = defaults.headers,
  8334. reqHeaders = extend({}, config.headers),
  8335. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  8336. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  8337. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  8338. defaultHeadersIteration:
  8339. for (defHeaderName in defHeaders) {
  8340. lowercaseDefHeaderName = lowercase(defHeaderName);
  8341. for (reqHeaderName in reqHeaders) {
  8342. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  8343. continue defaultHeadersIteration;
  8344. }
  8345. }
  8346. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  8347. }
  8348. // execute if header value is a function for merged headers
  8349. execHeaders(reqHeaders);
  8350. return reqHeaders;
  8351. function execHeaders(headers) {
  8352. var headerContent;
  8353. forEach(headers, function(headerFn, header) {
  8354. if (isFunction(headerFn)) {
  8355. headerContent = headerFn();
  8356. if (headerContent != null) {
  8357. headers[header] = headerContent;
  8358. } else {
  8359. delete headers[header];
  8360. }
  8361. }
  8362. });
  8363. }
  8364. }
  8365. }
  8366. $http.pendingRequests = [];
  8367. /**
  8368. * @ngdoc method
  8369. * @name $http#get
  8370. *
  8371. * @description
  8372. * Shortcut method to perform `GET` request.
  8373. *
  8374. * @param {string} url Relative or absolute URL specifying the destination of the request
  8375. * @param {Object=} config Optional configuration object
  8376. * @returns {HttpPromise} Future object
  8377. */
  8378. /**
  8379. * @ngdoc method
  8380. * @name $http#delete
  8381. *
  8382. * @description
  8383. * Shortcut method to perform `DELETE` request.
  8384. *
  8385. * @param {string} url Relative or absolute URL specifying the destination of the request
  8386. * @param {Object=} config Optional configuration object
  8387. * @returns {HttpPromise} Future object
  8388. */
  8389. /**
  8390. * @ngdoc method
  8391. * @name $http#head
  8392. *
  8393. * @description
  8394. * Shortcut method to perform `HEAD` request.
  8395. *
  8396. * @param {string} url Relative or absolute URL specifying the destination of the request
  8397. * @param {Object=} config Optional configuration object
  8398. * @returns {HttpPromise} Future object
  8399. */
  8400. /**
  8401. * @ngdoc method
  8402. * @name $http#jsonp
  8403. *
  8404. * @description
  8405. * Shortcut method to perform `JSONP` request.
  8406. *
  8407. * @param {string} url Relative or absolute URL specifying the destination of the request.
  8408. * The name of the callback should be the string `JSON_CALLBACK`.
  8409. * @param {Object=} config Optional configuration object
  8410. * @returns {HttpPromise} Future object
  8411. */
  8412. createShortMethods('get', 'delete', 'head', 'jsonp');
  8413. /**
  8414. * @ngdoc method
  8415. * @name $http#post
  8416. *
  8417. * @description
  8418. * Shortcut method to perform `POST` request.
  8419. *
  8420. * @param {string} url Relative or absolute URL specifying the destination of the request
  8421. * @param {*} data Request content
  8422. * @param {Object=} config Optional configuration object
  8423. * @returns {HttpPromise} Future object
  8424. */
  8425. /**
  8426. * @ngdoc method
  8427. * @name $http#put
  8428. *
  8429. * @description
  8430. * Shortcut method to perform `PUT` request.
  8431. *
  8432. * @param {string} url Relative or absolute URL specifying the destination of the request
  8433. * @param {*} data Request content
  8434. * @param {Object=} config Optional configuration object
  8435. * @returns {HttpPromise} Future object
  8436. */
  8437. /**
  8438. * @ngdoc method
  8439. * @name $http#patch
  8440. *
  8441. * @description
  8442. * Shortcut method to perform `PATCH` request.
  8443. *
  8444. * @param {string} url Relative or absolute URL specifying the destination of the request
  8445. * @param {*} data Request content
  8446. * @param {Object=} config Optional configuration object
  8447. * @returns {HttpPromise} Future object
  8448. */
  8449. createShortMethodsWithData('post', 'put', 'patch');
  8450. /**
  8451. * @ngdoc property
  8452. * @name $http#defaults
  8453. *
  8454. * @description
  8455. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  8456. * default headers, withCredentials as well as request and response transformations.
  8457. *
  8458. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  8459. */
  8460. $http.defaults = defaults;
  8461. return $http;
  8462. function createShortMethods(names) {
  8463. forEach(arguments, function(name) {
  8464. $http[name] = function(url, config) {
  8465. return $http(extend(config || {}, {
  8466. method: name,
  8467. url: url
  8468. }));
  8469. };
  8470. });
  8471. }
  8472. function createShortMethodsWithData(name) {
  8473. forEach(arguments, function(name) {
  8474. $http[name] = function(url, data, config) {
  8475. return $http(extend(config || {}, {
  8476. method: name,
  8477. url: url,
  8478. data: data
  8479. }));
  8480. };
  8481. });
  8482. }
  8483. /**
  8484. * Makes the request.
  8485. *
  8486. * !!! ACCESSES CLOSURE VARS:
  8487. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  8488. */
  8489. function sendReq(config, reqData, reqHeaders) {
  8490. var deferred = $q.defer(),
  8491. promise = deferred.promise,
  8492. cache,
  8493. cachedResp,
  8494. url = buildUrl(config.url, config.params);
  8495. $http.pendingRequests.push(config);
  8496. promise.then(removePendingReq, removePendingReq);
  8497. if ((config.cache || defaults.cache) && config.cache !== false &&
  8498. (config.method === 'GET' || config.method === 'JSONP')) {
  8499. cache = isObject(config.cache) ? config.cache
  8500. : isObject(defaults.cache) ? defaults.cache
  8501. : defaultCache;
  8502. }
  8503. if (cache) {
  8504. cachedResp = cache.get(url);
  8505. if (isDefined(cachedResp)) {
  8506. if (isPromiseLike(cachedResp)) {
  8507. // cached request has already been sent, but there is no response yet
  8508. cachedResp.then(removePendingReq, removePendingReq);
  8509. return cachedResp;
  8510. } else {
  8511. // serving from cache
  8512. if (isArray(cachedResp)) {
  8513. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  8514. } else {
  8515. resolvePromise(cachedResp, 200, {}, 'OK');
  8516. }
  8517. }
  8518. } else {
  8519. // put the promise for the non-transformed response into cache as a placeholder
  8520. cache.put(url, promise);
  8521. }
  8522. }
  8523. // if we won't have the response in cache, set the xsrf headers and
  8524. // send the request to the backend
  8525. if (isUndefined(cachedResp)) {
  8526. var xsrfValue = urlIsSameOrigin(config.url)
  8527. ? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
  8528. : undefined;
  8529. if (xsrfValue) {
  8530. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  8531. }
  8532. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  8533. config.withCredentials, config.responseType);
  8534. }
  8535. return promise;
  8536. /**
  8537. * Callback registered to $httpBackend():
  8538. * - caches the response if desired
  8539. * - resolves the raw $http promise
  8540. * - calls $apply
  8541. */
  8542. function done(status, response, headersString, statusText) {
  8543. if (cache) {
  8544. if (isSuccess(status)) {
  8545. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  8546. } else {
  8547. // remove promise from the cache
  8548. cache.remove(url);
  8549. }
  8550. }
  8551. function resolveHttpPromise() {
  8552. resolvePromise(response, status, headersString, statusText);
  8553. }
  8554. if (useApplyAsync) {
  8555. $rootScope.$applyAsync(resolveHttpPromise);
  8556. } else {
  8557. resolveHttpPromise();
  8558. if (!$rootScope.$$phase) $rootScope.$apply();
  8559. }
  8560. }
  8561. /**
  8562. * Resolves the raw $http promise.
  8563. */
  8564. function resolvePromise(response, status, headers, statusText) {
  8565. // normalize internal statuses to 0
  8566. status = Math.max(status, 0);
  8567. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  8568. data: response,
  8569. status: status,
  8570. headers: headersGetter(headers),
  8571. config: config,
  8572. statusText : statusText
  8573. });
  8574. }
  8575. function removePendingReq() {
  8576. var idx = $http.pendingRequests.indexOf(config);
  8577. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  8578. }
  8579. }
  8580. function buildUrl(url, params) {
  8581. if (!params) return url;
  8582. var parts = [];
  8583. forEachSorted(params, function(value, key) {
  8584. if (value === null || isUndefined(value)) return;
  8585. if (!isArray(value)) value = [value];
  8586. forEach(value, function(v) {
  8587. if (isObject(v)) {
  8588. if (isDate(v)){
  8589. v = v.toISOString();
  8590. } else {
  8591. v = toJson(v);
  8592. }
  8593. }
  8594. parts.push(encodeUriQuery(key) + '=' +
  8595. encodeUriQuery(v));
  8596. });
  8597. });
  8598. if(parts.length > 0) {
  8599. url += ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
  8600. }
  8601. return url;
  8602. }
  8603. }];
  8604. }
  8605. function createXhr() {
  8606. return new window.XMLHttpRequest();
  8607. }
  8608. /**
  8609. * @ngdoc service
  8610. * @name $httpBackend
  8611. * @requires $window
  8612. * @requires $document
  8613. *
  8614. * @description
  8615. * HTTP backend used by the {@link ng.$http service} that delegates to
  8616. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  8617. *
  8618. * You should never need to use this service directly, instead use the higher-level abstractions:
  8619. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  8620. *
  8621. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  8622. * $httpBackend} which can be trained with responses.
  8623. */
  8624. function $HttpBackendProvider() {
  8625. this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
  8626. return createHttpBackend($browser, createXhr, $browser.defer, $window.angular.callbacks, $document[0]);
  8627. }];
  8628. }
  8629. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  8630. // TODO(vojta): fix the signature
  8631. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  8632. $browser.$$incOutstandingRequestCount();
  8633. url = url || $browser.url();
  8634. if (lowercase(method) == 'jsonp') {
  8635. var callbackId = '_' + (callbacks.counter++).toString(36);
  8636. callbacks[callbackId] = function(data) {
  8637. callbacks[callbackId].data = data;
  8638. callbacks[callbackId].called = true;
  8639. };
  8640. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  8641. callbackId, function(status, text) {
  8642. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  8643. callbacks[callbackId] = noop;
  8644. });
  8645. } else {
  8646. var xhr = createXhr();
  8647. xhr.open(method, url, true);
  8648. forEach(headers, function(value, key) {
  8649. if (isDefined(value)) {
  8650. xhr.setRequestHeader(key, value);
  8651. }
  8652. });
  8653. xhr.onload = function requestLoaded() {
  8654. var statusText = xhr.statusText || '';
  8655. // responseText is the old-school way of retrieving response (supported by IE8 & 9)
  8656. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  8657. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  8658. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  8659. var status = xhr.status === 1223 ? 204 : xhr.status;
  8660. // fix status code when it is 0 (0 status is undocumented).
  8661. // Occurs when accessing file resources or on Android 4.1 stock browser
  8662. // while retrieving files from application cache.
  8663. if (status === 0) {
  8664. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  8665. }
  8666. completeRequest(callback,
  8667. status,
  8668. response,
  8669. xhr.getAllResponseHeaders(),
  8670. statusText);
  8671. };
  8672. var requestError = function () {
  8673. // The response is always empty
  8674. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  8675. completeRequest(callback, -1, null, null, '');
  8676. };
  8677. xhr.onerror = requestError;
  8678. xhr.onabort = requestError;
  8679. if (withCredentials) {
  8680. xhr.withCredentials = true;
  8681. }
  8682. if (responseType) {
  8683. try {
  8684. xhr.responseType = responseType;
  8685. } catch (e) {
  8686. // WebKit added support for the json responseType value on 09/03/2013
  8687. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  8688. // known to throw when setting the value "json" as the response type. Other older
  8689. // browsers implementing the responseType
  8690. //
  8691. // The json response type can be ignored if not supported, because JSON payloads are
  8692. // parsed on the client-side regardless.
  8693. if (responseType !== 'json') {
  8694. throw e;
  8695. }
  8696. }
  8697. }
  8698. xhr.send(post || null);
  8699. }
  8700. if (timeout > 0) {
  8701. var timeoutId = $browserDefer(timeoutRequest, timeout);
  8702. } else if (isPromiseLike(timeout)) {
  8703. timeout.then(timeoutRequest);
  8704. }
  8705. function timeoutRequest() {
  8706. jsonpDone && jsonpDone();
  8707. xhr && xhr.abort();
  8708. }
  8709. function completeRequest(callback, status, response, headersString, statusText) {
  8710. // cancel timeout and subsequent timeout promise resolution
  8711. timeoutId && $browserDefer.cancel(timeoutId);
  8712. jsonpDone = xhr = null;
  8713. callback(status, response, headersString, statusText);
  8714. $browser.$$completeOutstandingRequest(noop);
  8715. }
  8716. };
  8717. function jsonpReq(url, callbackId, done) {
  8718. // we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
  8719. // - fetches local scripts via XHR and evals them
  8720. // - adds and immediately removes script elements from the document
  8721. var script = rawDocument.createElement('script'), callback = null;
  8722. script.type = "text/javascript";
  8723. script.src = url;
  8724. script.async = true;
  8725. callback = function(event) {
  8726. removeEventListenerFn(script, "load", callback);
  8727. removeEventListenerFn(script, "error", callback);
  8728. rawDocument.body.removeChild(script);
  8729. script = null;
  8730. var status = -1;
  8731. var text = "unknown";
  8732. if (event) {
  8733. if (event.type === "load" && !callbacks[callbackId].called) {
  8734. event = { type: "error" };
  8735. }
  8736. text = event.type;
  8737. status = event.type === "error" ? 404 : 200;
  8738. }
  8739. if (done) {
  8740. done(status, text);
  8741. }
  8742. };
  8743. addEventListenerFn(script, "load", callback);
  8744. addEventListenerFn(script, "error", callback);
  8745. rawDocument.body.appendChild(script);
  8746. return callback;
  8747. }
  8748. }
  8749. var $interpolateMinErr = minErr('$interpolate');
  8750. /**
  8751. * @ngdoc provider
  8752. * @name $interpolateProvider
  8753. *
  8754. * @description
  8755. *
  8756. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  8757. *
  8758. * @example
  8759. <example module="customInterpolationApp">
  8760. <file name="index.html">
  8761. <script>
  8762. var customInterpolationApp = angular.module('customInterpolationApp', []);
  8763. customInterpolationApp.config(function($interpolateProvider) {
  8764. $interpolateProvider.startSymbol('//');
  8765. $interpolateProvider.endSymbol('//');
  8766. });
  8767. customInterpolationApp.controller('DemoController', function() {
  8768. this.label = "This binding is brought you by // interpolation symbols.";
  8769. });
  8770. </script>
  8771. <div ng-app="App" ng-controller="DemoController as demo">
  8772. //demo.label//
  8773. </div>
  8774. </file>
  8775. <file name="protractor.js" type="protractor">
  8776. it('should interpolate binding with custom symbols', function() {
  8777. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  8778. });
  8779. </file>
  8780. </example>
  8781. */
  8782. function $InterpolateProvider() {
  8783. var startSymbol = '{{';
  8784. var endSymbol = '}}';
  8785. /**
  8786. * @ngdoc method
  8787. * @name $interpolateProvider#startSymbol
  8788. * @description
  8789. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  8790. *
  8791. * @param {string=} value new value to set the starting symbol to.
  8792. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8793. */
  8794. this.startSymbol = function(value){
  8795. if (value) {
  8796. startSymbol = value;
  8797. return this;
  8798. } else {
  8799. return startSymbol;
  8800. }
  8801. };
  8802. /**
  8803. * @ngdoc method
  8804. * @name $interpolateProvider#endSymbol
  8805. * @description
  8806. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  8807. *
  8808. * @param {string=} value new value to set the ending symbol to.
  8809. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  8810. */
  8811. this.endSymbol = function(value){
  8812. if (value) {
  8813. endSymbol = value;
  8814. return this;
  8815. } else {
  8816. return endSymbol;
  8817. }
  8818. };
  8819. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  8820. var startSymbolLength = startSymbol.length,
  8821. endSymbolLength = endSymbol.length,
  8822. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  8823. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  8824. function escape(ch) {
  8825. return '\\\\\\' + ch;
  8826. }
  8827. /**
  8828. * @ngdoc service
  8829. * @name $interpolate
  8830. * @kind function
  8831. *
  8832. * @requires $parse
  8833. * @requires $sce
  8834. *
  8835. * @description
  8836. *
  8837. * Compiles a string with markup into an interpolation function. This service is used by the
  8838. * HTML {@link ng.$compile $compile} service for data binding. See
  8839. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  8840. * interpolation markup.
  8841. *
  8842. *
  8843. * ```js
  8844. * var $interpolate = ...; // injected
  8845. * var exp = $interpolate('Hello {{name | uppercase}}!');
  8846. * expect(exp({name:'Angular'}).toEqual('Hello ANGULAR!');
  8847. * ```
  8848. *
  8849. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  8850. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  8851. * evaluate to a value other than `undefined`.
  8852. *
  8853. * ```js
  8854. * var $interpolate = ...; // injected
  8855. * var context = {greeting: 'Hello', name: undefined };
  8856. *
  8857. * // default "forgiving" mode
  8858. * var exp = $interpolate('{{greeting}} {{name}}!');
  8859. * expect(exp(context)).toEqual('Hello !');
  8860. *
  8861. * // "allOrNothing" mode
  8862. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  8863. * expect(exp(context)).toBeUndefined();
  8864. * context.name = 'Angular';
  8865. * expect(exp(context)).toEqual('Hello Angular!');
  8866. * ```
  8867. *
  8868. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  8869. *
  8870. * ####Escaped Interpolation
  8871. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  8872. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  8873. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  8874. * or binding.
  8875. *
  8876. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  8877. * degree, while also enabling code examples to work without relying on the
  8878. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  8879. *
  8880. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  8881. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  8882. * interpolation start/end markers with their escaped counterparts.**
  8883. *
  8884. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  8885. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  8886. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  8887. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  8888. * this is typically useful only when user-data is used in rendering a template from the server, or
  8889. * when otherwise untrusted data is used by a directive.
  8890. *
  8891. * <example>
  8892. * <file name="index.html">
  8893. * <div ng-init="username='A user'">
  8894. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  8895. * </p>
  8896. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  8897. * application, but fails to accomplish their task, because the server has correctly
  8898. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  8899. * characters.</p>
  8900. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  8901. * from the database by an administrator.</p>
  8902. * </div>
  8903. * </file>
  8904. * </example>
  8905. *
  8906. * @param {string} text The text with markup to interpolate.
  8907. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  8908. * embedded expression in order to return an interpolation function. Strings with no
  8909. * embedded expression will return null for the interpolation function.
  8910. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  8911. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  8912. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  8913. * provides Strict Contextual Escaping for details.
  8914. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  8915. * unless all embedded expressions evaluate to a value other than `undefined`.
  8916. * @returns {function(context)} an interpolation function which is used to compute the
  8917. * interpolated string. The function has these parameters:
  8918. *
  8919. * - `context`: evaluation context for all expressions embedded in the interpolated text
  8920. */
  8921. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  8922. allOrNothing = !!allOrNothing;
  8923. var startIndex,
  8924. endIndex,
  8925. index = 0,
  8926. expressions = [],
  8927. parseFns = [],
  8928. textLength = text.length,
  8929. exp,
  8930. concat = [],
  8931. expressionPositions = [];
  8932. while(index < textLength) {
  8933. if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  8934. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
  8935. if (index !== startIndex) {
  8936. concat.push(unescapeText(text.substring(index, startIndex)));
  8937. }
  8938. exp = text.substring(startIndex + startSymbolLength, endIndex);
  8939. expressions.push(exp);
  8940. parseFns.push($parse(exp, parseStringifyInterceptor));
  8941. index = endIndex + endSymbolLength;
  8942. expressionPositions.push(concat.length);
  8943. concat.push('');
  8944. } else {
  8945. // we did not find an interpolation, so we have to add the remainder to the separators array
  8946. if (index !== textLength) {
  8947. concat.push(unescapeText(text.substring(index)));
  8948. }
  8949. break;
  8950. }
  8951. }
  8952. // Concatenating expressions makes it hard to reason about whether some combination of
  8953. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  8954. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  8955. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  8956. // make it obvious that you bound the value to some user controlled value. This helps reduce
  8957. // the load when auditing for XSS issues.
  8958. if (trustedContext && concat.length > 1) {
  8959. throw $interpolateMinErr('noconcat',
  8960. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  8961. "interpolations that concatenate multiple expressions when a trusted value is " +
  8962. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  8963. }
  8964. if (!mustHaveExpression || expressions.length) {
  8965. var compute = function(values) {
  8966. for(var i = 0, ii = expressions.length; i < ii; i++) {
  8967. if (allOrNothing && isUndefined(values[i])) return;
  8968. concat[expressionPositions[i]] = values[i];
  8969. }
  8970. return concat.join('');
  8971. };
  8972. var getValue = function (value) {
  8973. return trustedContext ?
  8974. $sce.getTrusted(trustedContext, value) :
  8975. $sce.valueOf(value);
  8976. };
  8977. var stringify = function (value) {
  8978. if (value == null) { // null || undefined
  8979. return '';
  8980. }
  8981. switch (typeof value) {
  8982. case 'string':
  8983. break;
  8984. case 'number':
  8985. value = '' + value;
  8986. break;
  8987. default:
  8988. value = toJson(value);
  8989. }
  8990. return value;
  8991. };
  8992. return extend(function interpolationFn(context) {
  8993. var i = 0;
  8994. var ii = expressions.length;
  8995. var values = new Array(ii);
  8996. try {
  8997. for (; i < ii; i++) {
  8998. values[i] = parseFns[i](context);
  8999. }
  9000. return compute(values);
  9001. } catch(err) {
  9002. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9003. err.toString());
  9004. $exceptionHandler(newErr);
  9005. }
  9006. }, {
  9007. // all of these properties are undocumented for now
  9008. exp: text, //just for compatibility with regular watchers created via $watch
  9009. expressions: expressions,
  9010. $$watchDelegate: function (scope, listener, objectEquality) {
  9011. var lastValue;
  9012. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  9013. var currValue = compute(values);
  9014. if (isFunction(listener)) {
  9015. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  9016. }
  9017. lastValue = currValue;
  9018. }, objectEquality);
  9019. }
  9020. });
  9021. }
  9022. function unescapeText(text) {
  9023. return text.replace(escapedStartRegexp, startSymbol).
  9024. replace(escapedEndRegexp, endSymbol);
  9025. }
  9026. function parseStringifyInterceptor(value) {
  9027. try {
  9028. return stringify(getValue(value));
  9029. } catch(err) {
  9030. var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
  9031. err.toString());
  9032. $exceptionHandler(newErr);
  9033. }
  9034. }
  9035. }
  9036. /**
  9037. * @ngdoc method
  9038. * @name $interpolate#startSymbol
  9039. * @description
  9040. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  9041. *
  9042. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  9043. * the symbol.
  9044. *
  9045. * @returns {string} start symbol.
  9046. */
  9047. $interpolate.startSymbol = function() {
  9048. return startSymbol;
  9049. };
  9050. /**
  9051. * @ngdoc method
  9052. * @name $interpolate#endSymbol
  9053. * @description
  9054. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9055. *
  9056. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  9057. * the symbol.
  9058. *
  9059. * @returns {string} end symbol.
  9060. */
  9061. $interpolate.endSymbol = function() {
  9062. return endSymbol;
  9063. };
  9064. return $interpolate;
  9065. }];
  9066. }
  9067. function $IntervalProvider() {
  9068. this.$get = ['$rootScope', '$window', '$q', '$$q',
  9069. function($rootScope, $window, $q, $$q) {
  9070. var intervals = {};
  9071. /**
  9072. * @ngdoc service
  9073. * @name $interval
  9074. *
  9075. * @description
  9076. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  9077. * milliseconds.
  9078. *
  9079. * The return value of registering an interval function is a promise. This promise will be
  9080. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  9081. * run indefinitely if `count` is not defined. The value of the notification will be the
  9082. * number of iterations that have run.
  9083. * To cancel an interval, call `$interval.cancel(promise)`.
  9084. *
  9085. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  9086. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  9087. * time.
  9088. *
  9089. * <div class="alert alert-warning">
  9090. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  9091. * with them. In particular they are not automatically destroyed when a controller's scope or a
  9092. * directive's element are destroyed.
  9093. * You should take this into consideration and make sure to always cancel the interval at the
  9094. * appropriate moment. See the example below for more details on how and when to do this.
  9095. * </div>
  9096. *
  9097. * @param {function()} fn A function that should be called repeatedly.
  9098. * @param {number} delay Number of milliseconds between each function call.
  9099. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  9100. * indefinitely.
  9101. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  9102. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  9103. * @returns {promise} A promise which will be notified on each iteration.
  9104. *
  9105. * @example
  9106. * <example module="intervalExample">
  9107. * <file name="index.html">
  9108. * <script>
  9109. * angular.module('intervalExample', [])
  9110. * .controller('ExampleController', ['$scope', '$interval',
  9111. * function($scope, $interval) {
  9112. * $scope.format = 'M/d/yy h:mm:ss a';
  9113. * $scope.blood_1 = 100;
  9114. * $scope.blood_2 = 120;
  9115. *
  9116. * var stop;
  9117. * $scope.fight = function() {
  9118. * // Don't start a new fight if we are already fighting
  9119. * if ( angular.isDefined(stop) ) return;
  9120. *
  9121. * stop = $interval(function() {
  9122. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  9123. * $scope.blood_1 = $scope.blood_1 - 3;
  9124. * $scope.blood_2 = $scope.blood_2 - 4;
  9125. * } else {
  9126. * $scope.stopFight();
  9127. * }
  9128. * }, 100);
  9129. * };
  9130. *
  9131. * $scope.stopFight = function() {
  9132. * if (angular.isDefined(stop)) {
  9133. * $interval.cancel(stop);
  9134. * stop = undefined;
  9135. * }
  9136. * };
  9137. *
  9138. * $scope.resetFight = function() {
  9139. * $scope.blood_1 = 100;
  9140. * $scope.blood_2 = 120;
  9141. * };
  9142. *
  9143. * $scope.$on('$destroy', function() {
  9144. * // Make sure that the interval is destroyed too
  9145. * $scope.stopFight();
  9146. * });
  9147. * }])
  9148. * // Register the 'myCurrentTime' directive factory method.
  9149. * // We inject $interval and dateFilter service since the factory method is DI.
  9150. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  9151. * function($interval, dateFilter) {
  9152. * // return the directive link function. (compile function not needed)
  9153. * return function(scope, element, attrs) {
  9154. * var format, // date format
  9155. * stopTime; // so that we can cancel the time updates
  9156. *
  9157. * // used to update the UI
  9158. * function updateTime() {
  9159. * element.text(dateFilter(new Date(), format));
  9160. * }
  9161. *
  9162. * // watch the expression, and update the UI on change.
  9163. * scope.$watch(attrs.myCurrentTime, function(value) {
  9164. * format = value;
  9165. * updateTime();
  9166. * });
  9167. *
  9168. * stopTime = $interval(updateTime, 1000);
  9169. *
  9170. * // listen on DOM destroy (removal) event, and cancel the next UI update
  9171. * // to prevent updating time after the DOM element was removed.
  9172. * element.on('$destroy', function() {
  9173. * $interval.cancel(stopTime);
  9174. * });
  9175. * }
  9176. * }]);
  9177. * </script>
  9178. *
  9179. * <div>
  9180. * <div ng-controller="ExampleController">
  9181. * Date format: <input ng-model="format"> <hr/>
  9182. * Current time is: <span my-current-time="format"></span>
  9183. * <hr/>
  9184. * Blood 1 : <font color='red'>{{blood_1}}</font>
  9185. * Blood 2 : <font color='red'>{{blood_2}}</font>
  9186. * <button type="button" data-ng-click="fight()">Fight</button>
  9187. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  9188. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  9189. * </div>
  9190. * </div>
  9191. *
  9192. * </file>
  9193. * </example>
  9194. */
  9195. function interval(fn, delay, count, invokeApply) {
  9196. var setInterval = $window.setInterval,
  9197. clearInterval = $window.clearInterval,
  9198. iteration = 0,
  9199. skipApply = (isDefined(invokeApply) && !invokeApply),
  9200. deferred = (skipApply ? $$q : $q).defer(),
  9201. promise = deferred.promise;
  9202. count = isDefined(count) ? count : 0;
  9203. promise.then(null, null, fn);
  9204. promise.$$intervalId = setInterval(function tick() {
  9205. deferred.notify(iteration++);
  9206. if (count > 0 && iteration >= count) {
  9207. deferred.resolve(iteration);
  9208. clearInterval(promise.$$intervalId);
  9209. delete intervals[promise.$$intervalId];
  9210. }
  9211. if (!skipApply) $rootScope.$apply();
  9212. }, delay);
  9213. intervals[promise.$$intervalId] = deferred;
  9214. return promise;
  9215. }
  9216. /**
  9217. * @ngdoc method
  9218. * @name $interval#cancel
  9219. *
  9220. * @description
  9221. * Cancels a task associated with the `promise`.
  9222. *
  9223. * @param {promise} promise returned by the `$interval` function.
  9224. * @returns {boolean} Returns `true` if the task was successfully canceled.
  9225. */
  9226. interval.cancel = function(promise) {
  9227. if (promise && promise.$$intervalId in intervals) {
  9228. intervals[promise.$$intervalId].reject('canceled');
  9229. $window.clearInterval(promise.$$intervalId);
  9230. delete intervals[promise.$$intervalId];
  9231. return true;
  9232. }
  9233. return false;
  9234. };
  9235. return interval;
  9236. }];
  9237. }
  9238. /**
  9239. * @ngdoc service
  9240. * @name $locale
  9241. *
  9242. * @description
  9243. * $locale service provides localization rules for various Angular components. As of right now the
  9244. * only public api is:
  9245. *
  9246. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  9247. */
  9248. function $LocaleProvider(){
  9249. this.$get = function() {
  9250. return {
  9251. id: 'en-us',
  9252. NUMBER_FORMATS: {
  9253. DECIMAL_SEP: '.',
  9254. GROUP_SEP: ',',
  9255. PATTERNS: [
  9256. { // Decimal Pattern
  9257. minInt: 1,
  9258. minFrac: 0,
  9259. maxFrac: 3,
  9260. posPre: '',
  9261. posSuf: '',
  9262. negPre: '-',
  9263. negSuf: '',
  9264. gSize: 3,
  9265. lgSize: 3
  9266. },{ //Currency Pattern
  9267. minInt: 1,
  9268. minFrac: 2,
  9269. maxFrac: 2,
  9270. posPre: '\u00A4',
  9271. posSuf: '',
  9272. negPre: '(\u00A4',
  9273. negSuf: ')',
  9274. gSize: 3,
  9275. lgSize: 3
  9276. }
  9277. ],
  9278. CURRENCY_SYM: '$'
  9279. },
  9280. DATETIME_FORMATS: {
  9281. MONTH:
  9282. 'January,February,March,April,May,June,July,August,September,October,November,December'
  9283. .split(','),
  9284. SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
  9285. DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
  9286. SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
  9287. AMPMS: ['AM','PM'],
  9288. medium: 'MMM d, y h:mm:ss a',
  9289. short: 'M/d/yy h:mm a',
  9290. fullDate: 'EEEE, MMMM d, y',
  9291. longDate: 'MMMM d, y',
  9292. mediumDate: 'MMM d, y',
  9293. shortDate: 'M/d/yy',
  9294. mediumTime: 'h:mm:ss a',
  9295. shortTime: 'h:mm a'
  9296. },
  9297. pluralCat: function(num) {
  9298. if (num === 1) {
  9299. return 'one';
  9300. }
  9301. return 'other';
  9302. }
  9303. };
  9304. };
  9305. }
  9306. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  9307. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  9308. var $locationMinErr = minErr('$location');
  9309. /**
  9310. * Encode path using encodeUriSegment, ignoring forward slashes
  9311. *
  9312. * @param {string} path Path to encode
  9313. * @returns {string}
  9314. */
  9315. function encodePath(path) {
  9316. var segments = path.split('/'),
  9317. i = segments.length;
  9318. while (i--) {
  9319. segments[i] = encodeUriSegment(segments[i]);
  9320. }
  9321. return segments.join('/');
  9322. }
  9323. function parseAbsoluteUrl(absoluteUrl, locationObj, appBase) {
  9324. var parsedUrl = urlResolve(absoluteUrl, appBase);
  9325. locationObj.$$protocol = parsedUrl.protocol;
  9326. locationObj.$$host = parsedUrl.hostname;
  9327. locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  9328. }
  9329. function parseAppUrl(relativeUrl, locationObj, appBase) {
  9330. var prefixed = (relativeUrl.charAt(0) !== '/');
  9331. if (prefixed) {
  9332. relativeUrl = '/' + relativeUrl;
  9333. }
  9334. var match = urlResolve(relativeUrl, appBase);
  9335. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  9336. match.pathname.substring(1) : match.pathname);
  9337. locationObj.$$search = parseKeyValue(match.search);
  9338. locationObj.$$hash = decodeURIComponent(match.hash);
  9339. // make sure path starts with '/';
  9340. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  9341. locationObj.$$path = '/' + locationObj.$$path;
  9342. }
  9343. }
  9344. /**
  9345. *
  9346. * @param {string} begin
  9347. * @param {string} whole
  9348. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  9349. * expected string.
  9350. */
  9351. function beginsWith(begin, whole) {
  9352. if (whole.indexOf(begin) === 0) {
  9353. return whole.substr(begin.length);
  9354. }
  9355. }
  9356. function stripHash(url) {
  9357. var index = url.indexOf('#');
  9358. return index == -1 ? url : url.substr(0, index);
  9359. }
  9360. function stripFile(url) {
  9361. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  9362. }
  9363. /* return the server only (scheme://host:port) */
  9364. function serverBase(url) {
  9365. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  9366. }
  9367. /**
  9368. * LocationHtml5Url represents an url
  9369. * This object is exposed as $location service when HTML5 mode is enabled and supported
  9370. *
  9371. * @constructor
  9372. * @param {string} appBase application base URL
  9373. * @param {string} basePrefix url path prefix
  9374. */
  9375. function LocationHtml5Url(appBase, basePrefix) {
  9376. this.$$html5 = true;
  9377. basePrefix = basePrefix || '';
  9378. var appBaseNoFile = stripFile(appBase);
  9379. parseAbsoluteUrl(appBase, this, appBase);
  9380. /**
  9381. * Parse given html5 (regular) url string into properties
  9382. * @param {string} newAbsoluteUrl HTML5 url
  9383. * @private
  9384. */
  9385. this.$$parse = function(url) {
  9386. var pathUrl = beginsWith(appBaseNoFile, url);
  9387. if (!isString(pathUrl)) {
  9388. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  9389. appBaseNoFile);
  9390. }
  9391. parseAppUrl(pathUrl, this, appBase);
  9392. if (!this.$$path) {
  9393. this.$$path = '/';
  9394. }
  9395. this.$$compose();
  9396. };
  9397. /**
  9398. * Compose url and update `absUrl` property
  9399. * @private
  9400. */
  9401. this.$$compose = function() {
  9402. var search = toKeyValue(this.$$search),
  9403. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9404. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9405. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  9406. };
  9407. this.$$parseLinkUrl = function(url, relHref) {
  9408. if (relHref && relHref[0] === '#') {
  9409. // special case for links to hash fragments:
  9410. // keep the old url and only replace the hash fragment
  9411. this.hash(relHref.slice(1));
  9412. return true;
  9413. }
  9414. var appUrl, prevAppUrl;
  9415. var rewrittenUrl;
  9416. if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
  9417. prevAppUrl = appUrl;
  9418. if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
  9419. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  9420. } else {
  9421. rewrittenUrl = appBase + prevAppUrl;
  9422. }
  9423. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
  9424. rewrittenUrl = appBaseNoFile + appUrl;
  9425. } else if (appBaseNoFile == url + '/') {
  9426. rewrittenUrl = appBaseNoFile;
  9427. }
  9428. if (rewrittenUrl) {
  9429. this.$$parse(rewrittenUrl);
  9430. }
  9431. return !!rewrittenUrl;
  9432. };
  9433. }
  9434. /**
  9435. * LocationHashbangUrl represents url
  9436. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  9437. * It also serves as the base class for html5 mode fallback on legacy browsers.
  9438. *
  9439. * @constructor
  9440. * @param {string} appBase application base URL
  9441. * @param {string} hashPrefix hashbang prefix
  9442. */
  9443. function LocationHashbangUrl(appBase, hashPrefix) {
  9444. var appBaseNoFile = stripFile(appBase);
  9445. parseAbsoluteUrl(appBase, this, appBase);
  9446. /**
  9447. * Parse given hashbang url into properties
  9448. * @param {string} url Hashbang url
  9449. * @private
  9450. */
  9451. this.$$parse = function(url) {
  9452. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  9453. var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
  9454. ? beginsWith(hashPrefix, withoutBaseUrl)
  9455. : (this.$$html5)
  9456. ? withoutBaseUrl
  9457. : '';
  9458. if (!isString(withoutHashUrl)) {
  9459. throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
  9460. hashPrefix);
  9461. }
  9462. parseAppUrl(withoutHashUrl, this, appBase);
  9463. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  9464. this.$$compose();
  9465. /*
  9466. * In Windows, on an anchor node on documents loaded from
  9467. * the filesystem, the browser will return a pathname
  9468. * prefixed with the drive name ('/C:/path') when a
  9469. * pathname without a drive is set:
  9470. * * a.setAttribute('href', '/foo')
  9471. * * a.pathname === '/C:/foo' //true
  9472. *
  9473. * Inside of Angular, we're always using pathnames that
  9474. * do not include drive names for routing.
  9475. */
  9476. function removeWindowsDriveName (path, url, base) {
  9477. /*
  9478. Matches paths for file protocol on windows,
  9479. such as /C:/foo/bar, and captures only /foo/bar.
  9480. */
  9481. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  9482. var firstPathSegmentMatch;
  9483. //Get the relative path from the input URL.
  9484. if (url.indexOf(base) === 0) {
  9485. url = url.replace(base, '');
  9486. }
  9487. // The input URL intentionally contains a first path segment that ends with a colon.
  9488. if (windowsFilePathExp.exec(url)) {
  9489. return path;
  9490. }
  9491. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  9492. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  9493. }
  9494. };
  9495. /**
  9496. * Compose hashbang url and update `absUrl` property
  9497. * @private
  9498. */
  9499. this.$$compose = function() {
  9500. var search = toKeyValue(this.$$search),
  9501. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9502. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9503. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  9504. };
  9505. this.$$parseLinkUrl = function(url, relHref) {
  9506. if(stripHash(appBase) == stripHash(url)) {
  9507. this.$$parse(url);
  9508. return true;
  9509. }
  9510. return false;
  9511. };
  9512. }
  9513. /**
  9514. * LocationHashbangUrl represents url
  9515. * This object is exposed as $location service when html5 history api is enabled but the browser
  9516. * does not support it.
  9517. *
  9518. * @constructor
  9519. * @param {string} appBase application base URL
  9520. * @param {string} hashPrefix hashbang prefix
  9521. */
  9522. function LocationHashbangInHtml5Url(appBase, hashPrefix) {
  9523. this.$$html5 = true;
  9524. LocationHashbangUrl.apply(this, arguments);
  9525. var appBaseNoFile = stripFile(appBase);
  9526. this.$$parseLinkUrl = function(url, relHref) {
  9527. if (relHref && relHref[0] === '#') {
  9528. // special case for links to hash fragments:
  9529. // keep the old url and only replace the hash fragment
  9530. this.hash(relHref.slice(1));
  9531. return true;
  9532. }
  9533. var rewrittenUrl;
  9534. var appUrl;
  9535. if ( appBase == stripHash(url) ) {
  9536. rewrittenUrl = url;
  9537. } else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
  9538. rewrittenUrl = appBase + hashPrefix + appUrl;
  9539. } else if ( appBaseNoFile === url + '/') {
  9540. rewrittenUrl = appBaseNoFile;
  9541. }
  9542. if (rewrittenUrl) {
  9543. this.$$parse(rewrittenUrl);
  9544. }
  9545. return !!rewrittenUrl;
  9546. };
  9547. this.$$compose = function() {
  9548. var search = toKeyValue(this.$$search),
  9549. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  9550. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  9551. // include hashPrefix in $$absUrl when $$url is empty so IE8 & 9 do not reload page because of removal of '#'
  9552. this.$$absUrl = appBase + hashPrefix + this.$$url;
  9553. };
  9554. }
  9555. var locationPrototype = {
  9556. /**
  9557. * Are we in html5 mode?
  9558. * @private
  9559. */
  9560. $$html5: false,
  9561. /**
  9562. * Has any change been replacing?
  9563. * @private
  9564. */
  9565. $$replace: false,
  9566. /**
  9567. * @ngdoc method
  9568. * @name $location#absUrl
  9569. *
  9570. * @description
  9571. * This method is getter only.
  9572. *
  9573. * Return full url representation with all segments encoded according to rules specified in
  9574. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  9575. *
  9576. * @return {string} full url
  9577. */
  9578. absUrl: locationGetter('$$absUrl'),
  9579. /**
  9580. * @ngdoc method
  9581. * @name $location#url
  9582. *
  9583. * @description
  9584. * This method is getter / setter.
  9585. *
  9586. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  9587. *
  9588. * Change path, search and hash, when called with parameter and return `$location`.
  9589. *
  9590. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  9591. * @return {string} url
  9592. */
  9593. url: function(url) {
  9594. if (isUndefined(url))
  9595. return this.$$url;
  9596. var match = PATH_MATCH.exec(url);
  9597. if (match[1]) this.path(decodeURIComponent(match[1]));
  9598. if (match[2] || match[1]) this.search(match[3] || '');
  9599. this.hash(match[5] || '');
  9600. return this;
  9601. },
  9602. /**
  9603. * @ngdoc method
  9604. * @name $location#protocol
  9605. *
  9606. * @description
  9607. * This method is getter only.
  9608. *
  9609. * Return protocol of current url.
  9610. *
  9611. * @return {string} protocol of current url
  9612. */
  9613. protocol: locationGetter('$$protocol'),
  9614. /**
  9615. * @ngdoc method
  9616. * @name $location#host
  9617. *
  9618. * @description
  9619. * This method is getter only.
  9620. *
  9621. * Return host of current url.
  9622. *
  9623. * @return {string} host of current url.
  9624. */
  9625. host: locationGetter('$$host'),
  9626. /**
  9627. * @ngdoc method
  9628. * @name $location#port
  9629. *
  9630. * @description
  9631. * This method is getter only.
  9632. *
  9633. * Return port of current url.
  9634. *
  9635. * @return {Number} port
  9636. */
  9637. port: locationGetter('$$port'),
  9638. /**
  9639. * @ngdoc method
  9640. * @name $location#path
  9641. *
  9642. * @description
  9643. * This method is getter / setter.
  9644. *
  9645. * Return path of current url when called without any parameter.
  9646. *
  9647. * Change path when called with parameter and return `$location`.
  9648. *
  9649. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  9650. * if it is missing.
  9651. *
  9652. * @param {(string|number)=} path New path
  9653. * @return {string} path
  9654. */
  9655. path: locationGetterSetter('$$path', function(path) {
  9656. path = path !== null ? path.toString() : '';
  9657. return path.charAt(0) == '/' ? path : '/' + path;
  9658. }),
  9659. /**
  9660. * @ngdoc method
  9661. * @name $location#search
  9662. *
  9663. * @description
  9664. * This method is getter / setter.
  9665. *
  9666. * Return search part (as object) of current url when called without any parameter.
  9667. *
  9668. * Change search part when called with parameter and return `$location`.
  9669. *
  9670. *
  9671. * ```js
  9672. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  9673. * var searchObject = $location.search();
  9674. * // => {foo: 'bar', baz: 'xoxo'}
  9675. *
  9676. *
  9677. * // set foo to 'yipee'
  9678. * $location.search('foo', 'yipee');
  9679. * // => $location
  9680. * ```
  9681. *
  9682. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  9683. * hash object.
  9684. *
  9685. * When called with a single argument the method acts as a setter, setting the `search` component
  9686. * of `$location` to the specified value.
  9687. *
  9688. * If the argument is a hash object containing an array of values, these values will be encoded
  9689. * as duplicate search parameters in the url.
  9690. *
  9691. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  9692. * will override only a single search property.
  9693. *
  9694. * If `paramValue` is an array, it will override the property of the `search` component of
  9695. * `$location` specified via the first argument.
  9696. *
  9697. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  9698. *
  9699. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  9700. * value nor trailing equal sign.
  9701. *
  9702. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  9703. * one or more arguments returns `$location` object itself.
  9704. */
  9705. search: function(search, paramValue) {
  9706. switch (arguments.length) {
  9707. case 0:
  9708. return this.$$search;
  9709. case 1:
  9710. if (isString(search) || isNumber(search)) {
  9711. search = search.toString();
  9712. this.$$search = parseKeyValue(search);
  9713. } else if (isObject(search)) {
  9714. search = copy(search, {});
  9715. // remove object undefined or null properties
  9716. forEach(search, function(value, key) {
  9717. if (value == null) delete search[key];
  9718. });
  9719. this.$$search = search;
  9720. } else {
  9721. throw $locationMinErr('isrcharg',
  9722. 'The first argument of the `$location#search()` call must be a string or an object.');
  9723. }
  9724. break;
  9725. default:
  9726. if (isUndefined(paramValue) || paramValue === null) {
  9727. delete this.$$search[search];
  9728. } else {
  9729. this.$$search[search] = paramValue;
  9730. }
  9731. }
  9732. this.$$compose();
  9733. return this;
  9734. },
  9735. /**
  9736. * @ngdoc method
  9737. * @name $location#hash
  9738. *
  9739. * @description
  9740. * This method is getter / setter.
  9741. *
  9742. * Return hash fragment when called without any parameter.
  9743. *
  9744. * Change hash fragment when called with parameter and return `$location`.
  9745. *
  9746. * @param {(string|number)=} hash New hash fragment
  9747. * @return {string} hash
  9748. */
  9749. hash: locationGetterSetter('$$hash', function(hash) {
  9750. return hash !== null ? hash.toString() : '';
  9751. }),
  9752. /**
  9753. * @ngdoc method
  9754. * @name $location#replace
  9755. *
  9756. * @description
  9757. * If called, all changes to $location during current `$digest` will be replacing current history
  9758. * record, instead of adding new one.
  9759. */
  9760. replace: function() {
  9761. this.$$replace = true;
  9762. return this;
  9763. }
  9764. };
  9765. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function (Location) {
  9766. Location.prototype = Object.create(locationPrototype);
  9767. /**
  9768. * @ngdoc method
  9769. * @name $location#state
  9770. *
  9771. * @description
  9772. * This method is getter / setter.
  9773. *
  9774. * Return the history state object when called without any parameter.
  9775. *
  9776. * Change the history state object when called with one parameter and return `$location`.
  9777. * The state object is later passed to `pushState` or `replaceState`.
  9778. *
  9779. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  9780. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  9781. * older browsers (like IE9 or Android < 4.0), don't use this method.
  9782. *
  9783. * @param {object=} state State object for pushState or replaceState
  9784. * @return {object} state
  9785. */
  9786. Location.prototype.state = function(state) {
  9787. if (!arguments.length)
  9788. return this.$$state;
  9789. if (Location !== LocationHtml5Url || !this.$$html5) {
  9790. throw $locationMinErr('nostate', 'History API state support is available only ' +
  9791. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  9792. }
  9793. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  9794. // but we're changing the $$state reference to $browser.state() during the $digest
  9795. // so the modification window is narrow.
  9796. this.$$state = isUndefined(state) ? null : state;
  9797. return this;
  9798. };
  9799. });
  9800. function locationGetter(property) {
  9801. return function() {
  9802. return this[property];
  9803. };
  9804. }
  9805. function locationGetterSetter(property, preprocess) {
  9806. return function(value) {
  9807. if (isUndefined(value))
  9808. return this[property];
  9809. this[property] = preprocess(value);
  9810. this.$$compose();
  9811. return this;
  9812. };
  9813. }
  9814. /**
  9815. * @ngdoc service
  9816. * @name $location
  9817. *
  9818. * @requires $rootElement
  9819. *
  9820. * @description
  9821. * The $location service parses the URL in the browser address bar (based on the
  9822. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  9823. * available to your application. Changes to the URL in the address bar are reflected into
  9824. * $location service and changes to $location are reflected into the browser address bar.
  9825. *
  9826. * **The $location service:**
  9827. *
  9828. * - Exposes the current URL in the browser address bar, so you can
  9829. * - Watch and observe the URL.
  9830. * - Change the URL.
  9831. * - Synchronizes the URL with the browser when the user
  9832. * - Changes the address bar.
  9833. * - Clicks the back or forward button (or clicks a History link).
  9834. * - Clicks on a link.
  9835. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  9836. *
  9837. * For more information see {@link guide/$location Developer Guide: Using $location}
  9838. */
  9839. /**
  9840. * @ngdoc provider
  9841. * @name $locationProvider
  9842. * @description
  9843. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  9844. */
  9845. function $LocationProvider(){
  9846. var hashPrefix = '',
  9847. html5Mode = {
  9848. enabled: false,
  9849. requireBase: true,
  9850. rewriteLinks: true
  9851. };
  9852. /**
  9853. * @ngdoc method
  9854. * @name $locationProvider#hashPrefix
  9855. * @description
  9856. * @param {string=} prefix Prefix for hash part (containing path and search)
  9857. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  9858. */
  9859. this.hashPrefix = function(prefix) {
  9860. if (isDefined(prefix)) {
  9861. hashPrefix = prefix;
  9862. return this;
  9863. } else {
  9864. return hashPrefix;
  9865. }
  9866. };
  9867. /**
  9868. * @ngdoc method
  9869. * @name $locationProvider#html5Mode
  9870. * @description
  9871. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  9872. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  9873. * properties:
  9874. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  9875. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  9876. * support `pushState`.
  9877. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  9878. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  9879. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  9880. * See the {@link guide/$location $location guide for more information}
  9881. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  9882. * enables/disables url rewriting for relative links.
  9883. *
  9884. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  9885. */
  9886. this.html5Mode = function(mode) {
  9887. if (isBoolean(mode)) {
  9888. html5Mode.enabled = mode;
  9889. return this;
  9890. } else if (isObject(mode)) {
  9891. if (isBoolean(mode.enabled)) {
  9892. html5Mode.enabled = mode.enabled;
  9893. }
  9894. if (isBoolean(mode.requireBase)) {
  9895. html5Mode.requireBase = mode.requireBase;
  9896. }
  9897. if (isBoolean(mode.rewriteLinks)) {
  9898. html5Mode.rewriteLinks = mode.rewriteLinks;
  9899. }
  9900. return this;
  9901. } else {
  9902. return html5Mode;
  9903. }
  9904. };
  9905. /**
  9906. * @ngdoc event
  9907. * @name $location#$locationChangeStart
  9908. * @eventType broadcast on root scope
  9909. * @description
  9910. * Broadcasted before a URL will change.
  9911. *
  9912. * This change can be prevented by calling
  9913. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  9914. * details about event object. Upon successful change
  9915. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  9916. *
  9917. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  9918. * the browser supports the HTML5 History API.
  9919. *
  9920. * @param {Object} angularEvent Synthetic event object.
  9921. * @param {string} newUrl New URL
  9922. * @param {string=} oldUrl URL that was before it was changed.
  9923. * @param {string=} newState New history state object
  9924. * @param {string=} oldState History state object that was before it was changed.
  9925. */
  9926. /**
  9927. * @ngdoc event
  9928. * @name $location#$locationChangeSuccess
  9929. * @eventType broadcast on root scope
  9930. * @description
  9931. * Broadcasted after a URL was changed.
  9932. *
  9933. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  9934. * the browser supports the HTML5 History API.
  9935. *
  9936. * @param {Object} angularEvent Synthetic event object.
  9937. * @param {string} newUrl New URL
  9938. * @param {string=} oldUrl URL that was before it was changed.
  9939. * @param {string=} newState New history state object
  9940. * @param {string=} oldState History state object that was before it was changed.
  9941. */
  9942. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
  9943. function( $rootScope, $browser, $sniffer, $rootElement) {
  9944. var $location,
  9945. LocationMode,
  9946. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  9947. initialUrl = $browser.url(),
  9948. appBase;
  9949. if (html5Mode.enabled) {
  9950. if (!baseHref && html5Mode.requireBase) {
  9951. throw $locationMinErr('nobase',
  9952. "$location in HTML5 mode requires a <base> tag to be present!");
  9953. }
  9954. appBase = serverBase(initialUrl) + (baseHref || '/');
  9955. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  9956. } else {
  9957. appBase = stripHash(initialUrl);
  9958. LocationMode = LocationHashbangUrl;
  9959. }
  9960. $location = new LocationMode(appBase, '#' + hashPrefix);
  9961. $location.$$parseLinkUrl(initialUrl, initialUrl);
  9962. $location.$$state = $browser.state();
  9963. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  9964. function setBrowserUrlWithFallback(url, replace, state) {
  9965. var oldUrl = $location.url();
  9966. var oldState = $location.$$state;
  9967. try {
  9968. $browser.url(url, replace, state);
  9969. // Make sure $location.state() returns referentially identical (not just deeply equal)
  9970. // state object; this makes possible quick checking if the state changed in the digest
  9971. // loop. Checking deep equality would be too expensive.
  9972. $location.$$state = $browser.state();
  9973. } catch (e) {
  9974. // Restore old values if pushState fails
  9975. $location.url(oldUrl);
  9976. $location.$$state = oldState;
  9977. throw e;
  9978. }
  9979. }
  9980. $rootElement.on('click', function(event) {
  9981. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  9982. // currently we open nice url link and redirect then
  9983. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.which == 2) return;
  9984. var elm = jqLite(event.target);
  9985. // traverse the DOM up to find first A tag
  9986. while (nodeName_(elm[0]) !== 'a') {
  9987. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  9988. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  9989. }
  9990. var absHref = elm.prop('href');
  9991. // get the actual href attribute - see
  9992. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  9993. var relHref = elm.attr('href') || elm.attr('xlink:href');
  9994. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  9995. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  9996. // an animation.
  9997. absHref = urlResolve(absHref.animVal).href;
  9998. }
  9999. // Ignore when url is started with javascript: or mailto:
  10000. if (IGNORE_URI_REGEXP.test(absHref)) return;
  10001. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  10002. if ($location.$$parseLinkUrl(absHref, relHref)) {
  10003. // We do a preventDefault for all urls that are part of the angular application,
  10004. // in html5mode and also without, so that we are able to abort navigation without
  10005. // getting double entries in the location history.
  10006. event.preventDefault();
  10007. // update location manually
  10008. if ($location.absUrl() != $browser.url()) {
  10009. $rootScope.$apply();
  10010. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  10011. window.angular['ff-684208-preventDefault'] = true;
  10012. }
  10013. }
  10014. }
  10015. });
  10016. // rewrite hashbang url <> html5 url
  10017. if ($location.absUrl() != initialUrl) {
  10018. $browser.url($location.absUrl(), true);
  10019. }
  10020. var initializing = true;
  10021. // update $location when $browser url changes
  10022. $browser.onUrlChange(function(newUrl, newState) {
  10023. $rootScope.$evalAsync(function() {
  10024. var oldUrl = $location.absUrl();
  10025. var oldState = $location.$$state;
  10026. $location.$$parse(newUrl);
  10027. $location.$$state = newState;
  10028. if ($rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  10029. newState, oldState).defaultPrevented) {
  10030. $location.$$parse(oldUrl);
  10031. $location.$$state = oldState;
  10032. setBrowserUrlWithFallback(oldUrl, false, oldState);
  10033. } else {
  10034. initializing = false;
  10035. afterLocationChange(oldUrl, oldState);
  10036. }
  10037. });
  10038. if (!$rootScope.$$phase) $rootScope.$digest();
  10039. });
  10040. // update browser
  10041. $rootScope.$watch(function $locationWatch() {
  10042. var oldUrl = $browser.url();
  10043. var oldState = $browser.state();
  10044. var currentReplace = $location.$$replace;
  10045. var urlOrStateChanged = oldUrl !== $location.absUrl() ||
  10046. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  10047. if (initializing || urlOrStateChanged) {
  10048. initializing = false;
  10049. $rootScope.$evalAsync(function() {
  10050. if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl,
  10051. $location.$$state, oldState).defaultPrevented) {
  10052. $location.$$parse(oldUrl);
  10053. $location.$$state = oldState;
  10054. } else {
  10055. if (urlOrStateChanged) {
  10056. setBrowserUrlWithFallback($location.absUrl(), currentReplace,
  10057. oldState === $location.$$state ? null : $location.$$state);
  10058. }
  10059. afterLocationChange(oldUrl, oldState);
  10060. }
  10061. });
  10062. }
  10063. $location.$$replace = false;
  10064. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  10065. // there is a change
  10066. });
  10067. return $location;
  10068. function afterLocationChange(oldUrl, oldState) {
  10069. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  10070. $location.$$state, oldState);
  10071. }
  10072. }];
  10073. }
  10074. /**
  10075. * @ngdoc service
  10076. * @name $log
  10077. * @requires $window
  10078. *
  10079. * @description
  10080. * Simple service for logging. Default implementation safely writes the message
  10081. * into the browser's console (if present).
  10082. *
  10083. * The main purpose of this service is to simplify debugging and troubleshooting.
  10084. *
  10085. * The default is to log `debug` messages. You can use
  10086. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  10087. *
  10088. * @example
  10089. <example module="logExample">
  10090. <file name="script.js">
  10091. angular.module('logExample', [])
  10092. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  10093. $scope.$log = $log;
  10094. $scope.message = 'Hello World!';
  10095. }]);
  10096. </file>
  10097. <file name="index.html">
  10098. <div ng-controller="LogController">
  10099. <p>Reload this page with open console, enter text and hit the log button...</p>
  10100. Message:
  10101. <input type="text" ng-model="message"/>
  10102. <button ng-click="$log.log(message)">log</button>
  10103. <button ng-click="$log.warn(message)">warn</button>
  10104. <button ng-click="$log.info(message)">info</button>
  10105. <button ng-click="$log.error(message)">error</button>
  10106. </div>
  10107. </file>
  10108. </example>
  10109. */
  10110. /**
  10111. * @ngdoc provider
  10112. * @name $logProvider
  10113. * @description
  10114. * Use the `$logProvider` to configure how the application logs messages
  10115. */
  10116. function $LogProvider(){
  10117. var debug = true,
  10118. self = this;
  10119. /**
  10120. * @ngdoc method
  10121. * @name $logProvider#debugEnabled
  10122. * @description
  10123. * @param {boolean=} flag enable or disable debug level messages
  10124. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10125. */
  10126. this.debugEnabled = function(flag) {
  10127. if (isDefined(flag)) {
  10128. debug = flag;
  10129. return this;
  10130. } else {
  10131. return debug;
  10132. }
  10133. };
  10134. this.$get = ['$window', function($window){
  10135. return {
  10136. /**
  10137. * @ngdoc method
  10138. * @name $log#log
  10139. *
  10140. * @description
  10141. * Write a log message
  10142. */
  10143. log: consoleLog('log'),
  10144. /**
  10145. * @ngdoc method
  10146. * @name $log#info
  10147. *
  10148. * @description
  10149. * Write an information message
  10150. */
  10151. info: consoleLog('info'),
  10152. /**
  10153. * @ngdoc method
  10154. * @name $log#warn
  10155. *
  10156. * @description
  10157. * Write a warning message
  10158. */
  10159. warn: consoleLog('warn'),
  10160. /**
  10161. * @ngdoc method
  10162. * @name $log#error
  10163. *
  10164. * @description
  10165. * Write an error message
  10166. */
  10167. error: consoleLog('error'),
  10168. /**
  10169. * @ngdoc method
  10170. * @name $log#debug
  10171. *
  10172. * @description
  10173. * Write a debug message
  10174. */
  10175. debug: (function () {
  10176. var fn = consoleLog('debug');
  10177. return function() {
  10178. if (debug) {
  10179. fn.apply(self, arguments);
  10180. }
  10181. };
  10182. }())
  10183. };
  10184. function formatError(arg) {
  10185. if (arg instanceof Error) {
  10186. if (arg.stack) {
  10187. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  10188. ? 'Error: ' + arg.message + '\n' + arg.stack
  10189. : arg.stack;
  10190. } else if (arg.sourceURL) {
  10191. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  10192. }
  10193. }
  10194. return arg;
  10195. }
  10196. function consoleLog(type) {
  10197. var console = $window.console || {},
  10198. logFn = console[type] || console.log || noop,
  10199. hasApply = false;
  10200. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  10201. // The reason behind this is that console.log has type "object" in IE8...
  10202. try {
  10203. hasApply = !!logFn.apply;
  10204. } catch (e) {}
  10205. if (hasApply) {
  10206. return function() {
  10207. var args = [];
  10208. forEach(arguments, function(arg) {
  10209. args.push(formatError(arg));
  10210. });
  10211. return logFn.apply(console, args);
  10212. };
  10213. }
  10214. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  10215. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  10216. return function(arg1, arg2) {
  10217. logFn(arg1, arg2 == null ? '' : arg2);
  10218. };
  10219. }
  10220. }];
  10221. }
  10222. var $parseMinErr = minErr('$parse');
  10223. // Sandboxing Angular Expressions
  10224. // ------------------------------
  10225. // Angular expressions are generally considered safe because these expressions only have direct
  10226. // access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
  10227. // obtaining a reference to native JS functions such as the Function constructor.
  10228. //
  10229. // As an example, consider the following Angular expression:
  10230. //
  10231. // {}.toString.constructor('alert("evil JS code")')
  10232. //
  10233. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  10234. // against the expression language, but not to prevent exploits that were enabled by exposing
  10235. // sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
  10236. // practice and therefore we are not even trying to protect against interaction with an object
  10237. // explicitly exposed in this way.
  10238. //
  10239. // In general, it is not possible to access a Window object from an angular expression unless a
  10240. // window or some DOM object that has a reference to window is published onto a Scope.
  10241. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  10242. // native objects.
  10243. function ensureSafeMemberName(name, fullExpression) {
  10244. if (name === "__defineGetter__" || name === "__defineSetter__"
  10245. || name === "__lookupGetter__" || name === "__lookupSetter__"
  10246. || name === "__proto__") {
  10247. throw $parseMinErr('isecfld',
  10248. 'Attempting to access a disallowed field in Angular expressions! '
  10249. +'Expression: {0}', fullExpression);
  10250. }
  10251. return name;
  10252. }
  10253. function ensureSafeObject(obj, fullExpression) {
  10254. // nifty check if obj is Function that is fast and works across iframes and other contexts
  10255. if (obj) {
  10256. if (obj.constructor === obj) {
  10257. throw $parseMinErr('isecfn',
  10258. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10259. fullExpression);
  10260. } else if (// isWindow(obj)
  10261. obj.window === obj) {
  10262. throw $parseMinErr('isecwindow',
  10263. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  10264. fullExpression);
  10265. } else if (// isElement(obj)
  10266. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  10267. throw $parseMinErr('isecdom',
  10268. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  10269. fullExpression);
  10270. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  10271. obj === Object) {
  10272. throw $parseMinErr('isecobj',
  10273. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  10274. fullExpression);
  10275. }
  10276. }
  10277. return obj;
  10278. }
  10279. var CALL = Function.prototype.call;
  10280. var APPLY = Function.prototype.apply;
  10281. var BIND = Function.prototype.bind;
  10282. function ensureSafeFunction(obj, fullExpression) {
  10283. if (obj) {
  10284. if (obj.constructor === obj) {
  10285. throw $parseMinErr('isecfn',
  10286. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  10287. fullExpression);
  10288. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  10289. throw $parseMinErr('isecff',
  10290. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  10291. fullExpression);
  10292. }
  10293. }
  10294. }
  10295. //Keyword constants
  10296. var CONSTANTS = createMap();
  10297. forEach({
  10298. 'null': function() { return null; },
  10299. 'true': function() { return true; },
  10300. 'false': function() { return false; },
  10301. 'undefined': function() {}
  10302. }, function(constantGetter, name) {
  10303. constantGetter.constant = constantGetter.literal = constantGetter.sharedGetter = true;
  10304. CONSTANTS[name] = constantGetter;
  10305. });
  10306. //Not quite a constant, but can be lex/parsed the same
  10307. CONSTANTS['this'] = function(self) { return self; };
  10308. CONSTANTS['this'].sharedGetter = true;
  10309. //Operators - will be wrapped by binaryFn/unaryFn/assignment/filter
  10310. var OPERATORS = extend(createMap(), {
  10311. '+':function(self, locals, a,b){
  10312. a=a(self, locals); b=b(self, locals);
  10313. if (isDefined(a)) {
  10314. if (isDefined(b)) {
  10315. return a + b;
  10316. }
  10317. return a;
  10318. }
  10319. return isDefined(b)?b:undefined;},
  10320. '-':function(self, locals, a,b){
  10321. a=a(self, locals); b=b(self, locals);
  10322. return (isDefined(a)?a:0)-(isDefined(b)?b:0);
  10323. },
  10324. '*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
  10325. '/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
  10326. '%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
  10327. '===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
  10328. '!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
  10329. '==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
  10330. '!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
  10331. '<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
  10332. '>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
  10333. '<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
  10334. '>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
  10335. '&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
  10336. '||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
  10337. '!':function(self, locals, a){return !a(self, locals);},
  10338. //Tokenized as operators but parsed as assignment/filters
  10339. '=':true,
  10340. '|':true
  10341. });
  10342. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  10343. /////////////////////////////////////////
  10344. /**
  10345. * @constructor
  10346. */
  10347. var Lexer = function (options) {
  10348. this.options = options;
  10349. };
  10350. Lexer.prototype = {
  10351. constructor: Lexer,
  10352. lex: function (text) {
  10353. this.text = text;
  10354. this.index = 0;
  10355. this.ch = undefined;
  10356. this.tokens = [];
  10357. while (this.index < this.text.length) {
  10358. this.ch = this.text.charAt(this.index);
  10359. if (this.is('"\'')) {
  10360. this.readString(this.ch);
  10361. } else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
  10362. this.readNumber();
  10363. } else if (this.isIdent(this.ch)) {
  10364. this.readIdent();
  10365. } else if (this.is('(){}[].,;:?')) {
  10366. this.tokens.push({
  10367. index: this.index,
  10368. text: this.ch
  10369. });
  10370. this.index++;
  10371. } else if (this.isWhitespace(this.ch)) {
  10372. this.index++;
  10373. } else {
  10374. var ch2 = this.ch + this.peek();
  10375. var ch3 = ch2 + this.peek(2);
  10376. var fn = OPERATORS[this.ch];
  10377. var fn2 = OPERATORS[ch2];
  10378. var fn3 = OPERATORS[ch3];
  10379. if (fn3) {
  10380. this.tokens.push({index: this.index, text: ch3, fn: fn3});
  10381. this.index += 3;
  10382. } else if (fn2) {
  10383. this.tokens.push({index: this.index, text: ch2, fn: fn2});
  10384. this.index += 2;
  10385. } else if (fn) {
  10386. this.tokens.push({
  10387. index: this.index,
  10388. text: this.ch,
  10389. fn: fn
  10390. });
  10391. this.index += 1;
  10392. } else {
  10393. this.throwError('Unexpected next character ', this.index, this.index + 1);
  10394. }
  10395. }
  10396. }
  10397. return this.tokens;
  10398. },
  10399. is: function(chars) {
  10400. return chars.indexOf(this.ch) !== -1;
  10401. },
  10402. peek: function(i) {
  10403. var num = i || 1;
  10404. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  10405. },
  10406. isNumber: function(ch) {
  10407. return ('0' <= ch && ch <= '9');
  10408. },
  10409. isWhitespace: function(ch) {
  10410. // IE treats non-breaking space as \u00A0
  10411. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  10412. ch === '\n' || ch === '\v' || ch === '\u00A0');
  10413. },
  10414. isIdent: function(ch) {
  10415. return ('a' <= ch && ch <= 'z' ||
  10416. 'A' <= ch && ch <= 'Z' ||
  10417. '_' === ch || ch === '$');
  10418. },
  10419. isExpOperator: function(ch) {
  10420. return (ch === '-' || ch === '+' || this.isNumber(ch));
  10421. },
  10422. throwError: function(error, start, end) {
  10423. end = end || this.index;
  10424. var colStr = (isDefined(start)
  10425. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  10426. : ' ' + end);
  10427. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  10428. error, colStr, this.text);
  10429. },
  10430. readNumber: function() {
  10431. var number = '';
  10432. var start = this.index;
  10433. while (this.index < this.text.length) {
  10434. var ch = lowercase(this.text.charAt(this.index));
  10435. if (ch == '.' || this.isNumber(ch)) {
  10436. number += ch;
  10437. } else {
  10438. var peekCh = this.peek();
  10439. if (ch == 'e' && this.isExpOperator(peekCh)) {
  10440. number += ch;
  10441. } else if (this.isExpOperator(ch) &&
  10442. peekCh && this.isNumber(peekCh) &&
  10443. number.charAt(number.length - 1) == 'e') {
  10444. number += ch;
  10445. } else if (this.isExpOperator(ch) &&
  10446. (!peekCh || !this.isNumber(peekCh)) &&
  10447. number.charAt(number.length - 1) == 'e') {
  10448. this.throwError('Invalid exponent');
  10449. } else {
  10450. break;
  10451. }
  10452. }
  10453. this.index++;
  10454. }
  10455. number = 1 * number;
  10456. this.tokens.push({
  10457. index: start,
  10458. text: number,
  10459. constant: true,
  10460. fn: function() { return number; }
  10461. });
  10462. },
  10463. readIdent: function() {
  10464. var expression = this.text;
  10465. var ident = '';
  10466. var start = this.index;
  10467. var lastDot, peekIndex, methodName, ch;
  10468. while (this.index < this.text.length) {
  10469. ch = this.text.charAt(this.index);
  10470. if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
  10471. if (ch === '.') lastDot = this.index;
  10472. ident += ch;
  10473. } else {
  10474. break;
  10475. }
  10476. this.index++;
  10477. }
  10478. //check if the identifier ends with . and if so move back one char
  10479. if (lastDot && ident[ident.length - 1] === '.') {
  10480. this.index--;
  10481. ident = ident.slice(0, -1);
  10482. lastDot = ident.lastIndexOf('.');
  10483. if (lastDot === -1) {
  10484. lastDot = undefined;
  10485. }
  10486. }
  10487. //check if this is not a method invocation and if it is back out to last dot
  10488. if (lastDot) {
  10489. peekIndex = this.index;
  10490. while (peekIndex < this.text.length) {
  10491. ch = this.text.charAt(peekIndex);
  10492. if (ch === '(') {
  10493. methodName = ident.substr(lastDot - start + 1);
  10494. ident = ident.substr(0, lastDot - start);
  10495. this.index = peekIndex;
  10496. break;
  10497. }
  10498. if (this.isWhitespace(ch)) {
  10499. peekIndex++;
  10500. } else {
  10501. break;
  10502. }
  10503. }
  10504. }
  10505. this.tokens.push({
  10506. index: start,
  10507. text: ident,
  10508. fn: CONSTANTS[ident] || getterFn(ident, this.options, expression)
  10509. });
  10510. if (methodName) {
  10511. this.tokens.push({
  10512. index: lastDot,
  10513. text: '.'
  10514. });
  10515. this.tokens.push({
  10516. index: lastDot + 1,
  10517. text: methodName
  10518. });
  10519. }
  10520. },
  10521. readString: function(quote) {
  10522. var start = this.index;
  10523. this.index++;
  10524. var string = '';
  10525. var rawString = quote;
  10526. var escape = false;
  10527. while (this.index < this.text.length) {
  10528. var ch = this.text.charAt(this.index);
  10529. rawString += ch;
  10530. if (escape) {
  10531. if (ch === 'u') {
  10532. var hex = this.text.substring(this.index + 1, this.index + 5);
  10533. if (!hex.match(/[\da-f]{4}/i))
  10534. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  10535. this.index += 4;
  10536. string += String.fromCharCode(parseInt(hex, 16));
  10537. } else {
  10538. var rep = ESCAPE[ch];
  10539. string = string + (rep || ch);
  10540. }
  10541. escape = false;
  10542. } else if (ch === '\\') {
  10543. escape = true;
  10544. } else if (ch === quote) {
  10545. this.index++;
  10546. this.tokens.push({
  10547. index: start,
  10548. text: rawString,
  10549. string: string,
  10550. constant: true,
  10551. fn: function() { return string; }
  10552. });
  10553. return;
  10554. } else {
  10555. string += ch;
  10556. }
  10557. this.index++;
  10558. }
  10559. this.throwError('Unterminated quote', start);
  10560. }
  10561. };
  10562. function isConstant(exp) {
  10563. return exp.constant;
  10564. }
  10565. /**
  10566. * @constructor
  10567. */
  10568. var Parser = function (lexer, $filter, options) {
  10569. this.lexer = lexer;
  10570. this.$filter = $filter;
  10571. this.options = options;
  10572. };
  10573. Parser.ZERO = extend(function () {
  10574. return 0;
  10575. }, {
  10576. sharedGetter: true,
  10577. constant: true
  10578. });
  10579. Parser.prototype = {
  10580. constructor: Parser,
  10581. parse: function (text) {
  10582. this.text = text;
  10583. this.tokens = this.lexer.lex(text);
  10584. var value = this.statements();
  10585. if (this.tokens.length !== 0) {
  10586. this.throwError('is an unexpected token', this.tokens[0]);
  10587. }
  10588. value.literal = !!value.literal;
  10589. value.constant = !!value.constant;
  10590. return value;
  10591. },
  10592. primary: function () {
  10593. var primary;
  10594. if (this.expect('(')) {
  10595. primary = this.filterChain();
  10596. this.consume(')');
  10597. } else if (this.expect('[')) {
  10598. primary = this.arrayDeclaration();
  10599. } else if (this.expect('{')) {
  10600. primary = this.object();
  10601. } else {
  10602. var token = this.expect();
  10603. primary = token.fn;
  10604. if (!primary) {
  10605. this.throwError('not a primary expression', token);
  10606. }
  10607. if (token.constant) {
  10608. primary.constant = true;
  10609. primary.literal = true;
  10610. }
  10611. }
  10612. var next, context;
  10613. while ((next = this.expect('(', '[', '.'))) {
  10614. if (next.text === '(') {
  10615. primary = this.functionCall(primary, context);
  10616. context = null;
  10617. } else if (next.text === '[') {
  10618. context = primary;
  10619. primary = this.objectIndex(primary);
  10620. } else if (next.text === '.') {
  10621. context = primary;
  10622. primary = this.fieldAccess(primary);
  10623. } else {
  10624. this.throwError('IMPOSSIBLE');
  10625. }
  10626. }
  10627. return primary;
  10628. },
  10629. throwError: function(msg, token) {
  10630. throw $parseMinErr('syntax',
  10631. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  10632. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  10633. },
  10634. peekToken: function() {
  10635. if (this.tokens.length === 0)
  10636. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  10637. return this.tokens[0];
  10638. },
  10639. peek: function(e1, e2, e3, e4) {
  10640. if (this.tokens.length > 0) {
  10641. var token = this.tokens[0];
  10642. var t = token.text;
  10643. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  10644. (!e1 && !e2 && !e3 && !e4)) {
  10645. return token;
  10646. }
  10647. }
  10648. return false;
  10649. },
  10650. expect: function(e1, e2, e3, e4){
  10651. var token = this.peek(e1, e2, e3, e4);
  10652. if (token) {
  10653. this.tokens.shift();
  10654. return token;
  10655. }
  10656. return false;
  10657. },
  10658. consume: function(e1){
  10659. if (!this.expect(e1)) {
  10660. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  10661. }
  10662. },
  10663. unaryFn: function(fn, right) {
  10664. return extend(function $parseUnaryFn(self, locals) {
  10665. return fn(self, locals, right);
  10666. }, {
  10667. constant:right.constant,
  10668. inputs: [right]
  10669. });
  10670. },
  10671. binaryFn: function(left, fn, right, isBranching) {
  10672. return extend(function $parseBinaryFn(self, locals) {
  10673. return fn(self, locals, left, right);
  10674. }, {
  10675. constant: left.constant && right.constant,
  10676. inputs: !isBranching && [left, right]
  10677. });
  10678. },
  10679. statements: function() {
  10680. var statements = [];
  10681. while (true) {
  10682. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  10683. statements.push(this.filterChain());
  10684. if (!this.expect(';')) {
  10685. // optimize for the common case where there is only one statement.
  10686. // TODO(size): maybe we should not support multiple statements?
  10687. return (statements.length === 1)
  10688. ? statements[0]
  10689. : function $parseStatements(self, locals) {
  10690. var value;
  10691. for (var i = 0, ii = statements.length; i < ii; i++) {
  10692. value = statements[i](self, locals);
  10693. }
  10694. return value;
  10695. };
  10696. }
  10697. }
  10698. },
  10699. filterChain: function() {
  10700. var left = this.expression();
  10701. var token;
  10702. while ((token = this.expect('|'))) {
  10703. left = this.filter(left);
  10704. }
  10705. return left;
  10706. },
  10707. filter: function(inputFn) {
  10708. var token = this.expect();
  10709. var fn = this.$filter(token.text);
  10710. var argsFn;
  10711. var args;
  10712. if (this.peek(':')) {
  10713. argsFn = [];
  10714. args = []; // we can safely reuse the array
  10715. while (this.expect(':')) {
  10716. argsFn.push(this.expression());
  10717. }
  10718. }
  10719. var inputs = [inputFn].concat(argsFn || []);
  10720. return extend(function $parseFilter(self, locals) {
  10721. var input = inputFn(self, locals);
  10722. if (args) {
  10723. args[0] = input;
  10724. var i = argsFn.length;
  10725. while (i--) {
  10726. args[i + 1] = argsFn[i](self, locals);
  10727. }
  10728. return fn.apply(undefined, args);
  10729. }
  10730. return fn(input);
  10731. }, {
  10732. constant: !fn.$stateful && inputs.every(isConstant),
  10733. inputs: !fn.$stateful && inputs
  10734. });
  10735. },
  10736. expression: function() {
  10737. return this.assignment();
  10738. },
  10739. assignment: function() {
  10740. var left = this.ternary();
  10741. var right;
  10742. var token;
  10743. if ((token = this.expect('='))) {
  10744. if (!left.assign) {
  10745. this.throwError('implies assignment but [' +
  10746. this.text.substring(0, token.index) + '] can not be assigned to', token);
  10747. }
  10748. right = this.ternary();
  10749. return extend(function $parseAssignment(scope, locals) {
  10750. return left.assign(scope, right(scope, locals), locals);
  10751. }, {
  10752. inputs: [left, right]
  10753. });
  10754. }
  10755. return left;
  10756. },
  10757. ternary: function() {
  10758. var left = this.logicalOR();
  10759. var middle;
  10760. var token;
  10761. if ((token = this.expect('?'))) {
  10762. middle = this.assignment();
  10763. if ((token = this.expect(':'))) {
  10764. var right = this.assignment();
  10765. return extend(function $parseTernary(self, locals){
  10766. return left(self, locals) ? middle(self, locals) : right(self, locals);
  10767. }, {
  10768. constant: left.constant && middle.constant && right.constant
  10769. });
  10770. } else {
  10771. this.throwError('expected :', token);
  10772. }
  10773. }
  10774. return left;
  10775. },
  10776. logicalOR: function() {
  10777. var left = this.logicalAND();
  10778. var token;
  10779. while ((token = this.expect('||'))) {
  10780. left = this.binaryFn(left, token.fn, this.logicalAND(), true);
  10781. }
  10782. return left;
  10783. },
  10784. logicalAND: function() {
  10785. var left = this.equality();
  10786. var token;
  10787. if ((token = this.expect('&&'))) {
  10788. left = this.binaryFn(left, token.fn, this.logicalAND(), true);
  10789. }
  10790. return left;
  10791. },
  10792. equality: function() {
  10793. var left = this.relational();
  10794. var token;
  10795. if ((token = this.expect('==','!=','===','!=='))) {
  10796. left = this.binaryFn(left, token.fn, this.equality());
  10797. }
  10798. return left;
  10799. },
  10800. relational: function() {
  10801. var left = this.additive();
  10802. var token;
  10803. if ((token = this.expect('<', '>', '<=', '>='))) {
  10804. left = this.binaryFn(left, token.fn, this.relational());
  10805. }
  10806. return left;
  10807. },
  10808. additive: function() {
  10809. var left = this.multiplicative();
  10810. var token;
  10811. while ((token = this.expect('+','-'))) {
  10812. left = this.binaryFn(left, token.fn, this.multiplicative());
  10813. }
  10814. return left;
  10815. },
  10816. multiplicative: function() {
  10817. var left = this.unary();
  10818. var token;
  10819. while ((token = this.expect('*','/','%'))) {
  10820. left = this.binaryFn(left, token.fn, this.unary());
  10821. }
  10822. return left;
  10823. },
  10824. unary: function() {
  10825. var token;
  10826. if (this.expect('+')) {
  10827. return this.primary();
  10828. } else if ((token = this.expect('-'))) {
  10829. return this.binaryFn(Parser.ZERO, token.fn, this.unary());
  10830. } else if ((token = this.expect('!'))) {
  10831. return this.unaryFn(token.fn, this.unary());
  10832. } else {
  10833. return this.primary();
  10834. }
  10835. },
  10836. fieldAccess: function(object) {
  10837. var expression = this.text;
  10838. var field = this.expect().text;
  10839. var getter = getterFn(field, this.options, expression);
  10840. return extend(function $parseFieldAccess(scope, locals, self) {
  10841. return getter(self || object(scope, locals));
  10842. }, {
  10843. assign: function(scope, value, locals) {
  10844. var o = object(scope, locals);
  10845. if (!o) object.assign(scope, o = {});
  10846. return setter(o, field, value, expression);
  10847. }
  10848. });
  10849. },
  10850. objectIndex: function(obj) {
  10851. var expression = this.text;
  10852. var indexFn = this.expression();
  10853. this.consume(']');
  10854. return extend(function $parseObjectIndex(self, locals) {
  10855. var o = obj(self, locals),
  10856. i = indexFn(self, locals),
  10857. v;
  10858. ensureSafeMemberName(i, expression);
  10859. if (!o) return undefined;
  10860. v = ensureSafeObject(o[i], expression);
  10861. return v;
  10862. }, {
  10863. assign: function(self, value, locals) {
  10864. var key = ensureSafeMemberName(indexFn(self, locals), expression);
  10865. // prevent overwriting of Function.constructor which would break ensureSafeObject check
  10866. var o = ensureSafeObject(obj(self, locals), expression);
  10867. if (!o) obj.assign(self, o = {});
  10868. return o[key] = value;
  10869. }
  10870. });
  10871. },
  10872. functionCall: function(fnGetter, contextGetter) {
  10873. var argsFn = [];
  10874. if (this.peekToken().text !== ')') {
  10875. do {
  10876. argsFn.push(this.expression());
  10877. } while (this.expect(','));
  10878. }
  10879. this.consume(')');
  10880. var expressionText = this.text;
  10881. // we can safely reuse the array across invocations
  10882. var args = argsFn.length ? [] : null;
  10883. return function $parseFunctionCall(scope, locals) {
  10884. var context = contextGetter ? contextGetter(scope, locals) : scope;
  10885. var fn = fnGetter(scope, locals, context) || noop;
  10886. if (args) {
  10887. var i = argsFn.length;
  10888. while (i--) {
  10889. args[i] = ensureSafeObject(argsFn[i](scope, locals), expressionText);
  10890. }
  10891. }
  10892. ensureSafeObject(context, expressionText);
  10893. ensureSafeFunction(fn, expressionText);
  10894. // IE stupidity! (IE doesn't have apply for some native functions)
  10895. var v = fn.apply
  10896. ? fn.apply(context, args)
  10897. : fn(args[0], args[1], args[2], args[3], args[4]);
  10898. return ensureSafeObject(v, expressionText);
  10899. };
  10900. },
  10901. // This is used with json array declaration
  10902. arrayDeclaration: function () {
  10903. var elementFns = [];
  10904. if (this.peekToken().text !== ']') {
  10905. do {
  10906. if (this.peek(']')) {
  10907. // Support trailing commas per ES5.1.
  10908. break;
  10909. }
  10910. var elementFn = this.expression();
  10911. elementFns.push(elementFn);
  10912. } while (this.expect(','));
  10913. }
  10914. this.consume(']');
  10915. return extend(function $parseArrayLiteral(self, locals) {
  10916. var array = [];
  10917. for (var i = 0, ii = elementFns.length; i < ii; i++) {
  10918. array.push(elementFns[i](self, locals));
  10919. }
  10920. return array;
  10921. }, {
  10922. literal: true,
  10923. constant: elementFns.every(isConstant),
  10924. inputs: elementFns
  10925. });
  10926. },
  10927. object: function () {
  10928. var keys = [], valueFns = [];
  10929. if (this.peekToken().text !== '}') {
  10930. do {
  10931. if (this.peek('}')) {
  10932. // Support trailing commas per ES5.1.
  10933. break;
  10934. }
  10935. var token = this.expect();
  10936. keys.push(token.string || token.text);
  10937. this.consume(':');
  10938. var value = this.expression();
  10939. valueFns.push(value);
  10940. } while (this.expect(','));
  10941. }
  10942. this.consume('}');
  10943. return extend(function $parseObjectLiteral(self, locals) {
  10944. var object = {};
  10945. for (var i = 0, ii = valueFns.length; i < ii; i++) {
  10946. object[keys[i]] = valueFns[i](self, locals);
  10947. }
  10948. return object;
  10949. }, {
  10950. literal: true,
  10951. constant: valueFns.every(isConstant),
  10952. inputs: valueFns
  10953. });
  10954. }
  10955. };
  10956. //////////////////////////////////////////////////
  10957. // Parser helper functions
  10958. //////////////////////////////////////////////////
  10959. function setter(obj, path, setValue, fullExp) {
  10960. ensureSafeObject(obj, fullExp);
  10961. var element = path.split('.'), key;
  10962. for (var i = 0; element.length > 1; i++) {
  10963. key = ensureSafeMemberName(element.shift(), fullExp);
  10964. var propertyObj = ensureSafeObject(obj[key], fullExp);
  10965. if (!propertyObj) {
  10966. propertyObj = {};
  10967. obj[key] = propertyObj;
  10968. }
  10969. obj = propertyObj;
  10970. }
  10971. key = ensureSafeMemberName(element.shift(), fullExp);
  10972. ensureSafeObject(obj[key], fullExp);
  10973. obj[key] = setValue;
  10974. return setValue;
  10975. }
  10976. var getterFnCache = createMap();
  10977. /**
  10978. * Implementation of the "Black Hole" variant from:
  10979. * - http://jsperf.com/angularjs-parse-getter/4
  10980. * - http://jsperf.com/path-evaluation-simplified/7
  10981. */
  10982. function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp) {
  10983. ensureSafeMemberName(key0, fullExp);
  10984. ensureSafeMemberName(key1, fullExp);
  10985. ensureSafeMemberName(key2, fullExp);
  10986. ensureSafeMemberName(key3, fullExp);
  10987. ensureSafeMemberName(key4, fullExp);
  10988. return function cspSafeGetter(scope, locals) {
  10989. var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
  10990. if (pathVal == null) return pathVal;
  10991. pathVal = pathVal[key0];
  10992. if (!key1) return pathVal;
  10993. if (pathVal == null) return undefined;
  10994. pathVal = pathVal[key1];
  10995. if (!key2) return pathVal;
  10996. if (pathVal == null) return undefined;
  10997. pathVal = pathVal[key2];
  10998. if (!key3) return pathVal;
  10999. if (pathVal == null) return undefined;
  11000. pathVal = pathVal[key3];
  11001. if (!key4) return pathVal;
  11002. if (pathVal == null) return undefined;
  11003. pathVal = pathVal[key4];
  11004. return pathVal;
  11005. };
  11006. }
  11007. function getterFn(path, options, fullExp) {
  11008. var fn = getterFnCache[path];
  11009. if (fn) return fn;
  11010. var pathKeys = path.split('.'),
  11011. pathKeysLength = pathKeys.length;
  11012. // http://jsperf.com/angularjs-parse-getter/6
  11013. if (options.csp) {
  11014. if (pathKeysLength < 6) {
  11015. fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp);
  11016. } else {
  11017. fn = function cspSafeGetter(scope, locals) {
  11018. var i = 0, val;
  11019. do {
  11020. val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
  11021. pathKeys[i++], fullExp)(scope, locals);
  11022. locals = undefined; // clear after first iteration
  11023. scope = val;
  11024. } while (i < pathKeysLength);
  11025. return val;
  11026. };
  11027. }
  11028. } else {
  11029. var code = '';
  11030. forEach(pathKeys, function(key, index) {
  11031. ensureSafeMemberName(key, fullExp);
  11032. code += 'if(s == null) return undefined;\n' +
  11033. 's='+ (index
  11034. // we simply dereference 's' on any .dot notation
  11035. ? 's'
  11036. // but if we are first then we check locals first, and if so read it first
  11037. : '((l&&l.hasOwnProperty("' + key + '"))?l:s)') + '.' + key + ';\n';
  11038. });
  11039. code += 'return s;';
  11040. /* jshint -W054 */
  11041. var evaledFnGetter = new Function('s', 'l', code); // s=scope, l=locals
  11042. /* jshint +W054 */
  11043. evaledFnGetter.toString = valueFn(code);
  11044. fn = evaledFnGetter;
  11045. }
  11046. fn.sharedGetter = true;
  11047. fn.assign = function(self, value) {
  11048. return setter(self, path, value, path);
  11049. };
  11050. getterFnCache[path] = fn;
  11051. return fn;
  11052. }
  11053. ///////////////////////////////////
  11054. /**
  11055. * @ngdoc service
  11056. * @name $parse
  11057. * @kind function
  11058. *
  11059. * @description
  11060. *
  11061. * Converts Angular {@link guide/expression expression} into a function.
  11062. *
  11063. * ```js
  11064. * var getter = $parse('user.name');
  11065. * var setter = getter.assign;
  11066. * var context = {user:{name:'angular'}};
  11067. * var locals = {user:{name:'local'}};
  11068. *
  11069. * expect(getter(context)).toEqual('angular');
  11070. * setter(context, 'newValue');
  11071. * expect(context.user.name).toEqual('newValue');
  11072. * expect(getter(context, locals)).toEqual('local');
  11073. * ```
  11074. *
  11075. *
  11076. * @param {string} expression String expression to compile.
  11077. * @returns {function(context, locals)} a function which represents the compiled expression:
  11078. *
  11079. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  11080. * are evaluated against (typically a scope object).
  11081. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  11082. * `context`.
  11083. *
  11084. * The returned function also has the following properties:
  11085. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  11086. * literal.
  11087. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  11088. * constant literals.
  11089. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  11090. * set to a function to change its value on the given context.
  11091. *
  11092. */
  11093. /**
  11094. * @ngdoc provider
  11095. * @name $parseProvider
  11096. *
  11097. * @description
  11098. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  11099. * service.
  11100. */
  11101. function $ParseProvider() {
  11102. var cache = createMap();
  11103. var $parseOptions = {
  11104. csp: false
  11105. };
  11106. this.$get = ['$filter', '$sniffer', function($filter, $sniffer) {
  11107. $parseOptions.csp = $sniffer.csp;
  11108. function wrapSharedExpression(exp) {
  11109. var wrapped = exp;
  11110. if (exp.sharedGetter) {
  11111. wrapped = function $parseWrapper(self, locals) {
  11112. return exp(self, locals);
  11113. };
  11114. wrapped.literal = exp.literal;
  11115. wrapped.constant = exp.constant;
  11116. wrapped.assign = exp.assign;
  11117. }
  11118. return wrapped;
  11119. }
  11120. return function $parse(exp, interceptorFn) {
  11121. var parsedExpression, oneTime, cacheKey;
  11122. switch (typeof exp) {
  11123. case 'string':
  11124. cacheKey = exp = exp.trim();
  11125. parsedExpression = cache[cacheKey];
  11126. if (!parsedExpression) {
  11127. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  11128. oneTime = true;
  11129. exp = exp.substring(2);
  11130. }
  11131. var lexer = new Lexer($parseOptions);
  11132. var parser = new Parser(lexer, $filter, $parseOptions);
  11133. parsedExpression = parser.parse(exp);
  11134. if (parsedExpression.constant) {
  11135. parsedExpression.$$watchDelegate = constantWatchDelegate;
  11136. } else if (oneTime) {
  11137. //oneTime is not part of the exp passed to the Parser so we may have to
  11138. //wrap the parsedExpression before adding a $$watchDelegate
  11139. parsedExpression = wrapSharedExpression(parsedExpression);
  11140. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  11141. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  11142. } else if (parsedExpression.inputs) {
  11143. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  11144. }
  11145. cache[cacheKey] = parsedExpression;
  11146. }
  11147. return addInterceptor(parsedExpression, interceptorFn);
  11148. case 'function':
  11149. return addInterceptor(exp, interceptorFn);
  11150. default:
  11151. return addInterceptor(noop, interceptorFn);
  11152. }
  11153. };
  11154. function collectExpressionInputs(inputs, list) {
  11155. for (var i = 0, ii = inputs.length; i < ii; i++) {
  11156. var input = inputs[i];
  11157. if (!input.constant) {
  11158. if (input.inputs) {
  11159. collectExpressionInputs(input.inputs, list);
  11160. } else if (list.indexOf(input) === -1) { // TODO(perf) can we do better?
  11161. list.push(input);
  11162. }
  11163. }
  11164. }
  11165. return list;
  11166. }
  11167. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  11168. if (newValue == null || oldValueOfValue == null) { // null/undefined
  11169. return newValue === oldValueOfValue;
  11170. }
  11171. if (typeof newValue === 'object') {
  11172. // attempt to convert the value to a primitive type
  11173. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  11174. // be cheaply dirty-checked
  11175. newValue = newValue.valueOf();
  11176. if (typeof newValue === 'object') {
  11177. // objects/arrays are not supported - deep-watching them would be too expensive
  11178. return false;
  11179. }
  11180. // fall-through to the primitive equality check
  11181. }
  11182. //Primitive or NaN
  11183. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  11184. }
  11185. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11186. var inputExpressions = parsedExpression.$$inputs ||
  11187. (parsedExpression.$$inputs = collectExpressionInputs(parsedExpression.inputs, []));
  11188. var lastResult;
  11189. if (inputExpressions.length === 1) {
  11190. var oldInputValue = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11191. inputExpressions = inputExpressions[0];
  11192. return scope.$watch(function expressionInputWatch(scope) {
  11193. var newInputValue = inputExpressions(scope);
  11194. if (!expressionInputDirtyCheck(newInputValue, oldInputValue)) {
  11195. lastResult = parsedExpression(scope);
  11196. oldInputValue = newInputValue && newInputValue.valueOf();
  11197. }
  11198. return lastResult;
  11199. }, listener, objectEquality);
  11200. }
  11201. var oldInputValueOfValues = [];
  11202. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11203. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  11204. }
  11205. return scope.$watch(function expressionInputsWatch(scope) {
  11206. var changed = false;
  11207. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  11208. var newInputValue = inputExpressions[i](scope);
  11209. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  11210. oldInputValueOfValues[i] = newInputValue && newInputValue.valueOf();
  11211. }
  11212. }
  11213. if (changed) {
  11214. lastResult = parsedExpression(scope);
  11215. }
  11216. return lastResult;
  11217. }, listener, objectEquality);
  11218. }
  11219. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11220. var unwatch, lastValue;
  11221. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11222. return parsedExpression(scope);
  11223. }, function oneTimeListener(value, old, scope) {
  11224. lastValue = value;
  11225. if (isFunction(listener)) {
  11226. listener.apply(this, arguments);
  11227. }
  11228. if (isDefined(value)) {
  11229. scope.$$postDigest(function () {
  11230. if (isDefined(lastValue)) {
  11231. unwatch();
  11232. }
  11233. });
  11234. }
  11235. }, objectEquality);
  11236. }
  11237. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11238. var unwatch, lastValue;
  11239. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  11240. return parsedExpression(scope);
  11241. }, function oneTimeListener(value, old, scope) {
  11242. lastValue = value;
  11243. if (isFunction(listener)) {
  11244. listener.call(this, value, old, scope);
  11245. }
  11246. if (isAllDefined(value)) {
  11247. scope.$$postDigest(function () {
  11248. if(isAllDefined(lastValue)) unwatch();
  11249. });
  11250. }
  11251. }, objectEquality);
  11252. function isAllDefined(value) {
  11253. var allDefined = true;
  11254. forEach(value, function (val) {
  11255. if (!isDefined(val)) allDefined = false;
  11256. });
  11257. return allDefined;
  11258. }
  11259. }
  11260. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  11261. var unwatch;
  11262. return unwatch = scope.$watch(function constantWatch(scope) {
  11263. return parsedExpression(scope);
  11264. }, function constantListener(value, old, scope) {
  11265. if (isFunction(listener)) {
  11266. listener.apply(this, arguments);
  11267. }
  11268. unwatch();
  11269. }, objectEquality);
  11270. }
  11271. function addInterceptor(parsedExpression, interceptorFn) {
  11272. if (!interceptorFn) return parsedExpression;
  11273. var fn = function interceptedExpression(scope, locals) {
  11274. var value = parsedExpression(scope, locals);
  11275. var result = interceptorFn(value, scope, locals);
  11276. // we only return the interceptor's result if the
  11277. // initial value is defined (for bind-once)
  11278. return isDefined(value) ? result : value;
  11279. };
  11280. // Propagate $$watchDelegates other then inputsWatchDelegate
  11281. if (parsedExpression.$$watchDelegate &&
  11282. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  11283. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  11284. } else if (!interceptorFn.$stateful) {
  11285. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  11286. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  11287. fn.$$watchDelegate = inputsWatchDelegate;
  11288. fn.inputs = [parsedExpression];
  11289. }
  11290. return fn;
  11291. }
  11292. }];
  11293. }
  11294. /**
  11295. * @ngdoc service
  11296. * @name $q
  11297. * @requires $rootScope
  11298. *
  11299. * @description
  11300. * A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
  11301. *
  11302. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  11303. * implementations, and the other which resembles ES6 promises to some degree.
  11304. *
  11305. * # $q constructor
  11306. *
  11307. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  11308. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  11309. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  11310. *
  11311. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  11312. * available yet.
  11313. *
  11314. * It can be used like so:
  11315. *
  11316. * ```js
  11317. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11318. * // are available in the current lexical scope (they could have been injected or passed in).
  11319. *
  11320. * function asyncGreet(name) {
  11321. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  11322. * return $q(function(resolve, reject) {
  11323. * setTimeout(function() {
  11324. * if (okToGreet(name)) {
  11325. * resolve('Hello, ' + name + '!');
  11326. * } else {
  11327. * reject('Greeting ' + name + ' is not allowed.');
  11328. * }
  11329. * }, 1000);
  11330. * });
  11331. * }
  11332. *
  11333. * var promise = asyncGreet('Robin Hood');
  11334. * promise.then(function(greeting) {
  11335. * alert('Success: ' + greeting);
  11336. * }, function(reason) {
  11337. * alert('Failed: ' + reason);
  11338. * });
  11339. * ```
  11340. *
  11341. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  11342. *
  11343. * However, the more traditional CommonJS-style usage is still available, and documented below.
  11344. *
  11345. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  11346. * interface for interacting with an object that represents the result of an action that is
  11347. * performed asynchronously, and may or may not be finished at any given point in time.
  11348. *
  11349. * From the perspective of dealing with error handling, deferred and promise APIs are to
  11350. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  11351. *
  11352. * ```js
  11353. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  11354. * // are available in the current lexical scope (they could have been injected or passed in).
  11355. *
  11356. * function asyncGreet(name) {
  11357. * var deferred = $q.defer();
  11358. *
  11359. * setTimeout(function() {
  11360. * deferred.notify('About to greet ' + name + '.');
  11361. *
  11362. * if (okToGreet(name)) {
  11363. * deferred.resolve('Hello, ' + name + '!');
  11364. * } else {
  11365. * deferred.reject('Greeting ' + name + ' is not allowed.');
  11366. * }
  11367. * }, 1000);
  11368. *
  11369. * return deferred.promise;
  11370. * }
  11371. *
  11372. * var promise = asyncGreet('Robin Hood');
  11373. * promise.then(function(greeting) {
  11374. * alert('Success: ' + greeting);
  11375. * }, function(reason) {
  11376. * alert('Failed: ' + reason);
  11377. * }, function(update) {
  11378. * alert('Got notification: ' + update);
  11379. * });
  11380. * ```
  11381. *
  11382. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  11383. * comes in the way of guarantees that promise and deferred APIs make, see
  11384. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  11385. *
  11386. * Additionally the promise api allows for composition that is very hard to do with the
  11387. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  11388. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  11389. * section on serial or parallel joining of promises.
  11390. *
  11391. * # The Deferred API
  11392. *
  11393. * A new instance of deferred is constructed by calling `$q.defer()`.
  11394. *
  11395. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  11396. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  11397. * of the task.
  11398. *
  11399. * **Methods**
  11400. *
  11401. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  11402. * constructed via `$q.reject`, the promise will be rejected instead.
  11403. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  11404. * resolving it with a rejection constructed via `$q.reject`.
  11405. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  11406. * multiple times before the promise is either resolved or rejected.
  11407. *
  11408. * **Properties**
  11409. *
  11410. * - promise – `{Promise}` – promise object associated with this deferred.
  11411. *
  11412. *
  11413. * # The Promise API
  11414. *
  11415. * A new promise instance is created when a deferred instance is created and can be retrieved by
  11416. * calling `deferred.promise`.
  11417. *
  11418. * The purpose of the promise object is to allow for interested parties to get access to the result
  11419. * of the deferred task when it completes.
  11420. *
  11421. * **Methods**
  11422. *
  11423. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  11424. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  11425. * as soon as the result is available. The callbacks are called with a single argument: the result
  11426. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  11427. * provide a progress indication, before the promise is resolved or rejected.
  11428. *
  11429. * This method *returns a new promise* which is resolved or rejected via the return value of the
  11430. * `successCallback`, `errorCallback`. It also notifies via the return value of the
  11431. * `notifyCallback` method. The promise cannot be resolved or rejected from the notifyCallback
  11432. * method.
  11433. *
  11434. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  11435. *
  11436. * - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
  11437. * but to do so without modifying the final value. This is useful to release resources or do some
  11438. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  11439. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  11440. * more information.
  11441. *
  11442. * Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
  11443. * property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
  11444. * make your code IE8 and Android 2.x compatible.
  11445. *
  11446. * # Chaining promises
  11447. *
  11448. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  11449. * possible to create a chain of promises:
  11450. *
  11451. * ```js
  11452. * promiseB = promiseA.then(function(result) {
  11453. * return result + 1;
  11454. * });
  11455. *
  11456. * // promiseB will be resolved immediately after promiseA is resolved and its value
  11457. * // will be the result of promiseA incremented by 1
  11458. * ```
  11459. *
  11460. * It is possible to create chains of any length and since a promise can be resolved with another
  11461. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  11462. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  11463. * $http's response interceptors.
  11464. *
  11465. *
  11466. * # Differences between Kris Kowal's Q and $q
  11467. *
  11468. * There are two main differences:
  11469. *
  11470. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  11471. * mechanism in angular, which means faster propagation of resolution or rejection into your
  11472. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  11473. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  11474. * all the important functionality needed for common async tasks.
  11475. *
  11476. * # Testing
  11477. *
  11478. * ```js
  11479. * it('should simulate promise', inject(function($q, $rootScope) {
  11480. * var deferred = $q.defer();
  11481. * var promise = deferred.promise;
  11482. * var resolvedValue;
  11483. *
  11484. * promise.then(function(value) { resolvedValue = value; });
  11485. * expect(resolvedValue).toBeUndefined();
  11486. *
  11487. * // Simulate resolving of promise
  11488. * deferred.resolve(123);
  11489. * // Note that the 'then' function does not get called synchronously.
  11490. * // This is because we want the promise API to always be async, whether or not
  11491. * // it got called synchronously or asynchronously.
  11492. * expect(resolvedValue).toBeUndefined();
  11493. *
  11494. * // Propagate promise resolution to 'then' functions using $apply().
  11495. * $rootScope.$apply();
  11496. * expect(resolvedValue).toEqual(123);
  11497. * }));
  11498. * ```
  11499. *
  11500. * @param {function(function, function)} resolver Function which is responsible for resolving or
  11501. * rejecting the newly created promise. The first parameter is a function which resolves the
  11502. * promise, the second parameter is a function which rejects the promise.
  11503. *
  11504. * @returns {Promise} The newly created promise.
  11505. */
  11506. function $QProvider() {
  11507. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  11508. return qFactory(function(callback) {
  11509. $rootScope.$evalAsync(callback);
  11510. }, $exceptionHandler);
  11511. }];
  11512. }
  11513. function $$QProvider() {
  11514. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  11515. return qFactory(function(callback) {
  11516. $browser.defer(callback);
  11517. }, $exceptionHandler);
  11518. }];
  11519. }
  11520. /**
  11521. * Constructs a promise manager.
  11522. *
  11523. * @param {function(function)} nextTick Function for executing functions in the next turn.
  11524. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  11525. * debugging purposes.
  11526. * @returns {object} Promise manager.
  11527. */
  11528. function qFactory(nextTick, exceptionHandler) {
  11529. var $qMinErr = minErr('$q', TypeError);
  11530. function callOnce(self, resolveFn, rejectFn) {
  11531. var called = false;
  11532. function wrap(fn) {
  11533. return function(value) {
  11534. if (called) return;
  11535. called = true;
  11536. fn.call(self, value);
  11537. };
  11538. }
  11539. return [wrap(resolveFn), wrap(rejectFn)];
  11540. }
  11541. /**
  11542. * @ngdoc method
  11543. * @name ng.$q#defer
  11544. * @kind function
  11545. *
  11546. * @description
  11547. * Creates a `Deferred` object which represents a task which will finish in the future.
  11548. *
  11549. * @returns {Deferred} Returns a new instance of deferred.
  11550. */
  11551. var defer = function() {
  11552. return new Deferred();
  11553. };
  11554. function Promise() {
  11555. this.$$state = { status: 0 };
  11556. }
  11557. Promise.prototype = {
  11558. then: function(onFulfilled, onRejected, progressBack) {
  11559. var result = new Deferred();
  11560. this.$$state.pending = this.$$state.pending || [];
  11561. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  11562. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  11563. return result.promise;
  11564. },
  11565. "catch": function(callback) {
  11566. return this.then(null, callback);
  11567. },
  11568. "finally": function(callback, progressBack) {
  11569. return this.then(function(value) {
  11570. return handleCallback(value, true, callback);
  11571. }, function(error) {
  11572. return handleCallback(error, false, callback);
  11573. }, progressBack);
  11574. }
  11575. };
  11576. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  11577. function simpleBind(context, fn) {
  11578. return function(value) {
  11579. fn.call(context, value);
  11580. };
  11581. }
  11582. function processQueue(state) {
  11583. var fn, promise, pending;
  11584. pending = state.pending;
  11585. state.processScheduled = false;
  11586. state.pending = undefined;
  11587. for (var i = 0, ii = pending.length; i < ii; ++i) {
  11588. promise = pending[i][0];
  11589. fn = pending[i][state.status];
  11590. try {
  11591. if (isFunction(fn)) {
  11592. promise.resolve(fn(state.value));
  11593. } else if (state.status === 1) {
  11594. promise.resolve(state.value);
  11595. } else {
  11596. promise.reject(state.value);
  11597. }
  11598. } catch(e) {
  11599. promise.reject(e);
  11600. exceptionHandler(e);
  11601. }
  11602. }
  11603. }
  11604. function scheduleProcessQueue(state) {
  11605. if (state.processScheduled || !state.pending) return;
  11606. state.processScheduled = true;
  11607. nextTick(function() { processQueue(state); });
  11608. }
  11609. function Deferred() {
  11610. this.promise = new Promise();
  11611. //Necessary to support unbound execution :/
  11612. this.resolve = simpleBind(this, this.resolve);
  11613. this.reject = simpleBind(this, this.reject);
  11614. this.notify = simpleBind(this, this.notify);
  11615. }
  11616. Deferred.prototype = {
  11617. resolve: function(val) {
  11618. if (this.promise.$$state.status) return;
  11619. if (val === this.promise) {
  11620. this.$$reject($qMinErr(
  11621. 'qcycle',
  11622. "Expected promise to be resolved with value other than itself '{0}'",
  11623. val));
  11624. }
  11625. else {
  11626. this.$$resolve(val);
  11627. }
  11628. },
  11629. $$resolve: function(val) {
  11630. var then, fns;
  11631. fns = callOnce(this, this.$$resolve, this.$$reject);
  11632. try {
  11633. if ((isObject(val) || isFunction(val))) then = val && val.then;
  11634. if (isFunction(then)) {
  11635. this.promise.$$state.status = -1;
  11636. then.call(val, fns[0], fns[1], this.notify);
  11637. } else {
  11638. this.promise.$$state.value = val;
  11639. this.promise.$$state.status = 1;
  11640. scheduleProcessQueue(this.promise.$$state);
  11641. }
  11642. } catch(e) {
  11643. fns[1](e);
  11644. exceptionHandler(e);
  11645. }
  11646. },
  11647. reject: function(reason) {
  11648. if (this.promise.$$state.status) return;
  11649. this.$$reject(reason);
  11650. },
  11651. $$reject: function(reason) {
  11652. this.promise.$$state.value = reason;
  11653. this.promise.$$state.status = 2;
  11654. scheduleProcessQueue(this.promise.$$state);
  11655. },
  11656. notify: function(progress) {
  11657. var callbacks = this.promise.$$state.pending;
  11658. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  11659. nextTick(function() {
  11660. var callback, result;
  11661. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  11662. result = callbacks[i][0];
  11663. callback = callbacks[i][3];
  11664. try {
  11665. result.notify(isFunction(callback) ? callback(progress) : progress);
  11666. } catch(e) {
  11667. exceptionHandler(e);
  11668. }
  11669. }
  11670. });
  11671. }
  11672. }
  11673. };
  11674. /**
  11675. * @ngdoc method
  11676. * @name $q#reject
  11677. * @kind function
  11678. *
  11679. * @description
  11680. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  11681. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  11682. * a promise chain, you don't need to worry about it.
  11683. *
  11684. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  11685. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  11686. * a promise error callback and you want to forward the error to the promise derived from the
  11687. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  11688. * `reject`.
  11689. *
  11690. * ```js
  11691. * promiseB = promiseA.then(function(result) {
  11692. * // success: do something and resolve promiseB
  11693. * // with the old or a new result
  11694. * return result;
  11695. * }, function(reason) {
  11696. * // error: handle the error if possible and
  11697. * // resolve promiseB with newPromiseOrValue,
  11698. * // otherwise forward the rejection to promiseB
  11699. * if (canHandle(reason)) {
  11700. * // handle the error and recover
  11701. * return newPromiseOrValue;
  11702. * }
  11703. * return $q.reject(reason);
  11704. * });
  11705. * ```
  11706. *
  11707. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  11708. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  11709. */
  11710. var reject = function(reason) {
  11711. var result = new Deferred();
  11712. result.reject(reason);
  11713. return result.promise;
  11714. };
  11715. var makePromise = function makePromise(value, resolved) {
  11716. var result = new Deferred();
  11717. if (resolved) {
  11718. result.resolve(value);
  11719. } else {
  11720. result.reject(value);
  11721. }
  11722. return result.promise;
  11723. };
  11724. var handleCallback = function handleCallback(value, isResolved, callback) {
  11725. var callbackOutput = null;
  11726. try {
  11727. if (isFunction(callback)) callbackOutput = callback();
  11728. } catch(e) {
  11729. return makePromise(e, false);
  11730. }
  11731. if (isPromiseLike(callbackOutput)) {
  11732. return callbackOutput.then(function() {
  11733. return makePromise(value, isResolved);
  11734. }, function(error) {
  11735. return makePromise(error, false);
  11736. });
  11737. } else {
  11738. return makePromise(value, isResolved);
  11739. }
  11740. };
  11741. /**
  11742. * @ngdoc method
  11743. * @name $q#when
  11744. * @kind function
  11745. *
  11746. * @description
  11747. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  11748. * This is useful when you are dealing with an object that might or might not be a promise, or if
  11749. * the promise comes from a source that can't be trusted.
  11750. *
  11751. * @param {*} value Value or a promise
  11752. * @returns {Promise} Returns a promise of the passed value or promise
  11753. */
  11754. var when = function(value, callback, errback, progressBack) {
  11755. var result = new Deferred();
  11756. result.resolve(value);
  11757. return result.promise.then(callback, errback, progressBack);
  11758. };
  11759. /**
  11760. * @ngdoc method
  11761. * @name $q#all
  11762. * @kind function
  11763. *
  11764. * @description
  11765. * Combines multiple promises into a single promise that is resolved when all of the input
  11766. * promises are resolved.
  11767. *
  11768. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  11769. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  11770. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  11771. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  11772. * with the same rejection value.
  11773. */
  11774. function all(promises) {
  11775. var deferred = new Deferred(),
  11776. counter = 0,
  11777. results = isArray(promises) ? [] : {};
  11778. forEach(promises, function(promise, key) {
  11779. counter++;
  11780. when(promise).then(function(value) {
  11781. if (results.hasOwnProperty(key)) return;
  11782. results[key] = value;
  11783. if (!(--counter)) deferred.resolve(results);
  11784. }, function(reason) {
  11785. if (results.hasOwnProperty(key)) return;
  11786. deferred.reject(reason);
  11787. });
  11788. });
  11789. if (counter === 0) {
  11790. deferred.resolve(results);
  11791. }
  11792. return deferred.promise;
  11793. }
  11794. var $Q = function Q(resolver) {
  11795. if (!isFunction(resolver)) {
  11796. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  11797. }
  11798. if (!(this instanceof Q)) {
  11799. // More useful when $Q is the Promise itself.
  11800. return new Q(resolver);
  11801. }
  11802. var deferred = new Deferred();
  11803. function resolveFn(value) {
  11804. deferred.resolve(value);
  11805. }
  11806. function rejectFn(reason) {
  11807. deferred.reject(reason);
  11808. }
  11809. resolver(resolveFn, rejectFn);
  11810. return deferred.promise;
  11811. };
  11812. $Q.defer = defer;
  11813. $Q.reject = reject;
  11814. $Q.when = when;
  11815. $Q.all = all;
  11816. return $Q;
  11817. }
  11818. function $$RAFProvider(){ //rAF
  11819. this.$get = ['$window', '$timeout', function($window, $timeout) {
  11820. var requestAnimationFrame = $window.requestAnimationFrame ||
  11821. $window.webkitRequestAnimationFrame ||
  11822. $window.mozRequestAnimationFrame;
  11823. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  11824. $window.webkitCancelAnimationFrame ||
  11825. $window.mozCancelAnimationFrame ||
  11826. $window.webkitCancelRequestAnimationFrame;
  11827. var rafSupported = !!requestAnimationFrame;
  11828. var raf = rafSupported
  11829. ? function(fn) {
  11830. var id = requestAnimationFrame(fn);
  11831. return function() {
  11832. cancelAnimationFrame(id);
  11833. };
  11834. }
  11835. : function(fn) {
  11836. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  11837. return function() {
  11838. $timeout.cancel(timer);
  11839. };
  11840. };
  11841. raf.supported = rafSupported;
  11842. return raf;
  11843. }];
  11844. }
  11845. /**
  11846. * DESIGN NOTES
  11847. *
  11848. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  11849. *
  11850. * The typical use of scope is to watch the expressions, which most of the time return the same
  11851. * value as last time so we optimize the operation.
  11852. *
  11853. * Closures construction is expensive in terms of speed as well as memory:
  11854. * - No closures, instead use prototypical inheritance for API
  11855. * - Internal state needs to be stored on scope directly, which means that private state is
  11856. * exposed as $$____ properties
  11857. *
  11858. * Loop operations are optimized by using while(count--) { ... }
  11859. * - this means that in order to keep the same order of execution as addition we have to add
  11860. * items to the array at the beginning (unshift) instead of at the end (push)
  11861. *
  11862. * Child scopes are created and removed often
  11863. * - Using an array would be slow since inserts in middle are expensive so we use linked list
  11864. *
  11865. * There are few watches then a lot of observers. This is why you don't want the observer to be
  11866. * implemented in the same way as watch. Watch requires return of initialization function which
  11867. * are expensive to construct.
  11868. */
  11869. /**
  11870. * @ngdoc provider
  11871. * @name $rootScopeProvider
  11872. * @description
  11873. *
  11874. * Provider for the $rootScope service.
  11875. */
  11876. /**
  11877. * @ngdoc method
  11878. * @name $rootScopeProvider#digestTtl
  11879. * @description
  11880. *
  11881. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  11882. * assuming that the model is unstable.
  11883. *
  11884. * The current default is 10 iterations.
  11885. *
  11886. * In complex applications it's possible that the dependencies between `$watch`s will result in
  11887. * several digest iterations. However if an application needs more than the default 10 digest
  11888. * iterations for its model to stabilize then you should investigate what is causing the model to
  11889. * continuously change during the digest.
  11890. *
  11891. * Increasing the TTL could have performance implications, so you should not change it without
  11892. * proper justification.
  11893. *
  11894. * @param {number} limit The number of digest iterations.
  11895. */
  11896. /**
  11897. * @ngdoc service
  11898. * @name $rootScope
  11899. * @description
  11900. *
  11901. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  11902. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  11903. * between the model and the view, via a mechanism for watching the model for changes.
  11904. * They also provide an event emission/broadcast and subscription facility. See the
  11905. * {@link guide/scope developer guide on scopes}.
  11906. */
  11907. function $RootScopeProvider(){
  11908. var TTL = 10;
  11909. var $rootScopeMinErr = minErr('$rootScope');
  11910. var lastDirtyWatch = null;
  11911. var applyAsyncId = null;
  11912. this.digestTtl = function(value) {
  11913. if (arguments.length) {
  11914. TTL = value;
  11915. }
  11916. return TTL;
  11917. };
  11918. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  11919. function( $injector, $exceptionHandler, $parse, $browser) {
  11920. /**
  11921. * @ngdoc type
  11922. * @name $rootScope.Scope
  11923. *
  11924. * @description
  11925. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  11926. * {@link auto.$injector $injector}. Child scopes are created using the
  11927. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  11928. * compiled HTML template is executed.)
  11929. *
  11930. * Here is a simple scope snippet to show how you can interact with the scope.
  11931. * ```html
  11932. * <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
  11933. * ```
  11934. *
  11935. * # Inheritance
  11936. * A scope can inherit from a parent scope, as in this example:
  11937. * ```js
  11938. var parent = $rootScope;
  11939. var child = parent.$new();
  11940. parent.salutation = "Hello";
  11941. child.name = "World";
  11942. expect(child.salutation).toEqual('Hello');
  11943. child.salutation = "Welcome";
  11944. expect(child.salutation).toEqual('Welcome');
  11945. expect(parent.salutation).toEqual('Hello');
  11946. * ```
  11947. *
  11948. *
  11949. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  11950. * provided for the current scope. Defaults to {@link ng}.
  11951. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  11952. * append/override services provided by `providers`. This is handy
  11953. * when unit-testing and having the need to override a default
  11954. * service.
  11955. * @returns {Object} Newly created scope.
  11956. *
  11957. */
  11958. function Scope() {
  11959. this.$id = nextUid();
  11960. this.$$phase = this.$parent = this.$$watchers =
  11961. this.$$nextSibling = this.$$prevSibling =
  11962. this.$$childHead = this.$$childTail = null;
  11963. this.$root = this;
  11964. this.$$destroyed = false;
  11965. this.$$listeners = {};
  11966. this.$$listenerCount = {};
  11967. this.$$isolateBindings = null;
  11968. }
  11969. /**
  11970. * @ngdoc property
  11971. * @name $rootScope.Scope#$id
  11972. *
  11973. * @description
  11974. * Unique scope ID (monotonically increasing) useful for debugging.
  11975. */
  11976. /**
  11977. * @ngdoc property
  11978. * @name $rootScope.Scope#$parent
  11979. *
  11980. * @description
  11981. * Reference to the parent scope.
  11982. */
  11983. /**
  11984. * @ngdoc property
  11985. * @name $rootScope.Scope#$root
  11986. *
  11987. * @description
  11988. * Reference to the root scope.
  11989. */
  11990. Scope.prototype = {
  11991. constructor: Scope,
  11992. /**
  11993. * @ngdoc method
  11994. * @name $rootScope.Scope#$new
  11995. * @kind function
  11996. *
  11997. * @description
  11998. * Creates a new child {@link ng.$rootScope.Scope scope}.
  11999. *
  12000. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  12001. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  12002. *
  12003. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  12004. * desired for the scope and its child scopes to be permanently detached from the parent and
  12005. * thus stop participating in model change detection and listener notification by invoking.
  12006. *
  12007. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  12008. * parent scope. The scope is isolated, as it can not see parent scope properties.
  12009. * When creating widgets, it is useful for the widget to not accidentally read parent
  12010. * state.
  12011. *
  12012. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  12013. * of the newly created scope. Defaults to `this` scope if not provided.
  12014. * This is used when creating a transclude scope to correctly place it
  12015. * in the scope hierarchy while maintaining the correct prototypical
  12016. * inheritance.
  12017. *
  12018. * @returns {Object} The newly created child scope.
  12019. *
  12020. */
  12021. $new: function(isolate, parent) {
  12022. var child;
  12023. parent = parent || this;
  12024. if (isolate) {
  12025. child = new Scope();
  12026. child.$root = this.$root;
  12027. } else {
  12028. // Only create a child scope class if somebody asks for one,
  12029. // but cache it to allow the VM to optimize lookups.
  12030. if (!this.$$ChildScope) {
  12031. this.$$ChildScope = function ChildScope() {
  12032. this.$$watchers = this.$$nextSibling =
  12033. this.$$childHead = this.$$childTail = null;
  12034. this.$$listeners = {};
  12035. this.$$listenerCount = {};
  12036. this.$id = nextUid();
  12037. this.$$ChildScope = null;
  12038. };
  12039. this.$$ChildScope.prototype = this;
  12040. }
  12041. child = new this.$$ChildScope();
  12042. }
  12043. child.$parent = parent;
  12044. child.$$prevSibling = parent.$$childTail;
  12045. if (parent.$$childHead) {
  12046. parent.$$childTail.$$nextSibling = child;
  12047. parent.$$childTail = child;
  12048. } else {
  12049. parent.$$childHead = parent.$$childTail = child;
  12050. }
  12051. // When the new scope is not isolated or we inherit from `this`, and
  12052. // the parent scope is destroyed, the property `$$destroyed` is inherited
  12053. // prototypically. In all other cases, this property needs to be set
  12054. // when the parent scope is destroyed.
  12055. // The listener needs to be added after the parent is set
  12056. if (isolate || parent != this) child.$on('$destroy', destroyChild);
  12057. return child;
  12058. function destroyChild() {
  12059. child.$$destroyed = true;
  12060. }
  12061. },
  12062. /**
  12063. * @ngdoc method
  12064. * @name $rootScope.Scope#$watch
  12065. * @kind function
  12066. *
  12067. * @description
  12068. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  12069. *
  12070. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  12071. * $digest()} and should return the value that will be watched. (Since
  12072. * {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
  12073. * `watchExpression` can execute multiple times per
  12074. * {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
  12075. * - The `listener` is called only when the value from the current `watchExpression` and the
  12076. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  12077. * see below). Inequality is determined according to reference inequality,
  12078. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  12079. * via the `!==` Javascript operator, unless `objectEquality == true`
  12080. * (see next point)
  12081. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  12082. * according to the {@link angular.equals} function. To save the value of the object for
  12083. * later comparison, the {@link angular.copy} function is used. This therefore means that
  12084. * watching complex objects will have adverse memory and performance implications.
  12085. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  12086. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  12087. * iteration limit is 10 to prevent an infinite loop deadlock.
  12088. *
  12089. *
  12090. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  12091. * you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
  12092. * can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
  12093. * change is detected, be prepared for multiple calls to your listener.)
  12094. *
  12095. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  12096. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  12097. * watcher. In rare cases, this is undesirable because the listener is called when the result
  12098. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  12099. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  12100. * listener was called due to initialization.
  12101. *
  12102. *
  12103. *
  12104. * # Example
  12105. * ```js
  12106. // let's assume that scope was dependency injected as the $rootScope
  12107. var scope = $rootScope;
  12108. scope.name = 'misko';
  12109. scope.counter = 0;
  12110. expect(scope.counter).toEqual(0);
  12111. scope.$watch('name', function(newValue, oldValue) {
  12112. scope.counter = scope.counter + 1;
  12113. });
  12114. expect(scope.counter).toEqual(0);
  12115. scope.$digest();
  12116. // the listener is always called during the first $digest loop after it was registered
  12117. expect(scope.counter).toEqual(1);
  12118. scope.$digest();
  12119. // but now it will not be called unless the value changes
  12120. expect(scope.counter).toEqual(1);
  12121. scope.name = 'adam';
  12122. scope.$digest();
  12123. expect(scope.counter).toEqual(2);
  12124. // Using a function as a watchExpression
  12125. var food;
  12126. scope.foodCounter = 0;
  12127. expect(scope.foodCounter).toEqual(0);
  12128. scope.$watch(
  12129. // This function returns the value being watched. It is called for each turn of the $digest loop
  12130. function() { return food; },
  12131. // This is the change listener, called when the value returned from the above function changes
  12132. function(newValue, oldValue) {
  12133. if ( newValue !== oldValue ) {
  12134. // Only increment the counter if the value changed
  12135. scope.foodCounter = scope.foodCounter + 1;
  12136. }
  12137. }
  12138. );
  12139. // No digest has been run so the counter will be zero
  12140. expect(scope.foodCounter).toEqual(0);
  12141. // Run the digest but since food has not changed count will still be zero
  12142. scope.$digest();
  12143. expect(scope.foodCounter).toEqual(0);
  12144. // Update food and run digest. Now the counter will increment
  12145. food = 'cheeseburger';
  12146. scope.$digest();
  12147. expect(scope.foodCounter).toEqual(1);
  12148. * ```
  12149. *
  12150. *
  12151. *
  12152. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  12153. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  12154. * a call to the `listener`.
  12155. *
  12156. * - `string`: Evaluated as {@link guide/expression expression}
  12157. * - `function(scope)`: called with current `scope` as a parameter.
  12158. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  12159. * of `watchExpression` changes.
  12160. *
  12161. * - `newVal` contains the current value of the `watchExpression`
  12162. * - `oldVal` contains the previous value of the `watchExpression`
  12163. * - `scope` refers to the current scope
  12164. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  12165. * comparing for reference equality.
  12166. * @returns {function()} Returns a deregistration function for this listener.
  12167. */
  12168. $watch: function(watchExp, listener, objectEquality) {
  12169. var get = $parse(watchExp);
  12170. if (get.$$watchDelegate) {
  12171. return get.$$watchDelegate(this, listener, objectEquality, get);
  12172. }
  12173. var scope = this,
  12174. array = scope.$$watchers,
  12175. watcher = {
  12176. fn: listener,
  12177. last: initWatchVal,
  12178. get: get,
  12179. exp: watchExp,
  12180. eq: !!objectEquality
  12181. };
  12182. lastDirtyWatch = null;
  12183. if (!isFunction(listener)) {
  12184. watcher.fn = noop;
  12185. }
  12186. if (!array) {
  12187. array = scope.$$watchers = [];
  12188. }
  12189. // we use unshift since we use a while loop in $digest for speed.
  12190. // the while loop reads in reverse order.
  12191. array.unshift(watcher);
  12192. return function deregisterWatch() {
  12193. arrayRemove(array, watcher);
  12194. lastDirtyWatch = null;
  12195. };
  12196. },
  12197. /**
  12198. * @ngdoc method
  12199. * @name $rootScope.Scope#$watchGroup
  12200. * @kind function
  12201. *
  12202. * @description
  12203. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  12204. * If any one expression in the collection changes the `listener` is executed.
  12205. *
  12206. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  12207. * call to $digest() to see if any items changes.
  12208. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  12209. *
  12210. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  12211. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  12212. *
  12213. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  12214. * expression in `watchExpressions` changes
  12215. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  12216. * those of `watchExpression`
  12217. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  12218. * those of `watchExpression`
  12219. * The `scope` refers to the current scope.
  12220. * @returns {function()} Returns a de-registration function for all listeners.
  12221. */
  12222. $watchGroup: function(watchExpressions, listener) {
  12223. var oldValues = new Array(watchExpressions.length);
  12224. var newValues = new Array(watchExpressions.length);
  12225. var deregisterFns = [];
  12226. var self = this;
  12227. var changeReactionScheduled = false;
  12228. var firstRun = true;
  12229. if (!watchExpressions.length) {
  12230. // No expressions means we call the listener ASAP
  12231. var shouldCall = true;
  12232. self.$evalAsync(function () {
  12233. if (shouldCall) listener(newValues, newValues, self);
  12234. });
  12235. return function deregisterWatchGroup() {
  12236. shouldCall = false;
  12237. };
  12238. }
  12239. if (watchExpressions.length === 1) {
  12240. // Special case size of one
  12241. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  12242. newValues[0] = value;
  12243. oldValues[0] = oldValue;
  12244. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  12245. });
  12246. }
  12247. forEach(watchExpressions, function (expr, i) {
  12248. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  12249. newValues[i] = value;
  12250. oldValues[i] = oldValue;
  12251. if (!changeReactionScheduled) {
  12252. changeReactionScheduled = true;
  12253. self.$evalAsync(watchGroupAction);
  12254. }
  12255. });
  12256. deregisterFns.push(unwatchFn);
  12257. });
  12258. function watchGroupAction() {
  12259. changeReactionScheduled = false;
  12260. if (firstRun) {
  12261. firstRun = false;
  12262. listener(newValues, newValues, self);
  12263. } else {
  12264. listener(newValues, oldValues, self);
  12265. }
  12266. }
  12267. return function deregisterWatchGroup() {
  12268. while (deregisterFns.length) {
  12269. deregisterFns.shift()();
  12270. }
  12271. };
  12272. },
  12273. /**
  12274. * @ngdoc method
  12275. * @name $rootScope.Scope#$watchCollection
  12276. * @kind function
  12277. *
  12278. * @description
  12279. * Shallow watches the properties of an object and fires whenever any of the properties change
  12280. * (for arrays, this implies watching the array items; for object maps, this implies watching
  12281. * the properties). If a change is detected, the `listener` callback is fired.
  12282. *
  12283. * - The `obj` collection is observed via standard $watch operation and is examined on every
  12284. * call to $digest() to see if any items have been added, removed, or moved.
  12285. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  12286. * adding, removing, and moving items belonging to an object or array.
  12287. *
  12288. *
  12289. * # Example
  12290. * ```js
  12291. $scope.names = ['igor', 'matias', 'misko', 'james'];
  12292. $scope.dataCount = 4;
  12293. $scope.$watchCollection('names', function(newNames, oldNames) {
  12294. $scope.dataCount = newNames.length;
  12295. });
  12296. expect($scope.dataCount).toEqual(4);
  12297. $scope.$digest();
  12298. //still at 4 ... no changes
  12299. expect($scope.dataCount).toEqual(4);
  12300. $scope.names.pop();
  12301. $scope.$digest();
  12302. //now there's been a change
  12303. expect($scope.dataCount).toEqual(3);
  12304. * ```
  12305. *
  12306. *
  12307. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  12308. * expression value should evaluate to an object or an array which is observed on each
  12309. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  12310. * collection will trigger a call to the `listener`.
  12311. *
  12312. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  12313. * when a change is detected.
  12314. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  12315. * - The `oldCollection` object is a copy of the former collection data.
  12316. * Due to performance considerations, the`oldCollection` value is computed only if the
  12317. * `listener` function declares two or more arguments.
  12318. * - The `scope` argument refers to the current scope.
  12319. *
  12320. * @returns {function()} Returns a de-registration function for this listener. When the
  12321. * de-registration function is executed, the internal watch operation is terminated.
  12322. */
  12323. $watchCollection: function(obj, listener) {
  12324. $watchCollectionInterceptor.$stateful = true;
  12325. var self = this;
  12326. // the current value, updated on each dirty-check run
  12327. var newValue;
  12328. // a shallow copy of the newValue from the last dirty-check run,
  12329. // updated to match newValue during dirty-check run
  12330. var oldValue;
  12331. // a shallow copy of the newValue from when the last change happened
  12332. var veryOldValue;
  12333. // only track veryOldValue if the listener is asking for it
  12334. var trackVeryOldValue = (listener.length > 1);
  12335. var changeDetected = 0;
  12336. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  12337. var internalArray = [];
  12338. var internalObject = {};
  12339. var initRun = true;
  12340. var oldLength = 0;
  12341. function $watchCollectionInterceptor(_value) {
  12342. newValue = _value;
  12343. var newLength, key, bothNaN, newItem, oldItem;
  12344. if (!isObject(newValue)) { // if primitive
  12345. if (oldValue !== newValue) {
  12346. oldValue = newValue;
  12347. changeDetected++;
  12348. }
  12349. } else if (isArrayLike(newValue)) {
  12350. if (oldValue !== internalArray) {
  12351. // we are transitioning from something which was not an array into array.
  12352. oldValue = internalArray;
  12353. oldLength = oldValue.length = 0;
  12354. changeDetected++;
  12355. }
  12356. newLength = newValue.length;
  12357. if (oldLength !== newLength) {
  12358. // if lengths do not match we need to trigger change notification
  12359. changeDetected++;
  12360. oldValue.length = oldLength = newLength;
  12361. }
  12362. // copy the items to oldValue and look for changes.
  12363. for (var i = 0; i < newLength; i++) {
  12364. oldItem = oldValue[i];
  12365. newItem = newValue[i];
  12366. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12367. if (!bothNaN && (oldItem !== newItem)) {
  12368. changeDetected++;
  12369. oldValue[i] = newItem;
  12370. }
  12371. }
  12372. } else {
  12373. if (oldValue !== internalObject) {
  12374. // we are transitioning from something which was not an object into object.
  12375. oldValue = internalObject = {};
  12376. oldLength = 0;
  12377. changeDetected++;
  12378. }
  12379. // copy the items to oldValue and look for changes.
  12380. newLength = 0;
  12381. for (key in newValue) {
  12382. if (newValue.hasOwnProperty(key)) {
  12383. newLength++;
  12384. newItem = newValue[key];
  12385. oldItem = oldValue[key];
  12386. if (key in oldValue) {
  12387. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  12388. if (!bothNaN && (oldItem !== newItem)) {
  12389. changeDetected++;
  12390. oldValue[key] = newItem;
  12391. }
  12392. } else {
  12393. oldLength++;
  12394. oldValue[key] = newItem;
  12395. changeDetected++;
  12396. }
  12397. }
  12398. }
  12399. if (oldLength > newLength) {
  12400. // we used to have more keys, need to find them and destroy them.
  12401. changeDetected++;
  12402. for(key in oldValue) {
  12403. if (!newValue.hasOwnProperty(key)) {
  12404. oldLength--;
  12405. delete oldValue[key];
  12406. }
  12407. }
  12408. }
  12409. }
  12410. return changeDetected;
  12411. }
  12412. function $watchCollectionAction() {
  12413. if (initRun) {
  12414. initRun = false;
  12415. listener(newValue, newValue, self);
  12416. } else {
  12417. listener(newValue, veryOldValue, self);
  12418. }
  12419. // make a copy for the next time a collection is changed
  12420. if (trackVeryOldValue) {
  12421. if (!isObject(newValue)) {
  12422. //primitive
  12423. veryOldValue = newValue;
  12424. } else if (isArrayLike(newValue)) {
  12425. veryOldValue = new Array(newValue.length);
  12426. for (var i = 0; i < newValue.length; i++) {
  12427. veryOldValue[i] = newValue[i];
  12428. }
  12429. } else { // if object
  12430. veryOldValue = {};
  12431. for (var key in newValue) {
  12432. if (hasOwnProperty.call(newValue, key)) {
  12433. veryOldValue[key] = newValue[key];
  12434. }
  12435. }
  12436. }
  12437. }
  12438. }
  12439. return this.$watch(changeDetector, $watchCollectionAction);
  12440. },
  12441. /**
  12442. * @ngdoc method
  12443. * @name $rootScope.Scope#$digest
  12444. * @kind function
  12445. *
  12446. * @description
  12447. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  12448. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  12449. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  12450. * until no more listeners are firing. This means that it is possible to get into an infinite
  12451. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  12452. * iterations exceeds 10.
  12453. *
  12454. * Usually, you don't call `$digest()` directly in
  12455. * {@link ng.directive:ngController controllers} or in
  12456. * {@link ng.$compileProvider#directive directives}.
  12457. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  12458. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  12459. *
  12460. * If you want to be notified whenever `$digest()` is called,
  12461. * you can register a `watchExpression` function with
  12462. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  12463. *
  12464. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  12465. *
  12466. * # Example
  12467. * ```js
  12468. var scope = ...;
  12469. scope.name = 'misko';
  12470. scope.counter = 0;
  12471. expect(scope.counter).toEqual(0);
  12472. scope.$watch('name', function(newValue, oldValue) {
  12473. scope.counter = scope.counter + 1;
  12474. });
  12475. expect(scope.counter).toEqual(0);
  12476. scope.$digest();
  12477. // the listener is always called during the first $digest loop after it was registered
  12478. expect(scope.counter).toEqual(1);
  12479. scope.$digest();
  12480. // but now it will not be called unless the value changes
  12481. expect(scope.counter).toEqual(1);
  12482. scope.name = 'adam';
  12483. scope.$digest();
  12484. expect(scope.counter).toEqual(2);
  12485. * ```
  12486. *
  12487. */
  12488. $digest: function() {
  12489. var watch, value, last,
  12490. watchers,
  12491. length,
  12492. dirty, ttl = TTL,
  12493. next, current, target = this,
  12494. watchLog = [],
  12495. logIdx, logMsg, asyncTask;
  12496. beginPhase('$digest');
  12497. // Check for changes to browser url that happened in sync before the call to $digest
  12498. $browser.$$checkUrlChange();
  12499. if (this === $rootScope && applyAsyncId !== null) {
  12500. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  12501. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  12502. $browser.defer.cancel(applyAsyncId);
  12503. flushApplyAsync();
  12504. }
  12505. lastDirtyWatch = null;
  12506. do { // "while dirty" loop
  12507. dirty = false;
  12508. current = target;
  12509. while(asyncQueue.length) {
  12510. try {
  12511. asyncTask = asyncQueue.shift();
  12512. asyncTask.scope.$eval(asyncTask.expression);
  12513. } catch (e) {
  12514. $exceptionHandler(e);
  12515. }
  12516. lastDirtyWatch = null;
  12517. }
  12518. traverseScopesLoop:
  12519. do { // "traverse the scopes" loop
  12520. if ((watchers = current.$$watchers)) {
  12521. // process our watches
  12522. length = watchers.length;
  12523. while (length--) {
  12524. try {
  12525. watch = watchers[length];
  12526. // Most common watches are on primitives, in which case we can short
  12527. // circuit it with === operator, only when === fails do we use .equals
  12528. if (watch) {
  12529. if ((value = watch.get(current)) !== (last = watch.last) &&
  12530. !(watch.eq
  12531. ? equals(value, last)
  12532. : (typeof value === 'number' && typeof last === 'number'
  12533. && isNaN(value) && isNaN(last)))) {
  12534. dirty = true;
  12535. lastDirtyWatch = watch;
  12536. watch.last = watch.eq ? copy(value, null) : value;
  12537. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  12538. if (ttl < 5) {
  12539. logIdx = 4 - ttl;
  12540. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  12541. logMsg = (isFunction(watch.exp))
  12542. ? 'fn: ' + (watch.exp.name || watch.exp.toString())
  12543. : watch.exp;
  12544. logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
  12545. watchLog[logIdx].push(logMsg);
  12546. }
  12547. } else if (watch === lastDirtyWatch) {
  12548. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  12549. // have already been tested.
  12550. dirty = false;
  12551. break traverseScopesLoop;
  12552. }
  12553. }
  12554. } catch (e) {
  12555. $exceptionHandler(e);
  12556. }
  12557. }
  12558. }
  12559. // Insanity Warning: scope depth-first traversal
  12560. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  12561. // this piece should be kept in sync with the traversal in $broadcast
  12562. if (!(next = (current.$$childHead ||
  12563. (current !== target && current.$$nextSibling)))) {
  12564. while(current !== target && !(next = current.$$nextSibling)) {
  12565. current = current.$parent;
  12566. }
  12567. }
  12568. } while ((current = next));
  12569. // `break traverseScopesLoop;` takes us to here
  12570. if((dirty || asyncQueue.length) && !(ttl--)) {
  12571. clearPhase();
  12572. throw $rootScopeMinErr('infdig',
  12573. '{0} $digest() iterations reached. Aborting!\n' +
  12574. 'Watchers fired in the last 5 iterations: {1}',
  12575. TTL, toJson(watchLog));
  12576. }
  12577. } while (dirty || asyncQueue.length);
  12578. clearPhase();
  12579. while(postDigestQueue.length) {
  12580. try {
  12581. postDigestQueue.shift()();
  12582. } catch (e) {
  12583. $exceptionHandler(e);
  12584. }
  12585. }
  12586. },
  12587. /**
  12588. * @ngdoc event
  12589. * @name $rootScope.Scope#$destroy
  12590. * @eventType broadcast on scope being destroyed
  12591. *
  12592. * @description
  12593. * Broadcasted when a scope and its children are being destroyed.
  12594. *
  12595. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12596. * clean up DOM bindings before an element is removed from the DOM.
  12597. */
  12598. /**
  12599. * @ngdoc method
  12600. * @name $rootScope.Scope#$destroy
  12601. * @kind function
  12602. *
  12603. * @description
  12604. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  12605. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  12606. * propagate to the current scope and its children. Removal also implies that the current
  12607. * scope is eligible for garbage collection.
  12608. *
  12609. * The `$destroy()` is usually used by directives such as
  12610. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  12611. * unrolling of the loop.
  12612. *
  12613. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  12614. * Application code can register a `$destroy` event handler that will give it a chance to
  12615. * perform any necessary cleanup.
  12616. *
  12617. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  12618. * clean up DOM bindings before an element is removed from the DOM.
  12619. */
  12620. $destroy: function() {
  12621. // we can't destroy the root scope or a scope that has been already destroyed
  12622. if (this.$$destroyed) return;
  12623. var parent = this.$parent;
  12624. this.$broadcast('$destroy');
  12625. this.$$destroyed = true;
  12626. if (this === $rootScope) return;
  12627. for (var eventName in this.$$listenerCount) {
  12628. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  12629. }
  12630. // sever all the references to parent scopes (after this cleanup, the current scope should
  12631. // not be retained by any of our references and should be eligible for garbage collection)
  12632. if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  12633. if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  12634. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  12635. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  12636. // Disable listeners, watchers and apply/digest methods
  12637. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  12638. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  12639. this.$$listeners = {};
  12640. // All of the code below is bogus code that works around V8's memory leak via optimized code
  12641. // and inline caches.
  12642. //
  12643. // see:
  12644. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  12645. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  12646. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  12647. this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
  12648. this.$$childTail = this.$root = this.$$watchers = null;
  12649. },
  12650. /**
  12651. * @ngdoc method
  12652. * @name $rootScope.Scope#$eval
  12653. * @kind function
  12654. *
  12655. * @description
  12656. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  12657. * the expression are propagated (uncaught). This is useful when evaluating Angular
  12658. * expressions.
  12659. *
  12660. * # Example
  12661. * ```js
  12662. var scope = ng.$rootScope.Scope();
  12663. scope.a = 1;
  12664. scope.b = 2;
  12665. expect(scope.$eval('a+b')).toEqual(3);
  12666. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  12667. * ```
  12668. *
  12669. * @param {(string|function())=} expression An angular expression to be executed.
  12670. *
  12671. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12672. * - `function(scope)`: execute the function with the current `scope` parameter.
  12673. *
  12674. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  12675. * @returns {*} The result of evaluating the expression.
  12676. */
  12677. $eval: function(expr, locals) {
  12678. return $parse(expr)(this, locals);
  12679. },
  12680. /**
  12681. * @ngdoc method
  12682. * @name $rootScope.Scope#$evalAsync
  12683. * @kind function
  12684. *
  12685. * @description
  12686. * Executes the expression on the current scope at a later point in time.
  12687. *
  12688. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  12689. * that:
  12690. *
  12691. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  12692. * rendering).
  12693. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  12694. * `expression` execution.
  12695. *
  12696. * Any exceptions from the execution of the expression are forwarded to the
  12697. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12698. *
  12699. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  12700. * will be scheduled. However, it is encouraged to always call code that changes the model
  12701. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  12702. *
  12703. * @param {(string|function())=} expression An angular expression to be executed.
  12704. *
  12705. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12706. * - `function(scope)`: execute the function with the current `scope` parameter.
  12707. *
  12708. */
  12709. $evalAsync: function(expr) {
  12710. // if we are outside of an $digest loop and this is the first time we are scheduling async
  12711. // task also schedule async auto-flush
  12712. if (!$rootScope.$$phase && !asyncQueue.length) {
  12713. $browser.defer(function() {
  12714. if (asyncQueue.length) {
  12715. $rootScope.$digest();
  12716. }
  12717. });
  12718. }
  12719. asyncQueue.push({scope: this, expression: expr});
  12720. },
  12721. $$postDigest : function(fn) {
  12722. postDigestQueue.push(fn);
  12723. },
  12724. /**
  12725. * @ngdoc method
  12726. * @name $rootScope.Scope#$apply
  12727. * @kind function
  12728. *
  12729. * @description
  12730. * `$apply()` is used to execute an expression in angular from outside of the angular
  12731. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  12732. * Because we are calling into the angular framework we need to perform proper scope life
  12733. * cycle of {@link ng.$exceptionHandler exception handling},
  12734. * {@link ng.$rootScope.Scope#$digest executing watches}.
  12735. *
  12736. * ## Life cycle
  12737. *
  12738. * # Pseudo-Code of `$apply()`
  12739. * ```js
  12740. function $apply(expr) {
  12741. try {
  12742. return $eval(expr);
  12743. } catch (e) {
  12744. $exceptionHandler(e);
  12745. } finally {
  12746. $root.$digest();
  12747. }
  12748. }
  12749. * ```
  12750. *
  12751. *
  12752. * Scope's `$apply()` method transitions through the following stages:
  12753. *
  12754. * 1. The {@link guide/expression expression} is executed using the
  12755. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  12756. * 2. Any exceptions from the execution of the expression are forwarded to the
  12757. * {@link ng.$exceptionHandler $exceptionHandler} service.
  12758. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  12759. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  12760. *
  12761. *
  12762. * @param {(string|function())=} exp An angular expression to be executed.
  12763. *
  12764. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12765. * - `function(scope)`: execute the function with current `scope` parameter.
  12766. *
  12767. * @returns {*} The result of evaluating the expression.
  12768. */
  12769. $apply: function(expr) {
  12770. try {
  12771. beginPhase('$apply');
  12772. return this.$eval(expr);
  12773. } catch (e) {
  12774. $exceptionHandler(e);
  12775. } finally {
  12776. clearPhase();
  12777. try {
  12778. $rootScope.$digest();
  12779. } catch (e) {
  12780. $exceptionHandler(e);
  12781. throw e;
  12782. }
  12783. }
  12784. },
  12785. /**
  12786. * @ngdoc method
  12787. * @name $rootScope.Scope#$applyAsync
  12788. * @kind function
  12789. *
  12790. * @description
  12791. * Schedule the invokation of $apply to occur at a later time. The actual time difference
  12792. * varies across browsers, but is typically around ~10 milliseconds.
  12793. *
  12794. * This can be used to queue up multiple expressions which need to be evaluated in the same
  12795. * digest.
  12796. *
  12797. * @param {(string|function())=} exp An angular expression to be executed.
  12798. *
  12799. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  12800. * - `function(scope)`: execute the function with current `scope` parameter.
  12801. */
  12802. $applyAsync: function(expr) {
  12803. var scope = this;
  12804. expr && applyAsyncQueue.push($applyAsyncExpression);
  12805. scheduleApplyAsync();
  12806. function $applyAsyncExpression() {
  12807. scope.$eval(expr);
  12808. }
  12809. },
  12810. /**
  12811. * @ngdoc method
  12812. * @name $rootScope.Scope#$on
  12813. * @kind function
  12814. *
  12815. * @description
  12816. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  12817. * discussion of event life cycle.
  12818. *
  12819. * The event listener function format is: `function(event, args...)`. The `event` object
  12820. * passed into the listener has the following attributes:
  12821. *
  12822. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  12823. * `$broadcast`-ed.
  12824. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  12825. * event propagates through the scope hierarchy, this property is set to null.
  12826. * - `name` - `{string}`: name of the event.
  12827. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  12828. * further event propagation (available only for events that were `$emit`-ed).
  12829. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  12830. * to true.
  12831. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  12832. *
  12833. * @param {string} name Event name to listen on.
  12834. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  12835. * @returns {function()} Returns a deregistration function for this listener.
  12836. */
  12837. $on: function(name, listener) {
  12838. var namedListeners = this.$$listeners[name];
  12839. if (!namedListeners) {
  12840. this.$$listeners[name] = namedListeners = [];
  12841. }
  12842. namedListeners.push(listener);
  12843. var current = this;
  12844. do {
  12845. if (!current.$$listenerCount[name]) {
  12846. current.$$listenerCount[name] = 0;
  12847. }
  12848. current.$$listenerCount[name]++;
  12849. } while ((current = current.$parent));
  12850. var self = this;
  12851. return function() {
  12852. namedListeners[namedListeners.indexOf(listener)] = null;
  12853. decrementListenerCount(self, 1, name);
  12854. };
  12855. },
  12856. /**
  12857. * @ngdoc method
  12858. * @name $rootScope.Scope#$emit
  12859. * @kind function
  12860. *
  12861. * @description
  12862. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  12863. * registered {@link ng.$rootScope.Scope#$on} listeners.
  12864. *
  12865. * The event life cycle starts at the scope on which `$emit` was called. All
  12866. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  12867. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  12868. * registered listeners along the way. The event will stop propagating if one of the listeners
  12869. * cancels it.
  12870. *
  12871. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  12872. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  12873. *
  12874. * @param {string} name Event name to emit.
  12875. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  12876. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  12877. */
  12878. $emit: function(name, args) {
  12879. var empty = [],
  12880. namedListeners,
  12881. scope = this,
  12882. stopPropagation = false,
  12883. event = {
  12884. name: name,
  12885. targetScope: scope,
  12886. stopPropagation: function() {stopPropagation = true;},
  12887. preventDefault: function() {
  12888. event.defaultPrevented = true;
  12889. },
  12890. defaultPrevented: false
  12891. },
  12892. listenerArgs = concat([event], arguments, 1),
  12893. i, length;
  12894. do {
  12895. namedListeners = scope.$$listeners[name] || empty;
  12896. event.currentScope = scope;
  12897. for (i=0, length=namedListeners.length; i<length; i++) {
  12898. // if listeners were deregistered, defragment the array
  12899. if (!namedListeners[i]) {
  12900. namedListeners.splice(i, 1);
  12901. i--;
  12902. length--;
  12903. continue;
  12904. }
  12905. try {
  12906. //allow all listeners attached to the current scope to run
  12907. namedListeners[i].apply(null, listenerArgs);
  12908. } catch (e) {
  12909. $exceptionHandler(e);
  12910. }
  12911. }
  12912. //if any listener on the current scope stops propagation, prevent bubbling
  12913. if (stopPropagation) {
  12914. event.currentScope = null;
  12915. return event;
  12916. }
  12917. //traverse upwards
  12918. scope = scope.$parent;
  12919. } while (scope);
  12920. event.currentScope = null;
  12921. return event;
  12922. },
  12923. /**
  12924. * @ngdoc method
  12925. * @name $rootScope.Scope#$broadcast
  12926. * @kind function
  12927. *
  12928. * @description
  12929. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  12930. * registered {@link ng.$rootScope.Scope#$on} listeners.
  12931. *
  12932. * The event life cycle starts at the scope on which `$broadcast` was called. All
  12933. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  12934. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  12935. * scope and calls all registered listeners along the way. The event cannot be canceled.
  12936. *
  12937. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  12938. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  12939. *
  12940. * @param {string} name Event name to broadcast.
  12941. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  12942. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  12943. */
  12944. $broadcast: function(name, args) {
  12945. var target = this,
  12946. current = target,
  12947. next = target,
  12948. event = {
  12949. name: name,
  12950. targetScope: target,
  12951. preventDefault: function() {
  12952. event.defaultPrevented = true;
  12953. },
  12954. defaultPrevented: false
  12955. };
  12956. if (!target.$$listenerCount[name]) return event;
  12957. var listenerArgs = concat([event], arguments, 1),
  12958. listeners, i, length;
  12959. //down while you can, then up and next sibling or up and next sibling until back at root
  12960. while ((current = next)) {
  12961. event.currentScope = current;
  12962. listeners = current.$$listeners[name] || [];
  12963. for (i=0, length = listeners.length; i<length; i++) {
  12964. // if listeners were deregistered, defragment the array
  12965. if (!listeners[i]) {
  12966. listeners.splice(i, 1);
  12967. i--;
  12968. length--;
  12969. continue;
  12970. }
  12971. try {
  12972. listeners[i].apply(null, listenerArgs);
  12973. } catch(e) {
  12974. $exceptionHandler(e);
  12975. }
  12976. }
  12977. // Insanity Warning: scope depth-first traversal
  12978. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  12979. // this piece should be kept in sync with the traversal in $digest
  12980. // (though it differs due to having the extra check for $$listenerCount)
  12981. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  12982. (current !== target && current.$$nextSibling)))) {
  12983. while(current !== target && !(next = current.$$nextSibling)) {
  12984. current = current.$parent;
  12985. }
  12986. }
  12987. }
  12988. event.currentScope = null;
  12989. return event;
  12990. }
  12991. };
  12992. var $rootScope = new Scope();
  12993. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  12994. var asyncQueue = $rootScope.$$asyncQueue = [];
  12995. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  12996. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  12997. return $rootScope;
  12998. function beginPhase(phase) {
  12999. if ($rootScope.$$phase) {
  13000. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  13001. }
  13002. $rootScope.$$phase = phase;
  13003. }
  13004. function clearPhase() {
  13005. $rootScope.$$phase = null;
  13006. }
  13007. function decrementListenerCount(current, count, name) {
  13008. do {
  13009. current.$$listenerCount[name] -= count;
  13010. if (current.$$listenerCount[name] === 0) {
  13011. delete current.$$listenerCount[name];
  13012. }
  13013. } while ((current = current.$parent));
  13014. }
  13015. /**
  13016. * function used as an initial value for watchers.
  13017. * because it's unique we can easily tell it apart from other values
  13018. */
  13019. function initWatchVal() {}
  13020. function flushApplyAsync() {
  13021. while (applyAsyncQueue.length) {
  13022. try {
  13023. applyAsyncQueue.shift()();
  13024. } catch(e) {
  13025. $exceptionHandler(e);
  13026. }
  13027. }
  13028. applyAsyncId = null;
  13029. }
  13030. function scheduleApplyAsync() {
  13031. if (applyAsyncId === null) {
  13032. applyAsyncId = $browser.defer(function() {
  13033. $rootScope.$apply(flushApplyAsync);
  13034. });
  13035. }
  13036. }
  13037. }];
  13038. }
  13039. /**
  13040. * @description
  13041. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  13042. */
  13043. function $$SanitizeUriProvider() {
  13044. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  13045. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  13046. /**
  13047. * @description
  13048. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13049. * urls during a[href] sanitization.
  13050. *
  13051. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13052. *
  13053. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  13054. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  13055. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13056. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13057. *
  13058. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13059. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13060. * chaining otherwise.
  13061. */
  13062. this.aHrefSanitizationWhitelist = function(regexp) {
  13063. if (isDefined(regexp)) {
  13064. aHrefSanitizationWhitelist = regexp;
  13065. return this;
  13066. }
  13067. return aHrefSanitizationWhitelist;
  13068. };
  13069. /**
  13070. * @description
  13071. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  13072. * urls during img[src] sanitization.
  13073. *
  13074. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  13075. *
  13076. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  13077. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  13078. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  13079. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  13080. *
  13081. * @param {RegExp=} regexp New regexp to whitelist urls with.
  13082. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  13083. * chaining otherwise.
  13084. */
  13085. this.imgSrcSanitizationWhitelist = function(regexp) {
  13086. if (isDefined(regexp)) {
  13087. imgSrcSanitizationWhitelist = regexp;
  13088. return this;
  13089. }
  13090. return imgSrcSanitizationWhitelist;
  13091. };
  13092. this.$get = function() {
  13093. return function sanitizeUri(uri, isImage) {
  13094. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  13095. var normalizedVal;
  13096. normalizedVal = urlResolve(uri).href;
  13097. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  13098. return 'unsafe:'+normalizedVal;
  13099. }
  13100. return uri;
  13101. };
  13102. };
  13103. }
  13104. var $sceMinErr = minErr('$sce');
  13105. var SCE_CONTEXTS = {
  13106. HTML: 'html',
  13107. CSS: 'css',
  13108. URL: 'url',
  13109. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  13110. // url. (e.g. ng-include, script src, templateUrl)
  13111. RESOURCE_URL: 'resourceUrl',
  13112. JS: 'js'
  13113. };
  13114. // Helper functions follow.
  13115. // Copied from:
  13116. // http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
  13117. // Prereq: s is a string.
  13118. function escapeForRegexp(s) {
  13119. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  13120. replace(/\x08/g, '\\x08');
  13121. }
  13122. function adjustMatcher(matcher) {
  13123. if (matcher === 'self') {
  13124. return matcher;
  13125. } else if (isString(matcher)) {
  13126. // Strings match exactly except for 2 wildcards - '*' and '**'.
  13127. // '*' matches any character except those from the set ':/.?&'.
  13128. // '**' matches any character (like .* in a RegExp).
  13129. // More than 2 *'s raises an error as it's ill defined.
  13130. if (matcher.indexOf('***') > -1) {
  13131. throw $sceMinErr('iwcard',
  13132. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  13133. }
  13134. matcher = escapeForRegexp(matcher).
  13135. replace('\\*\\*', '.*').
  13136. replace('\\*', '[^:/.?&;]*');
  13137. return new RegExp('^' + matcher + '$');
  13138. } else if (isRegExp(matcher)) {
  13139. // The only other type of matcher allowed is a Regexp.
  13140. // Match entire URL / disallow partial matches.
  13141. // Flags are reset (i.e. no global, ignoreCase or multiline)
  13142. return new RegExp('^' + matcher.source + '$');
  13143. } else {
  13144. throw $sceMinErr('imatcher',
  13145. 'Matchers may only be "self", string patterns or RegExp objects');
  13146. }
  13147. }
  13148. function adjustMatchers(matchers) {
  13149. var adjustedMatchers = [];
  13150. if (isDefined(matchers)) {
  13151. forEach(matchers, function(matcher) {
  13152. adjustedMatchers.push(adjustMatcher(matcher));
  13153. });
  13154. }
  13155. return adjustedMatchers;
  13156. }
  13157. /**
  13158. * @ngdoc service
  13159. * @name $sceDelegate
  13160. * @kind function
  13161. *
  13162. * @description
  13163. *
  13164. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  13165. * Contextual Escaping (SCE)} services to AngularJS.
  13166. *
  13167. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  13168. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  13169. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  13170. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  13171. * work because `$sce` delegates to `$sceDelegate` for these operations.
  13172. *
  13173. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  13174. *
  13175. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  13176. * can override it completely to change the behavior of `$sce`, the common case would
  13177. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  13178. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  13179. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  13180. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  13181. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13182. */
  13183. /**
  13184. * @ngdoc provider
  13185. * @name $sceDelegateProvider
  13186. * @description
  13187. *
  13188. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  13189. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  13190. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  13191. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  13192. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  13193. *
  13194. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  13195. * Strict Contextual Escaping (SCE)}.
  13196. *
  13197. * **Example**: Consider the following case. <a name="example"></a>
  13198. *
  13199. * - your app is hosted at url `http://myapp.example.com/`
  13200. * - but some of your templates are hosted on other domains you control such as
  13201. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  13202. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  13203. *
  13204. * Here is what a secure configuration for this scenario might look like:
  13205. *
  13206. * ```
  13207. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  13208. * $sceDelegateProvider.resourceUrlWhitelist([
  13209. * // Allow same origin resource loads.
  13210. * 'self',
  13211. * // Allow loading from our assets domain. Notice the difference between * and **.
  13212. * 'http://srv*.assets.example.com/**'
  13213. * ]);
  13214. *
  13215. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  13216. * $sceDelegateProvider.resourceUrlBlacklist([
  13217. * 'http://myapp.example.com/clickThru**'
  13218. * ]);
  13219. * });
  13220. * ```
  13221. */
  13222. function $SceDelegateProvider() {
  13223. this.SCE_CONTEXTS = SCE_CONTEXTS;
  13224. // Resource URLs can also be trusted by policy.
  13225. var resourceUrlWhitelist = ['self'],
  13226. resourceUrlBlacklist = [];
  13227. /**
  13228. * @ngdoc method
  13229. * @name $sceDelegateProvider#resourceUrlWhitelist
  13230. * @kind function
  13231. *
  13232. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  13233. * provided. This must be an array or null. A snapshot of this array is used so further
  13234. * changes to the array are ignored.
  13235. *
  13236. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13237. * allowed in this array.
  13238. *
  13239. * Note: **an empty whitelist array will block all URLs**!
  13240. *
  13241. * @return {Array} the currently set whitelist array.
  13242. *
  13243. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  13244. * same origin resource requests.
  13245. *
  13246. * @description
  13247. * Sets/Gets the whitelist of trusted resource URLs.
  13248. */
  13249. this.resourceUrlWhitelist = function (value) {
  13250. if (arguments.length) {
  13251. resourceUrlWhitelist = adjustMatchers(value);
  13252. }
  13253. return resourceUrlWhitelist;
  13254. };
  13255. /**
  13256. * @ngdoc method
  13257. * @name $sceDelegateProvider#resourceUrlBlacklist
  13258. * @kind function
  13259. *
  13260. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  13261. * provided. This must be an array or null. A snapshot of this array is used so further
  13262. * changes to the array are ignored.
  13263. *
  13264. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  13265. * allowed in this array.
  13266. *
  13267. * The typical usage for the blacklist is to **block
  13268. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  13269. * these would otherwise be trusted but actually return content from the redirected domain.
  13270. *
  13271. * Finally, **the blacklist overrides the whitelist** and has the final say.
  13272. *
  13273. * @return {Array} the currently set blacklist array.
  13274. *
  13275. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  13276. * is no blacklist.)
  13277. *
  13278. * @description
  13279. * Sets/Gets the blacklist of trusted resource URLs.
  13280. */
  13281. this.resourceUrlBlacklist = function (value) {
  13282. if (arguments.length) {
  13283. resourceUrlBlacklist = adjustMatchers(value);
  13284. }
  13285. return resourceUrlBlacklist;
  13286. };
  13287. this.$get = ['$injector', function($injector) {
  13288. var htmlSanitizer = function htmlSanitizer(html) {
  13289. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13290. };
  13291. if ($injector.has('$sanitize')) {
  13292. htmlSanitizer = $injector.get('$sanitize');
  13293. }
  13294. function matchUrl(matcher, parsedUrl) {
  13295. if (matcher === 'self') {
  13296. return urlIsSameOrigin(parsedUrl);
  13297. } else {
  13298. // definitely a regex. See adjustMatchers()
  13299. return !!matcher.exec(parsedUrl.href);
  13300. }
  13301. }
  13302. function isResourceUrlAllowedByPolicy(url) {
  13303. var parsedUrl = urlResolve(url.toString());
  13304. var i, n, allowed = false;
  13305. // Ensure that at least one item from the whitelist allows this url.
  13306. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  13307. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  13308. allowed = true;
  13309. break;
  13310. }
  13311. }
  13312. if (allowed) {
  13313. // Ensure that no item from the blacklist blocked this url.
  13314. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  13315. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  13316. allowed = false;
  13317. break;
  13318. }
  13319. }
  13320. }
  13321. return allowed;
  13322. }
  13323. function generateHolderType(Base) {
  13324. var holderType = function TrustedValueHolderType(trustedValue) {
  13325. this.$$unwrapTrustedValue = function() {
  13326. return trustedValue;
  13327. };
  13328. };
  13329. if (Base) {
  13330. holderType.prototype = new Base();
  13331. }
  13332. holderType.prototype.valueOf = function sceValueOf() {
  13333. return this.$$unwrapTrustedValue();
  13334. };
  13335. holderType.prototype.toString = function sceToString() {
  13336. return this.$$unwrapTrustedValue().toString();
  13337. };
  13338. return holderType;
  13339. }
  13340. var trustedValueHolderBase = generateHolderType(),
  13341. byType = {};
  13342. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  13343. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  13344. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  13345. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  13346. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  13347. /**
  13348. * @ngdoc method
  13349. * @name $sceDelegate#trustAs
  13350. *
  13351. * @description
  13352. * Returns an object that is trusted by angular for use in specified strict
  13353. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  13354. * attribute interpolation, any dom event binding attribute interpolation
  13355. * such as for onclick, etc.) that uses the provided value.
  13356. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  13357. *
  13358. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13359. * resourceUrl, html, js and css.
  13360. * @param {*} value The value that that should be considered trusted/safe.
  13361. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13362. * where Angular expects a $sce.trustAs() return value.
  13363. */
  13364. function trustAs(type, trustedValue) {
  13365. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13366. if (!Constructor) {
  13367. throw $sceMinErr('icontext',
  13368. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  13369. type, trustedValue);
  13370. }
  13371. if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
  13372. return trustedValue;
  13373. }
  13374. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  13375. // mutable objects, we ensure here that the value passed in is actually a string.
  13376. if (typeof trustedValue !== 'string') {
  13377. throw $sceMinErr('itype',
  13378. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  13379. type);
  13380. }
  13381. return new Constructor(trustedValue);
  13382. }
  13383. /**
  13384. * @ngdoc method
  13385. * @name $sceDelegate#valueOf
  13386. *
  13387. * @description
  13388. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  13389. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  13390. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  13391. *
  13392. * If the passed parameter is not a value that had been returned by {@link
  13393. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  13394. *
  13395. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  13396. * call or anything else.
  13397. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  13398. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  13399. * `value` unchanged.
  13400. */
  13401. function valueOf(maybeTrusted) {
  13402. if (maybeTrusted instanceof trustedValueHolderBase) {
  13403. return maybeTrusted.$$unwrapTrustedValue();
  13404. } else {
  13405. return maybeTrusted;
  13406. }
  13407. }
  13408. /**
  13409. * @ngdoc method
  13410. * @name $sceDelegate#getTrusted
  13411. *
  13412. * @description
  13413. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  13414. * returns the originally supplied value if the queried context type is a supertype of the
  13415. * created type. If this condition isn't satisfied, throws an exception.
  13416. *
  13417. * @param {string} type The kind of context in which this value is to be used.
  13418. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  13419. * `$sceDelegate.trustAs`} call.
  13420. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  13421. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  13422. */
  13423. function getTrusted(type, maybeTrusted) {
  13424. if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
  13425. return maybeTrusted;
  13426. }
  13427. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  13428. if (constructor && maybeTrusted instanceof constructor) {
  13429. return maybeTrusted.$$unwrapTrustedValue();
  13430. }
  13431. // If we get here, then we may only take one of two actions.
  13432. // 1. sanitize the value for the requested type, or
  13433. // 2. throw an exception.
  13434. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  13435. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  13436. return maybeTrusted;
  13437. } else {
  13438. throw $sceMinErr('insecurl',
  13439. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  13440. maybeTrusted.toString());
  13441. }
  13442. } else if (type === SCE_CONTEXTS.HTML) {
  13443. return htmlSanitizer(maybeTrusted);
  13444. }
  13445. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  13446. }
  13447. return { trustAs: trustAs,
  13448. getTrusted: getTrusted,
  13449. valueOf: valueOf };
  13450. }];
  13451. }
  13452. /**
  13453. * @ngdoc provider
  13454. * @name $sceProvider
  13455. * @description
  13456. *
  13457. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  13458. * - enable/disable Strict Contextual Escaping (SCE) in a module
  13459. * - override the default implementation with a custom delegate
  13460. *
  13461. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  13462. */
  13463. /* jshint maxlen: false*/
  13464. /**
  13465. * @ngdoc service
  13466. * @name $sce
  13467. * @kind function
  13468. *
  13469. * @description
  13470. *
  13471. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  13472. *
  13473. * # Strict Contextual Escaping
  13474. *
  13475. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  13476. * contexts to result in a value that is marked as safe to use for that context. One example of
  13477. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  13478. * to these contexts as privileged or SCE contexts.
  13479. *
  13480. * As of version 1.2, Angular ships with SCE enabled by default.
  13481. *
  13482. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  13483. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  13484. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  13485. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  13486. * to the top of your HTML document.
  13487. *
  13488. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  13489. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  13490. *
  13491. * Here's an example of a binding in a privileged context:
  13492. *
  13493. * ```
  13494. * <input ng-model="userHtml">
  13495. * <div ng-bind-html="userHtml"></div>
  13496. * ```
  13497. *
  13498. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  13499. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  13500. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  13501. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  13502. * security vulnerabilities.)
  13503. *
  13504. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  13505. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  13506. *
  13507. * How would you ensure that every place that used these types of bindings was bound to a value that
  13508. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  13509. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  13510. * properties/fields and forgot to update the binding to the sanitized value?
  13511. *
  13512. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  13513. * determine that something explicitly says it's safe to use a value for binding in that
  13514. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  13515. * for those values that you can easily tell are safe - because they were received from your server,
  13516. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  13517. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  13518. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  13519. *
  13520. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  13521. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  13522. * obtain values that will be accepted by SCE / privileged contexts.
  13523. *
  13524. *
  13525. * ## How does it work?
  13526. *
  13527. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  13528. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  13529. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  13530. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  13531. *
  13532. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  13533. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  13534. * simplified):
  13535. *
  13536. * ```
  13537. * var ngBindHtmlDirective = ['$sce', function($sce) {
  13538. * return function(scope, element, attr) {
  13539. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  13540. * element.html(value || '');
  13541. * });
  13542. * };
  13543. * }];
  13544. * ```
  13545. *
  13546. * ## Impact on loading templates
  13547. *
  13548. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  13549. * `templateUrl`'s specified by {@link guide/directive directives}.
  13550. *
  13551. * By default, Angular only loads templates from the same domain and protocol as the application
  13552. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  13553. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  13554. * protocols, you may either either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  13555. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  13556. *
  13557. * *Please note*:
  13558. * The browser's
  13559. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  13560. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  13561. * policy apply in addition to this and may further restrict whether the template is successfully
  13562. * loaded. This means that without the right CORS policy, loading templates from a different domain
  13563. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  13564. * browsers.
  13565. *
  13566. * ## This feels like too much overhead
  13567. *
  13568. * It's important to remember that SCE only applies to interpolation expressions.
  13569. *
  13570. * If your expressions are constant literals, they're automatically trusted and you don't need to
  13571. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  13572. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  13573. *
  13574. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  13575. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  13576. *
  13577. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  13578. * templates in `ng-include` from your application's domain without having to even know about SCE.
  13579. * It blocks loading templates from other domains or loading templates over http from an https
  13580. * served document. You can change these by setting your own custom {@link
  13581. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  13582. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  13583. *
  13584. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  13585. * application that's secure and can be audited to verify that with much more ease than bolting
  13586. * security onto an application later.
  13587. *
  13588. * <a name="contexts"></a>
  13589. * ## What trusted context types are supported?
  13590. *
  13591. * | Context | Notes |
  13592. * |---------------------|----------------|
  13593. * | `$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. |
  13594. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  13595. * | `$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. |
  13596. * | `$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. |
  13597. * | `$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. |
  13598. *
  13599. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  13600. *
  13601. * Each element in these arrays must be one of the following:
  13602. *
  13603. * - **'self'**
  13604. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  13605. * domain** as the application document using the **same protocol**.
  13606. * - **String** (except the special value `'self'`)
  13607. * - The string is matched against the full *normalized / absolute URL* of the resource
  13608. * being tested (substring matches are not good enough.)
  13609. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  13610. * match themselves.
  13611. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  13612. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
  13613. * in a whitelist.
  13614. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  13615. * not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
  13616. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  13617. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  13618. * http://foo.example.com/templates/**).
  13619. * - **RegExp** (*see caveat below*)
  13620. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  13621. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  13622. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  13623. * have good test coverage.). For instance, the use of `.` in the regex is correct only in a
  13624. * small number of cases. A `.` character in the regex used when matching the scheme or a
  13625. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  13626. * is highly recommended to use the string patterns and only fall back to regular expressions
  13627. * if they as a last resort.
  13628. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  13629. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  13630. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  13631. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  13632. * - If you are generating your JavaScript from some other templating engine (not
  13633. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  13634. * remember to escape your regular expression (and be aware that you might need more than
  13635. * one level of escaping depending on your templating engine and the way you interpolated
  13636. * the value.) Do make use of your platform's escaping mechanism as it might be good
  13637. * enough before coding your own. e.g. Ruby has
  13638. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  13639. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  13640. * Javascript lacks a similar built in function for escaping. Take a look at Google
  13641. * Closure library's [goog.string.regExpEscape(s)](
  13642. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  13643. *
  13644. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  13645. *
  13646. * ## Show me an example using SCE.
  13647. *
  13648. * <example module="mySceApp" deps="angular-sanitize.js">
  13649. * <file name="index.html">
  13650. * <div ng-controller="AppController as myCtrl">
  13651. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  13652. * <b>User comments</b><br>
  13653. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  13654. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  13655. * exploit.
  13656. * <div class="well">
  13657. * <div ng-repeat="userComment in myCtrl.userComments">
  13658. * <b>{{userComment.name}}</b>:
  13659. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  13660. * <br>
  13661. * </div>
  13662. * </div>
  13663. * </div>
  13664. * </file>
  13665. *
  13666. * <file name="script.js">
  13667. * angular.module('mySceApp', ['ngSanitize'])
  13668. * .controller('AppController', ['$http', '$templateCache', '$sce',
  13669. * function($http, $templateCache, $sce) {
  13670. * var self = this;
  13671. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  13672. * self.userComments = userComments;
  13673. * });
  13674. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  13675. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13676. * 'sanitization.&quot;">Hover over this text.</span>');
  13677. * }]);
  13678. * </file>
  13679. *
  13680. * <file name="test_data.json">
  13681. * [
  13682. * { "name": "Alice",
  13683. * "htmlComment":
  13684. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  13685. * },
  13686. * { "name": "Bob",
  13687. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  13688. * }
  13689. * ]
  13690. * </file>
  13691. *
  13692. * <file name="protractor.js" type="protractor">
  13693. * describe('SCE doc demo', function() {
  13694. * it('should sanitize untrusted values', function() {
  13695. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  13696. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  13697. * });
  13698. *
  13699. * it('should NOT sanitize explicitly trusted values', function() {
  13700. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  13701. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  13702. * 'sanitization.&quot;">Hover over this text.</span>');
  13703. * });
  13704. * });
  13705. * </file>
  13706. * </example>
  13707. *
  13708. *
  13709. *
  13710. * ## Can I disable SCE completely?
  13711. *
  13712. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  13713. * for little coding overhead. It will be much harder to take an SCE disabled application and
  13714. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  13715. * for cases where you have a lot of existing code that was written before SCE was introduced and
  13716. * you're migrating them a module at a time.
  13717. *
  13718. * That said, here's how you can completely disable SCE:
  13719. *
  13720. * ```
  13721. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  13722. * // Completely disable SCE. For demonstration purposes only!
  13723. * // Do not use in new projects.
  13724. * $sceProvider.enabled(false);
  13725. * });
  13726. * ```
  13727. *
  13728. */
  13729. /* jshint maxlen: 100 */
  13730. function $SceProvider() {
  13731. var enabled = true;
  13732. /**
  13733. * @ngdoc method
  13734. * @name $sceProvider#enabled
  13735. * @kind function
  13736. *
  13737. * @param {boolean=} value If provided, then enables/disables SCE.
  13738. * @return {boolean} true if SCE is enabled, false otherwise.
  13739. *
  13740. * @description
  13741. * Enables/disables SCE and returns the current value.
  13742. */
  13743. this.enabled = function (value) {
  13744. if (arguments.length) {
  13745. enabled = !!value;
  13746. }
  13747. return enabled;
  13748. };
  13749. /* Design notes on the default implementation for SCE.
  13750. *
  13751. * The API contract for the SCE delegate
  13752. * -------------------------------------
  13753. * The SCE delegate object must provide the following 3 methods:
  13754. *
  13755. * - trustAs(contextEnum, value)
  13756. * This method is used to tell the SCE service that the provided value is OK to use in the
  13757. * contexts specified by contextEnum. It must return an object that will be accepted by
  13758. * getTrusted() for a compatible contextEnum and return this value.
  13759. *
  13760. * - valueOf(value)
  13761. * For values that were not produced by trustAs(), return them as is. For values that were
  13762. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  13763. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  13764. * such a value.
  13765. *
  13766. * - getTrusted(contextEnum, value)
  13767. * This function should return the a value that is safe to use in the context specified by
  13768. * contextEnum or throw and exception otherwise.
  13769. *
  13770. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  13771. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  13772. * instance, an implementation could maintain a registry of all trusted objects by context. In
  13773. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  13774. * return the same object passed in if it was found in the registry under a compatible context or
  13775. * throw an exception otherwise. An implementation might only wrap values some of the time based
  13776. * on some criteria. getTrusted() might return a value and not throw an exception for special
  13777. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  13778. *
  13779. *
  13780. * A note on the inheritance model for SCE contexts
  13781. * ------------------------------------------------
  13782. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  13783. * is purely an implementation details.
  13784. *
  13785. * The contract is simply this:
  13786. *
  13787. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  13788. * will also succeed.
  13789. *
  13790. * Inheritance happens to capture this in a natural way. In some future, we
  13791. * may not use inheritance anymore. That is OK because no code outside of
  13792. * sce.js and sceSpecs.js would need to be aware of this detail.
  13793. */
  13794. this.$get = ['$document', '$parse', '$sceDelegate', function(
  13795. $document, $parse, $sceDelegate) {
  13796. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  13797. // the "expression(javascript expression)" syntax which is insecure.
  13798. if (enabled && $document[0].documentMode < 8) {
  13799. throw $sceMinErr('iequirks',
  13800. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  13801. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  13802. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  13803. }
  13804. var sce = shallowCopy(SCE_CONTEXTS);
  13805. /**
  13806. * @ngdoc method
  13807. * @name $sce#isEnabled
  13808. * @kind function
  13809. *
  13810. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  13811. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  13812. *
  13813. * @description
  13814. * Returns a boolean indicating if SCE is enabled.
  13815. */
  13816. sce.isEnabled = function () {
  13817. return enabled;
  13818. };
  13819. sce.trustAs = $sceDelegate.trustAs;
  13820. sce.getTrusted = $sceDelegate.getTrusted;
  13821. sce.valueOf = $sceDelegate.valueOf;
  13822. if (!enabled) {
  13823. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  13824. sce.valueOf = identity;
  13825. }
  13826. /**
  13827. * @ngdoc method
  13828. * @name $sce#parseAs
  13829. *
  13830. * @description
  13831. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  13832. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  13833. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  13834. * *result*)}
  13835. *
  13836. * @param {string} type The kind of SCE context in which this result will be used.
  13837. * @param {string} expression String expression to compile.
  13838. * @returns {function(context, locals)} a function which represents the compiled expression:
  13839. *
  13840. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  13841. * are evaluated against (typically a scope object).
  13842. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  13843. * `context`.
  13844. */
  13845. sce.parseAs = function sceParseAs(type, expr) {
  13846. var parsed = $parse(expr);
  13847. if (parsed.literal && parsed.constant) {
  13848. return parsed;
  13849. } else {
  13850. return $parse(expr, function (value) {
  13851. return sce.getTrusted(type, value);
  13852. });
  13853. }
  13854. };
  13855. /**
  13856. * @ngdoc method
  13857. * @name $sce#trustAs
  13858. *
  13859. * @description
  13860. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  13861. * returns an object that is trusted by angular for use in specified strict contextual
  13862. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  13863. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  13864. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  13865. * escaping.
  13866. *
  13867. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  13868. * resource_url, html, js and css.
  13869. * @param {*} value The value that that should be considered trusted/safe.
  13870. * @returns {*} A value that can be used to stand in for the provided `value` in places
  13871. * where Angular expects a $sce.trustAs() return value.
  13872. */
  13873. /**
  13874. * @ngdoc method
  13875. * @name $sce#trustAsHtml
  13876. *
  13877. * @description
  13878. * Shorthand method. `$sce.trustAsHtml(value)` →
  13879. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  13880. *
  13881. * @param {*} value The value to trustAs.
  13882. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  13883. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  13884. * only accept expressions that are either literal constants or are the
  13885. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  13886. */
  13887. /**
  13888. * @ngdoc method
  13889. * @name $sce#trustAsUrl
  13890. *
  13891. * @description
  13892. * Shorthand method. `$sce.trustAsUrl(value)` →
  13893. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  13894. *
  13895. * @param {*} value The value to trustAs.
  13896. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  13897. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  13898. * only accept expressions that are either literal constants or are the
  13899. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  13900. */
  13901. /**
  13902. * @ngdoc method
  13903. * @name $sce#trustAsResourceUrl
  13904. *
  13905. * @description
  13906. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  13907. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  13908. *
  13909. * @param {*} value The value to trustAs.
  13910. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  13911. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  13912. * only accept expressions that are either literal constants or are the return
  13913. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  13914. */
  13915. /**
  13916. * @ngdoc method
  13917. * @name $sce#trustAsJs
  13918. *
  13919. * @description
  13920. * Shorthand method. `$sce.trustAsJs(value)` →
  13921. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  13922. *
  13923. * @param {*} value The value to trustAs.
  13924. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  13925. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  13926. * only accept expressions that are either literal constants or are the
  13927. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  13928. */
  13929. /**
  13930. * @ngdoc method
  13931. * @name $sce#getTrusted
  13932. *
  13933. * @description
  13934. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  13935. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  13936. * originally supplied value if the queried context type is a supertype of the created type.
  13937. * If this condition isn't satisfied, throws an exception.
  13938. *
  13939. * @param {string} type The kind of context in which this value is to be used.
  13940. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  13941. * call.
  13942. * @returns {*} The value the was originally provided to
  13943. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  13944. * Otherwise, throws an exception.
  13945. */
  13946. /**
  13947. * @ngdoc method
  13948. * @name $sce#getTrustedHtml
  13949. *
  13950. * @description
  13951. * Shorthand method. `$sce.getTrustedHtml(value)` →
  13952. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  13953. *
  13954. * @param {*} value The value to pass to `$sce.getTrusted`.
  13955. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  13956. */
  13957. /**
  13958. * @ngdoc method
  13959. * @name $sce#getTrustedCss
  13960. *
  13961. * @description
  13962. * Shorthand method. `$sce.getTrustedCss(value)` →
  13963. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  13964. *
  13965. * @param {*} value The value to pass to `$sce.getTrusted`.
  13966. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  13967. */
  13968. /**
  13969. * @ngdoc method
  13970. * @name $sce#getTrustedUrl
  13971. *
  13972. * @description
  13973. * Shorthand method. `$sce.getTrustedUrl(value)` →
  13974. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  13975. *
  13976. * @param {*} value The value to pass to `$sce.getTrusted`.
  13977. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  13978. */
  13979. /**
  13980. * @ngdoc method
  13981. * @name $sce#getTrustedResourceUrl
  13982. *
  13983. * @description
  13984. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  13985. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  13986. *
  13987. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  13988. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  13989. */
  13990. /**
  13991. * @ngdoc method
  13992. * @name $sce#getTrustedJs
  13993. *
  13994. * @description
  13995. * Shorthand method. `$sce.getTrustedJs(value)` →
  13996. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  13997. *
  13998. * @param {*} value The value to pass to `$sce.getTrusted`.
  13999. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  14000. */
  14001. /**
  14002. * @ngdoc method
  14003. * @name $sce#parseAsHtml
  14004. *
  14005. * @description
  14006. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  14007. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  14008. *
  14009. * @param {string} expression String expression to compile.
  14010. * @returns {function(context, locals)} a function which represents the compiled expression:
  14011. *
  14012. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14013. * are evaluated against (typically a scope object).
  14014. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14015. * `context`.
  14016. */
  14017. /**
  14018. * @ngdoc method
  14019. * @name $sce#parseAsCss
  14020. *
  14021. * @description
  14022. * Shorthand method. `$sce.parseAsCss(value)` →
  14023. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  14024. *
  14025. * @param {string} expression String expression to compile.
  14026. * @returns {function(context, locals)} a function which represents the compiled expression:
  14027. *
  14028. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14029. * are evaluated against (typically a scope object).
  14030. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14031. * `context`.
  14032. */
  14033. /**
  14034. * @ngdoc method
  14035. * @name $sce#parseAsUrl
  14036. *
  14037. * @description
  14038. * Shorthand method. `$sce.parseAsUrl(value)` →
  14039. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  14040. *
  14041. * @param {string} expression String expression to compile.
  14042. * @returns {function(context, locals)} a function which represents the compiled expression:
  14043. *
  14044. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14045. * are evaluated against (typically a scope object).
  14046. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14047. * `context`.
  14048. */
  14049. /**
  14050. * @ngdoc method
  14051. * @name $sce#parseAsResourceUrl
  14052. *
  14053. * @description
  14054. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  14055. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  14056. *
  14057. * @param {string} expression String expression to compile.
  14058. * @returns {function(context, locals)} a function which represents the compiled expression:
  14059. *
  14060. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14061. * are evaluated against (typically a scope object).
  14062. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14063. * `context`.
  14064. */
  14065. /**
  14066. * @ngdoc method
  14067. * @name $sce#parseAsJs
  14068. *
  14069. * @description
  14070. * Shorthand method. `$sce.parseAsJs(value)` →
  14071. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  14072. *
  14073. * @param {string} expression String expression to compile.
  14074. * @returns {function(context, locals)} a function which represents the compiled expression:
  14075. *
  14076. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  14077. * are evaluated against (typically a scope object).
  14078. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  14079. * `context`.
  14080. */
  14081. // Shorthand delegations.
  14082. var parse = sce.parseAs,
  14083. getTrusted = sce.getTrusted,
  14084. trustAs = sce.trustAs;
  14085. forEach(SCE_CONTEXTS, function (enumValue, name) {
  14086. var lName = lowercase(name);
  14087. sce[camelCase("parse_as_" + lName)] = function (expr) {
  14088. return parse(enumValue, expr);
  14089. };
  14090. sce[camelCase("get_trusted_" + lName)] = function (value) {
  14091. return getTrusted(enumValue, value);
  14092. };
  14093. sce[camelCase("trust_as_" + lName)] = function (value) {
  14094. return trustAs(enumValue, value);
  14095. };
  14096. });
  14097. return sce;
  14098. }];
  14099. }
  14100. /**
  14101. * !!! This is an undocumented "private" service !!!
  14102. *
  14103. * @name $sniffer
  14104. * @requires $window
  14105. * @requires $document
  14106. *
  14107. * @property {boolean} history Does the browser support html5 history api ?
  14108. * @property {boolean} transitions Does the browser support CSS transition events ?
  14109. * @property {boolean} animations Does the browser support CSS animation events ?
  14110. *
  14111. * @description
  14112. * This is very simple implementation of testing browser's features.
  14113. */
  14114. function $SnifferProvider() {
  14115. this.$get = ['$window', '$document', function($window, $document) {
  14116. var eventSupport = {},
  14117. android =
  14118. int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  14119. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  14120. document = $document[0] || {},
  14121. vendorPrefix,
  14122. vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
  14123. bodyStyle = document.body && document.body.style,
  14124. transitions = false,
  14125. animations = false,
  14126. match;
  14127. if (bodyStyle) {
  14128. for(var prop in bodyStyle) {
  14129. if(match = vendorRegex.exec(prop)) {
  14130. vendorPrefix = match[0];
  14131. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  14132. break;
  14133. }
  14134. }
  14135. if(!vendorPrefix) {
  14136. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  14137. }
  14138. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  14139. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  14140. if (android && (!transitions||!animations)) {
  14141. transitions = isString(document.body.style.webkitTransition);
  14142. animations = isString(document.body.style.webkitAnimation);
  14143. }
  14144. }
  14145. return {
  14146. // Android has history.pushState, but it does not update location correctly
  14147. // so let's not use the history API at all.
  14148. // http://code.google.com/p/android/issues/detail?id=17471
  14149. // https://github.com/angular/angular.js/issues/904
  14150. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  14151. // so let's not use the history API also
  14152. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  14153. // jshint -W018
  14154. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  14155. // jshint +W018
  14156. hasEvent: function(event) {
  14157. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  14158. // it. In particular the event is not fired when backspace or delete key are pressed or
  14159. // when cut operation is performed.
  14160. if (event == 'input' && msie == 9) return false;
  14161. if (isUndefined(eventSupport[event])) {
  14162. var divElm = document.createElement('div');
  14163. eventSupport[event] = 'on' + event in divElm;
  14164. }
  14165. return eventSupport[event];
  14166. },
  14167. csp: csp(),
  14168. vendorPrefix: vendorPrefix,
  14169. transitions : transitions,
  14170. animations : animations,
  14171. android: android
  14172. };
  14173. }];
  14174. }
  14175. var $compileMinErr = minErr('$compile');
  14176. /**
  14177. * @ngdoc service
  14178. * @name $templateRequest
  14179. *
  14180. * @description
  14181. * The `$templateRequest` service downloads the provided template using `$http` and, upon success,
  14182. * stores the contents inside of `$templateCache`. If the HTTP request fails or the response data
  14183. * of the HTTP request is empty then a `$compile` error will be thrown (the exception can be thwarted
  14184. * by setting the 2nd parameter of the function to true).
  14185. *
  14186. * @param {string} tpl The HTTP request template URL
  14187. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  14188. *
  14189. * @return {Promise} the HTTP Promise for the given.
  14190. *
  14191. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  14192. */
  14193. function $TemplateRequestProvider() {
  14194. this.$get = ['$templateCache', '$http', '$q', function($templateCache, $http, $q) {
  14195. function handleRequestFn(tpl, ignoreRequestError) {
  14196. var self = handleRequestFn;
  14197. self.totalPendingRequests++;
  14198. return $http.get(tpl, { cache : $templateCache })
  14199. .then(function(response) {
  14200. var html = response.data;
  14201. if(!html || html.length === 0) {
  14202. return handleError();
  14203. }
  14204. self.totalPendingRequests--;
  14205. $templateCache.put(tpl, html);
  14206. return html;
  14207. }, handleError);
  14208. function handleError() {
  14209. self.totalPendingRequests--;
  14210. if (!ignoreRequestError) {
  14211. throw $compileMinErr('tpload', 'Failed to load template: {0}', tpl);
  14212. }
  14213. return $q.reject();
  14214. }
  14215. }
  14216. handleRequestFn.totalPendingRequests = 0;
  14217. return handleRequestFn;
  14218. }];
  14219. }
  14220. function $$TestabilityProvider() {
  14221. this.$get = ['$rootScope', '$browser', '$location',
  14222. function($rootScope, $browser, $location) {
  14223. /**
  14224. * @name $testability
  14225. *
  14226. * @description
  14227. * The private $$testability service provides a collection of methods for use when debugging
  14228. * or by automated test and debugging tools.
  14229. */
  14230. var testability = {};
  14231. /**
  14232. * @name $$testability#findBindings
  14233. *
  14234. * @description
  14235. * Returns an array of elements that are bound (via ng-bind or {{}})
  14236. * to expressions matching the input.
  14237. *
  14238. * @param {Element} element The element root to search from.
  14239. * @param {string} expression The binding expression to match.
  14240. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14241. * for the expression. Filters and whitespace are ignored.
  14242. */
  14243. testability.findBindings = function(element, expression, opt_exactMatch) {
  14244. var bindings = element.getElementsByClassName('ng-binding');
  14245. var matches = [];
  14246. forEach(bindings, function(binding) {
  14247. var dataBinding = angular.element(binding).data('$binding');
  14248. if (dataBinding) {
  14249. forEach(dataBinding, function(bindingName) {
  14250. if (opt_exactMatch) {
  14251. var matcher = new RegExp('(^|\\s)' + expression + '(\\s|\\||$)');
  14252. if (matcher.test(bindingName)) {
  14253. matches.push(binding);
  14254. }
  14255. } else {
  14256. if (bindingName.indexOf(expression) != -1) {
  14257. matches.push(binding);
  14258. }
  14259. }
  14260. });
  14261. }
  14262. });
  14263. return matches;
  14264. };
  14265. /**
  14266. * @name $$testability#findModels
  14267. *
  14268. * @description
  14269. * Returns an array of elements that are two-way found via ng-model to
  14270. * expressions matching the input.
  14271. *
  14272. * @param {Element} element The element root to search from.
  14273. * @param {string} expression The model expression to match.
  14274. * @param {boolean} opt_exactMatch If true, only returns exact matches
  14275. * for the expression.
  14276. */
  14277. testability.findModels = function(element, expression, opt_exactMatch) {
  14278. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  14279. for (var p = 0; p < prefixes.length; ++p) {
  14280. var attributeEquals = opt_exactMatch ? '=' : '*=';
  14281. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  14282. var elements = element.querySelectorAll(selector);
  14283. if (elements.length) {
  14284. return elements;
  14285. }
  14286. }
  14287. };
  14288. /**
  14289. * @name $$testability#getLocation
  14290. *
  14291. * @description
  14292. * Shortcut for getting the location in a browser agnostic way. Returns
  14293. * the path, search, and hash. (e.g. /path?a=b#hash)
  14294. */
  14295. testability.getLocation = function() {
  14296. return $location.url();
  14297. };
  14298. /**
  14299. * @name $$testability#setLocation
  14300. *
  14301. * @description
  14302. * Shortcut for navigating to a location without doing a full page reload.
  14303. *
  14304. * @param {string} url The location url (path, search and hash,
  14305. * e.g. /path?a=b#hash) to go to.
  14306. */
  14307. testability.setLocation = function(url) {
  14308. if (url !== $location.url()) {
  14309. $location.url(url);
  14310. $rootScope.$digest();
  14311. }
  14312. };
  14313. /**
  14314. * @name $$testability#whenStable
  14315. *
  14316. * @description
  14317. * Calls the callback when $timeout and $http requests are completed.
  14318. *
  14319. * @param {function} callback
  14320. */
  14321. testability.whenStable = function(callback) {
  14322. $browser.notifyWhenNoOutstandingRequests(callback);
  14323. };
  14324. return testability;
  14325. }];
  14326. }
  14327. function $TimeoutProvider() {
  14328. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  14329. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  14330. var deferreds = {};
  14331. /**
  14332. * @ngdoc service
  14333. * @name $timeout
  14334. *
  14335. * @description
  14336. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  14337. * block and delegates any exceptions to
  14338. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14339. *
  14340. * The return value of registering a timeout function is a promise, which will be resolved when
  14341. * the timeout is reached and the timeout function is executed.
  14342. *
  14343. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  14344. *
  14345. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  14346. * synchronously flush the queue of deferred functions.
  14347. *
  14348. * @param {function()} fn A function, whose execution should be delayed.
  14349. * @param {number=} [delay=0] Delay in milliseconds.
  14350. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  14351. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  14352. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  14353. * promise will be resolved with is the return value of the `fn` function.
  14354. *
  14355. */
  14356. function timeout(fn, delay, invokeApply) {
  14357. var skipApply = (isDefined(invokeApply) && !invokeApply),
  14358. deferred = (skipApply ? $$q : $q).defer(),
  14359. promise = deferred.promise,
  14360. timeoutId;
  14361. timeoutId = $browser.defer(function() {
  14362. try {
  14363. deferred.resolve(fn());
  14364. } catch(e) {
  14365. deferred.reject(e);
  14366. $exceptionHandler(e);
  14367. }
  14368. finally {
  14369. delete deferreds[promise.$$timeoutId];
  14370. }
  14371. if (!skipApply) $rootScope.$apply();
  14372. }, delay);
  14373. promise.$$timeoutId = timeoutId;
  14374. deferreds[timeoutId] = deferred;
  14375. return promise;
  14376. }
  14377. /**
  14378. * @ngdoc method
  14379. * @name $timeout#cancel
  14380. *
  14381. * @description
  14382. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  14383. * resolved with a rejection.
  14384. *
  14385. * @param {Promise=} promise Promise returned by the `$timeout` function.
  14386. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  14387. * canceled.
  14388. */
  14389. timeout.cancel = function(promise) {
  14390. if (promise && promise.$$timeoutId in deferreds) {
  14391. deferreds[promise.$$timeoutId].reject('canceled');
  14392. delete deferreds[promise.$$timeoutId];
  14393. return $browser.defer.cancel(promise.$$timeoutId);
  14394. }
  14395. return false;
  14396. };
  14397. return timeout;
  14398. }];
  14399. }
  14400. // NOTE: The usage of window and document instead of $window and $document here is
  14401. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  14402. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  14403. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  14404. // doesn't know about mocked locations and resolves URLs to the real document - which is
  14405. // exactly the behavior needed here. There is little value is mocking these out for this
  14406. // service.
  14407. var urlParsingNode = document.createElement("a");
  14408. var originUrl = urlResolve(window.location.href, true);
  14409. /**
  14410. *
  14411. * Implementation Notes for non-IE browsers
  14412. * ----------------------------------------
  14413. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  14414. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  14415. * URL will be resolved into an absolute URL in the context of the application document.
  14416. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  14417. * properties are all populated to reflect the normalized URL. This approach has wide
  14418. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  14419. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14420. *
  14421. * Implementation Notes for IE
  14422. * ---------------------------
  14423. * IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
  14424. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  14425. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  14426. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  14427. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  14428. * properties such as protocol, hostname, port, etc.
  14429. *
  14430. * IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
  14431. * uses the inner HTML approach to assign the URL as part of an HTML snippet -
  14432. * http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
  14433. * Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
  14434. * Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
  14435. * method and IE < 8 is unsupported.
  14436. *
  14437. * References:
  14438. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  14439. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  14440. * http://url.spec.whatwg.org/#urlutils
  14441. * https://github.com/angular/angular.js/pull/2902
  14442. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  14443. *
  14444. * @kind function
  14445. * @param {string} url The URL to be parsed.
  14446. * @description Normalizes and parses a URL.
  14447. * @returns {object} Returns the normalized URL as a dictionary.
  14448. *
  14449. * | member name | Description |
  14450. * |---------------|----------------|
  14451. * | href | A normalized version of the provided URL if it was not an absolute URL |
  14452. * | protocol | The protocol including the trailing colon |
  14453. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  14454. * | search | The search params, minus the question mark |
  14455. * | hash | The hash string, minus the hash symbol
  14456. * | hostname | The hostname
  14457. * | port | The port, without ":"
  14458. * | pathname | The pathname, beginning with "/"
  14459. *
  14460. */
  14461. function urlResolve(url, base) {
  14462. var href = url;
  14463. if (msie) {
  14464. // Normalize before parse. Refer Implementation Notes on why this is
  14465. // done in two steps on IE.
  14466. urlParsingNode.setAttribute("href", href);
  14467. href = urlParsingNode.href;
  14468. }
  14469. urlParsingNode.setAttribute('href', href);
  14470. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  14471. return {
  14472. href: urlParsingNode.href,
  14473. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  14474. host: urlParsingNode.host,
  14475. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  14476. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  14477. hostname: urlParsingNode.hostname,
  14478. port: urlParsingNode.port,
  14479. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  14480. ? urlParsingNode.pathname
  14481. : '/' + urlParsingNode.pathname
  14482. };
  14483. }
  14484. /**
  14485. * Parse a request URL and determine whether this is a same-origin request as the application document.
  14486. *
  14487. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  14488. * or a parsed URL object.
  14489. * @returns {boolean} Whether the request is for the same origin as the application document.
  14490. */
  14491. function urlIsSameOrigin(requestUrl) {
  14492. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  14493. return (parsed.protocol === originUrl.protocol &&
  14494. parsed.host === originUrl.host);
  14495. }
  14496. /**
  14497. * @ngdoc service
  14498. * @name $window
  14499. *
  14500. * @description
  14501. * A reference to the browser's `window` object. While `window`
  14502. * is globally available in JavaScript, it causes testability problems, because
  14503. * it is a global variable. In angular we always refer to it through the
  14504. * `$window` service, so it may be overridden, removed or mocked for testing.
  14505. *
  14506. * Expressions, like the one defined for the `ngClick` directive in the example
  14507. * below, are evaluated with respect to the current scope. Therefore, there is
  14508. * no risk of inadvertently coding in a dependency on a global value in such an
  14509. * expression.
  14510. *
  14511. * @example
  14512. <example module="windowExample">
  14513. <file name="index.html">
  14514. <script>
  14515. angular.module('windowExample', [])
  14516. .controller('ExampleController', ['$scope', '$window', function ($scope, $window) {
  14517. $scope.greeting = 'Hello, World!';
  14518. $scope.doGreeting = function(greeting) {
  14519. $window.alert(greeting);
  14520. };
  14521. }]);
  14522. </script>
  14523. <div ng-controller="ExampleController">
  14524. <input type="text" ng-model="greeting" />
  14525. <button ng-click="doGreeting(greeting)">ALERT</button>
  14526. </div>
  14527. </file>
  14528. <file name="protractor.js" type="protractor">
  14529. it('should display the greeting in the input box', function() {
  14530. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  14531. // If we click the button it will block the test runner
  14532. // element(':button').click();
  14533. });
  14534. </file>
  14535. </example>
  14536. */
  14537. function $WindowProvider(){
  14538. this.$get = valueFn(window);
  14539. }
  14540. /* global currencyFilter: true,
  14541. dateFilter: true,
  14542. filterFilter: true,
  14543. jsonFilter: true,
  14544. limitToFilter: true,
  14545. lowercaseFilter: true,
  14546. numberFilter: true,
  14547. orderByFilter: true,
  14548. uppercaseFilter: true,
  14549. */
  14550. /**
  14551. * @ngdoc provider
  14552. * @name $filterProvider
  14553. * @description
  14554. *
  14555. * Filters are just functions which transform input to an output. However filters need to be
  14556. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  14557. * annotated with dependencies and is responsible for creating a filter function.
  14558. *
  14559. * ```js
  14560. * // Filter registration
  14561. * function MyModule($provide, $filterProvider) {
  14562. * // create a service to demonstrate injection (not always needed)
  14563. * $provide.value('greet', function(name){
  14564. * return 'Hello ' + name + '!';
  14565. * });
  14566. *
  14567. * // register a filter factory which uses the
  14568. * // greet service to demonstrate DI.
  14569. * $filterProvider.register('greet', function(greet){
  14570. * // return the filter function which uses the greet service
  14571. * // to generate salutation
  14572. * return function(text) {
  14573. * // filters need to be forgiving so check input validity
  14574. * return text && greet(text) || text;
  14575. * };
  14576. * });
  14577. * }
  14578. * ```
  14579. *
  14580. * The filter function is registered with the `$injector` under the filter name suffix with
  14581. * `Filter`.
  14582. *
  14583. * ```js
  14584. * it('should be the same instance', inject(
  14585. * function($filterProvider) {
  14586. * $filterProvider.register('reverse', function(){
  14587. * return ...;
  14588. * });
  14589. * },
  14590. * function($filter, reverseFilter) {
  14591. * expect($filter('reverse')).toBe(reverseFilter);
  14592. * });
  14593. * ```
  14594. *
  14595. *
  14596. * For more information about how angular filters work, and how to create your own filters, see
  14597. * {@link guide/filter Filters} in the Angular Developer Guide.
  14598. */
  14599. /**
  14600. * @ngdoc service
  14601. * @name $filter
  14602. * @kind function
  14603. * @description
  14604. * Filters are used for formatting data displayed to the user.
  14605. *
  14606. * The general syntax in templates is as follows:
  14607. *
  14608. * {{ expression [| filter_name[:parameter_value] ... ] }}
  14609. *
  14610. * @param {String} name Name of the filter function to retrieve
  14611. * @return {Function} the filter function
  14612. * @example
  14613. <example name="$filter" module="filterExample">
  14614. <file name="index.html">
  14615. <div ng-controller="MainCtrl">
  14616. <h3>{{ originalText }}</h3>
  14617. <h3>{{ filteredText }}</h3>
  14618. </div>
  14619. </file>
  14620. <file name="script.js">
  14621. angular.module('filterExample', [])
  14622. .controller('MainCtrl', function($scope, $filter) {
  14623. $scope.originalText = 'hello';
  14624. $scope.filteredText = $filter('uppercase')($scope.originalText);
  14625. });
  14626. </file>
  14627. </example>
  14628. */
  14629. $FilterProvider.$inject = ['$provide'];
  14630. function $FilterProvider($provide) {
  14631. var suffix = 'Filter';
  14632. /**
  14633. * @ngdoc method
  14634. * @name $filterProvider#register
  14635. * @param {string|Object} name Name of the filter function, or an object map of filters where
  14636. * the keys are the filter names and the values are the filter factories.
  14637. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  14638. * of the registered filter instances.
  14639. */
  14640. function register(name, factory) {
  14641. if(isObject(name)) {
  14642. var filters = {};
  14643. forEach(name, function(filter, key) {
  14644. filters[key] = register(key, filter);
  14645. });
  14646. return filters;
  14647. } else {
  14648. return $provide.factory(name + suffix, factory);
  14649. }
  14650. }
  14651. this.register = register;
  14652. this.$get = ['$injector', function($injector) {
  14653. return function(name) {
  14654. return $injector.get(name + suffix);
  14655. };
  14656. }];
  14657. ////////////////////////////////////////
  14658. /* global
  14659. currencyFilter: false,
  14660. dateFilter: false,
  14661. filterFilter: false,
  14662. jsonFilter: false,
  14663. limitToFilter: false,
  14664. lowercaseFilter: false,
  14665. numberFilter: false,
  14666. orderByFilter: false,
  14667. uppercaseFilter: false,
  14668. */
  14669. register('currency', currencyFilter);
  14670. register('date', dateFilter);
  14671. register('filter', filterFilter);
  14672. register('json', jsonFilter);
  14673. register('limitTo', limitToFilter);
  14674. register('lowercase', lowercaseFilter);
  14675. register('number', numberFilter);
  14676. register('orderBy', orderByFilter);
  14677. register('uppercase', uppercaseFilter);
  14678. }
  14679. /**
  14680. * @ngdoc filter
  14681. * @name filter
  14682. * @kind function
  14683. *
  14684. * @description
  14685. * Selects a subset of items from `array` and returns it as a new array.
  14686. *
  14687. * @param {Array} array The source array.
  14688. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  14689. * `array`.
  14690. *
  14691. * Can be one of:
  14692. *
  14693. * - `string`: The string is evaluated as an expression and the resulting value is used for substring match against
  14694. * the contents of the `array`. All strings or objects with string properties in `array` that contain this string
  14695. * will be returned. The predicate can be negated by prefixing the string with `!`.
  14696. *
  14697. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  14698. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  14699. * which have property `name` containing "M" and property `phone` containing "1". A special
  14700. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  14701. * property of the object. That's equivalent to the simple substring match with a `string`
  14702. * as described above. The predicate can be negated by prefixing the string with `!`.
  14703. * For Example `{name: "!M"}` predicate will return an array of items which have property `name`
  14704. * not containing "M".
  14705. *
  14706. * - `function(value, index)`: A predicate function can be used to write arbitrary filters. The
  14707. * function is called for each element of `array`. The final result is an array of those
  14708. * elements that the predicate returned true for.
  14709. *
  14710. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  14711. * determining if the expected value (from the filter expression) and actual value (from
  14712. * the object in the array) should be considered a match.
  14713. *
  14714. * Can be one of:
  14715. *
  14716. * - `function(actual, expected)`:
  14717. * The function will be given the object value and the predicate value to compare and
  14718. * should return true if the item should be included in filtered result.
  14719. *
  14720. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(expected, actual)}`.
  14721. * this is essentially strict comparison of expected and actual.
  14722. *
  14723. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  14724. * insensitive way.
  14725. *
  14726. * @example
  14727. <example>
  14728. <file name="index.html">
  14729. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  14730. {name:'Mary', phone:'800-BIG-MARY'},
  14731. {name:'Mike', phone:'555-4321'},
  14732. {name:'Adam', phone:'555-5678'},
  14733. {name:'Julie', phone:'555-8765'},
  14734. {name:'Juliette', phone:'555-5678'}]"></div>
  14735. Search: <input ng-model="searchText">
  14736. <table id="searchTextResults">
  14737. <tr><th>Name</th><th>Phone</th></tr>
  14738. <tr ng-repeat="friend in friends | filter:searchText">
  14739. <td>{{friend.name}}</td>
  14740. <td>{{friend.phone}}</td>
  14741. </tr>
  14742. </table>
  14743. <hr>
  14744. Any: <input ng-model="search.$"> <br>
  14745. Name only <input ng-model="search.name"><br>
  14746. Phone only <input ng-model="search.phone"><br>
  14747. Equality <input type="checkbox" ng-model="strict"><br>
  14748. <table id="searchObjResults">
  14749. <tr><th>Name</th><th>Phone</th></tr>
  14750. <tr ng-repeat="friendObj in friends | filter:search:strict">
  14751. <td>{{friendObj.name}}</td>
  14752. <td>{{friendObj.phone}}</td>
  14753. </tr>
  14754. </table>
  14755. </file>
  14756. <file name="protractor.js" type="protractor">
  14757. var expectFriendNames = function(expectedNames, key) {
  14758. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  14759. arr.forEach(function(wd, i) {
  14760. expect(wd.getText()).toMatch(expectedNames[i]);
  14761. });
  14762. });
  14763. };
  14764. it('should search across all fields when filtering with a string', function() {
  14765. var searchText = element(by.model('searchText'));
  14766. searchText.clear();
  14767. searchText.sendKeys('m');
  14768. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  14769. searchText.clear();
  14770. searchText.sendKeys('76');
  14771. expectFriendNames(['John', 'Julie'], 'friend');
  14772. });
  14773. it('should search in specific fields when filtering with a predicate object', function() {
  14774. var searchAny = element(by.model('search.$'));
  14775. searchAny.clear();
  14776. searchAny.sendKeys('i');
  14777. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  14778. });
  14779. it('should use a equal comparison when comparator is true', function() {
  14780. var searchName = element(by.model('search.name'));
  14781. var strict = element(by.model('strict'));
  14782. searchName.clear();
  14783. searchName.sendKeys('Julie');
  14784. strict.click();
  14785. expectFriendNames(['Julie'], 'friendObj');
  14786. });
  14787. </file>
  14788. </example>
  14789. */
  14790. function filterFilter() {
  14791. return function(array, expression, comparator) {
  14792. if (!isArray(array)) return array;
  14793. var comparatorType = typeof(comparator),
  14794. predicates = [];
  14795. predicates.check = function(value, index) {
  14796. for (var j = 0; j < predicates.length; j++) {
  14797. if(!predicates[j](value, index)) {
  14798. return false;
  14799. }
  14800. }
  14801. return true;
  14802. };
  14803. if (comparatorType !== 'function') {
  14804. if (comparatorType === 'boolean' && comparator) {
  14805. comparator = function(obj, text) {
  14806. return angular.equals(obj, text);
  14807. };
  14808. } else {
  14809. comparator = function(obj, text) {
  14810. if (obj && text && typeof obj === 'object' && typeof text === 'object') {
  14811. for (var objKey in obj) {
  14812. if (objKey.charAt(0) !== '$' && hasOwnProperty.call(obj, objKey) &&
  14813. comparator(obj[objKey], text[objKey])) {
  14814. return true;
  14815. }
  14816. }
  14817. return false;
  14818. }
  14819. text = (''+text).toLowerCase();
  14820. return (''+obj).toLowerCase().indexOf(text) > -1;
  14821. };
  14822. }
  14823. }
  14824. var search = function(obj, text){
  14825. if (typeof text === 'string' && text.charAt(0) === '!') {
  14826. return !search(obj, text.substr(1));
  14827. }
  14828. switch (typeof obj) {
  14829. case 'boolean':
  14830. case 'number':
  14831. case 'string':
  14832. return comparator(obj, text);
  14833. case 'object':
  14834. switch (typeof text) {
  14835. case 'object':
  14836. return comparator(obj, text);
  14837. default:
  14838. for ( var objKey in obj) {
  14839. if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
  14840. return true;
  14841. }
  14842. }
  14843. break;
  14844. }
  14845. return false;
  14846. case 'array':
  14847. for ( var i = 0; i < obj.length; i++) {
  14848. if (search(obj[i], text)) {
  14849. return true;
  14850. }
  14851. }
  14852. return false;
  14853. default:
  14854. return false;
  14855. }
  14856. };
  14857. switch (typeof expression) {
  14858. case 'boolean':
  14859. case 'number':
  14860. case 'string':
  14861. // Set up expression object and fall through
  14862. expression = {$:expression};
  14863. // jshint -W086
  14864. case 'object':
  14865. // jshint +W086
  14866. for (var key in expression) {
  14867. (function(path) {
  14868. if (typeof expression[path] === 'undefined') return;
  14869. predicates.push(function(value) {
  14870. return search(path == '$' ? value : (value && value[path]), expression[path]);
  14871. });
  14872. })(key);
  14873. }
  14874. break;
  14875. case 'function':
  14876. predicates.push(expression);
  14877. break;
  14878. default:
  14879. return array;
  14880. }
  14881. var filtered = [];
  14882. for ( var j = 0; j < array.length; j++) {
  14883. var value = array[j];
  14884. if (predicates.check(value, j)) {
  14885. filtered.push(value);
  14886. }
  14887. }
  14888. return filtered;
  14889. };
  14890. }
  14891. /**
  14892. * @ngdoc filter
  14893. * @name currency
  14894. * @kind function
  14895. *
  14896. * @description
  14897. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  14898. * symbol for current locale is used.
  14899. *
  14900. * @param {number} amount Input to filter.
  14901. * @param {string=} symbol Currency symbol or identifier to be displayed.
  14902. * @param {number=} fractionSize Number of decimal places to round the amount to.
  14903. * @returns {string} Formatted number.
  14904. *
  14905. *
  14906. * @example
  14907. <example module="currencyExample">
  14908. <file name="index.html">
  14909. <script>
  14910. angular.module('currencyExample', [])
  14911. .controller('ExampleController', ['$scope', function($scope) {
  14912. $scope.amount = 1234.56;
  14913. }]);
  14914. </script>
  14915. <div ng-controller="ExampleController">
  14916. <input type="number" ng-model="amount"> <br>
  14917. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  14918. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  14919. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  14920. </div>
  14921. </file>
  14922. <file name="protractor.js" type="protractor">
  14923. it('should init with 1234.56', function() {
  14924. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  14925. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  14926. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  14927. });
  14928. it('should update', function() {
  14929. if (browser.params.browser == 'safari') {
  14930. // Safari does not understand the minus key. See
  14931. // https://github.com/angular/protractor/issues/481
  14932. return;
  14933. }
  14934. element(by.model('amount')).clear();
  14935. element(by.model('amount')).sendKeys('-1234');
  14936. expect(element(by.id('currency-default')).getText()).toBe('($1,234.00)');
  14937. expect(element(by.id('currency-custom')).getText()).toBe('(USD$1,234.00)');
  14938. expect(element(by.id('currency-no-fractions')).getText()).toBe('(USD$1,234)');
  14939. });
  14940. </file>
  14941. </example>
  14942. */
  14943. currencyFilter.$inject = ['$locale'];
  14944. function currencyFilter($locale) {
  14945. var formats = $locale.NUMBER_FORMATS;
  14946. return function(amount, currencySymbol, fractionSize){
  14947. if (isUndefined(currencySymbol)) {
  14948. currencySymbol = formats.CURRENCY_SYM;
  14949. }
  14950. if (isUndefined(fractionSize)) {
  14951. // TODO: read the default value from the locale file
  14952. fractionSize = 2;
  14953. }
  14954. // if null or undefined pass it through
  14955. return (amount == null)
  14956. ? amount
  14957. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  14958. replace(/\u00A4/g, currencySymbol);
  14959. };
  14960. }
  14961. /**
  14962. * @ngdoc filter
  14963. * @name number
  14964. * @kind function
  14965. *
  14966. * @description
  14967. * Formats a number as text.
  14968. *
  14969. * If the input is not a number an empty string is returned.
  14970. *
  14971. * @param {number|string} number Number to format.
  14972. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  14973. * If this is not provided then the fraction size is computed from the current locale's number
  14974. * formatting pattern. In the case of the default locale, it will be 3.
  14975. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  14976. *
  14977. * @example
  14978. <example module="numberFilterExample">
  14979. <file name="index.html">
  14980. <script>
  14981. angular.module('numberFilterExample', [])
  14982. .controller('ExampleController', ['$scope', function($scope) {
  14983. $scope.val = 1234.56789;
  14984. }]);
  14985. </script>
  14986. <div ng-controller="ExampleController">
  14987. Enter number: <input ng-model='val'><br>
  14988. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  14989. No fractions: <span>{{val | number:0}}</span><br>
  14990. Negative number: <span>{{-val | number:4}}</span>
  14991. </div>
  14992. </file>
  14993. <file name="protractor.js" type="protractor">
  14994. it('should format numbers', function() {
  14995. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  14996. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  14997. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  14998. });
  14999. it('should update', function() {
  15000. element(by.model('val')).clear();
  15001. element(by.model('val')).sendKeys('3374.333');
  15002. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  15003. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  15004. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  15005. });
  15006. </file>
  15007. </example>
  15008. */
  15009. numberFilter.$inject = ['$locale'];
  15010. function numberFilter($locale) {
  15011. var formats = $locale.NUMBER_FORMATS;
  15012. return function(number, fractionSize) {
  15013. // if null or undefined pass it through
  15014. return (number == null)
  15015. ? number
  15016. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  15017. fractionSize);
  15018. };
  15019. }
  15020. var DECIMAL_SEP = '.';
  15021. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  15022. if (!isFinite(number) || isObject(number)) return '';
  15023. var isNegative = number < 0;
  15024. number = Math.abs(number);
  15025. var numStr = number + '',
  15026. formatedText = '',
  15027. parts = [];
  15028. var hasExponent = false;
  15029. if (numStr.indexOf('e') !== -1) {
  15030. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  15031. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  15032. numStr = '0';
  15033. number = 0;
  15034. } else {
  15035. formatedText = numStr;
  15036. hasExponent = true;
  15037. }
  15038. }
  15039. if (!hasExponent) {
  15040. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  15041. // determine fractionSize if it is not specified
  15042. if (isUndefined(fractionSize)) {
  15043. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  15044. }
  15045. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  15046. // inspired by:
  15047. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  15048. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  15049. if (number === 0) {
  15050. isNegative = false;
  15051. }
  15052. var fraction = ('' + number).split(DECIMAL_SEP);
  15053. var whole = fraction[0];
  15054. fraction = fraction[1] || '';
  15055. var i, pos = 0,
  15056. lgroup = pattern.lgSize,
  15057. group = pattern.gSize;
  15058. if (whole.length >= (lgroup + group)) {
  15059. pos = whole.length - lgroup;
  15060. for (i = 0; i < pos; i++) {
  15061. if ((pos - i)%group === 0 && i !== 0) {
  15062. formatedText += groupSep;
  15063. }
  15064. formatedText += whole.charAt(i);
  15065. }
  15066. }
  15067. for (i = pos; i < whole.length; i++) {
  15068. if ((whole.length - i)%lgroup === 0 && i !== 0) {
  15069. formatedText += groupSep;
  15070. }
  15071. formatedText += whole.charAt(i);
  15072. }
  15073. // format fraction part.
  15074. while(fraction.length < fractionSize) {
  15075. fraction += '0';
  15076. }
  15077. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  15078. } else {
  15079. if (fractionSize > 0 && number > -1 && number < 1) {
  15080. formatedText = number.toFixed(fractionSize);
  15081. }
  15082. }
  15083. parts.push(isNegative ? pattern.negPre : pattern.posPre);
  15084. parts.push(formatedText);
  15085. parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
  15086. return parts.join('');
  15087. }
  15088. function padNumber(num, digits, trim) {
  15089. var neg = '';
  15090. if (num < 0) {
  15091. neg = '-';
  15092. num = -num;
  15093. }
  15094. num = '' + num;
  15095. while(num.length < digits) num = '0' + num;
  15096. if (trim)
  15097. num = num.substr(num.length - digits);
  15098. return neg + num;
  15099. }
  15100. function dateGetter(name, size, offset, trim) {
  15101. offset = offset || 0;
  15102. return function(date) {
  15103. var value = date['get' + name]();
  15104. if (offset > 0 || value > -offset)
  15105. value += offset;
  15106. if (value === 0 && offset == -12 ) value = 12;
  15107. return padNumber(value, size, trim);
  15108. };
  15109. }
  15110. function dateStrGetter(name, shortForm) {
  15111. return function(date, formats) {
  15112. var value = date['get' + name]();
  15113. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  15114. return formats[get][value];
  15115. };
  15116. }
  15117. function timeZoneGetter(date) {
  15118. var zone = -1 * date.getTimezoneOffset();
  15119. var paddedZone = (zone >= 0) ? "+" : "";
  15120. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  15121. padNumber(Math.abs(zone % 60), 2);
  15122. return paddedZone;
  15123. }
  15124. function getFirstThursdayOfYear(year) {
  15125. // 0 = index of January
  15126. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  15127. // 4 = index of Thursday (+1 to account for 1st = 5)
  15128. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  15129. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  15130. }
  15131. function getThursdayThisWeek(datetime) {
  15132. return new Date(datetime.getFullYear(), datetime.getMonth(),
  15133. // 4 = index of Thursday
  15134. datetime.getDate() + (4 - datetime.getDay()));
  15135. }
  15136. function weekGetter(size) {
  15137. return function(date) {
  15138. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  15139. thisThurs = getThursdayThisWeek(date);
  15140. var diff = +thisThurs - +firstThurs,
  15141. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  15142. return padNumber(result, size);
  15143. };
  15144. }
  15145. function ampmGetter(date, formats) {
  15146. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  15147. }
  15148. var DATE_FORMATS = {
  15149. yyyy: dateGetter('FullYear', 4),
  15150. yy: dateGetter('FullYear', 2, 0, true),
  15151. y: dateGetter('FullYear', 1),
  15152. MMMM: dateStrGetter('Month'),
  15153. MMM: dateStrGetter('Month', true),
  15154. MM: dateGetter('Month', 2, 1),
  15155. M: dateGetter('Month', 1, 1),
  15156. dd: dateGetter('Date', 2),
  15157. d: dateGetter('Date', 1),
  15158. HH: dateGetter('Hours', 2),
  15159. H: dateGetter('Hours', 1),
  15160. hh: dateGetter('Hours', 2, -12),
  15161. h: dateGetter('Hours', 1, -12),
  15162. mm: dateGetter('Minutes', 2),
  15163. m: dateGetter('Minutes', 1),
  15164. ss: dateGetter('Seconds', 2),
  15165. s: dateGetter('Seconds', 1),
  15166. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  15167. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  15168. sss: dateGetter('Milliseconds', 3),
  15169. EEEE: dateStrGetter('Day'),
  15170. EEE: dateStrGetter('Day', true),
  15171. a: ampmGetter,
  15172. Z: timeZoneGetter,
  15173. ww: weekGetter(2),
  15174. w: weekGetter(1)
  15175. };
  15176. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEw']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|w+))(.*)/,
  15177. NUMBER_STRING = /^\-?\d+$/;
  15178. /**
  15179. * @ngdoc filter
  15180. * @name date
  15181. * @kind function
  15182. *
  15183. * @description
  15184. * Formats `date` to a string based on the requested `format`.
  15185. *
  15186. * `format` string can be composed of the following elements:
  15187. *
  15188. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  15189. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  15190. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  15191. * * `'MMMM'`: Month in year (January-December)
  15192. * * `'MMM'`: Month in year (Jan-Dec)
  15193. * * `'MM'`: Month in year, padded (01-12)
  15194. * * `'M'`: Month in year (1-12)
  15195. * * `'dd'`: Day in month, padded (01-31)
  15196. * * `'d'`: Day in month (1-31)
  15197. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  15198. * * `'EEE'`: Day in Week, (Sun-Sat)
  15199. * * `'HH'`: Hour in day, padded (00-23)
  15200. * * `'H'`: Hour in day (0-23)
  15201. * * `'hh'`: Hour in AM/PM, padded (01-12)
  15202. * * `'h'`: Hour in AM/PM, (1-12)
  15203. * * `'mm'`: Minute in hour, padded (00-59)
  15204. * * `'m'`: Minute in hour (0-59)
  15205. * * `'ss'`: Second in minute, padded (00-59)
  15206. * * `'s'`: Second in minute (0-59)
  15207. * * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
  15208. * * `'a'`: AM/PM marker
  15209. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  15210. * * `'ww'`: ISO-8601 week of year (00-53)
  15211. * * `'w'`: ISO-8601 week of year (0-53)
  15212. *
  15213. * `format` string can also be one of the following predefined
  15214. * {@link guide/i18n localizable formats}:
  15215. *
  15216. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  15217. * (e.g. Sep 3, 2010 12:05:08 PM)
  15218. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  15219. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  15220. * (e.g. Friday, September 3, 2010)
  15221. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  15222. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  15223. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  15224. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  15225. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  15226. *
  15227. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  15228. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  15229. * (e.g. `"h 'o''clock'"`).
  15230. *
  15231. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  15232. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  15233. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  15234. * specified in the string input, the time is considered to be in the local timezone.
  15235. * @param {string=} format Formatting rules (see Description). If not specified,
  15236. * `mediumDate` is used.
  15237. * @param {string=} timezone Timezone to be used for formatting. Right now, only `'UTC'` is supported.
  15238. * If not specified, the timezone of the browser will be used.
  15239. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  15240. *
  15241. * @example
  15242. <example>
  15243. <file name="index.html">
  15244. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  15245. <span>{{1288323623006 | date:'medium'}}</span><br>
  15246. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  15247. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  15248. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  15249. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  15250. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  15251. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  15252. </file>
  15253. <file name="protractor.js" type="protractor">
  15254. it('should format date', function() {
  15255. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  15256. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  15257. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  15258. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  15259. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  15260. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  15261. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  15262. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  15263. });
  15264. </file>
  15265. </example>
  15266. */
  15267. dateFilter.$inject = ['$locale'];
  15268. function dateFilter($locale) {
  15269. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  15270. // 1 2 3 4 5 6 7 8 9 10 11
  15271. function jsonStringToDate(string) {
  15272. var match;
  15273. if (match = string.match(R_ISO8601_STR)) {
  15274. var date = new Date(0),
  15275. tzHour = 0,
  15276. tzMin = 0,
  15277. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  15278. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  15279. if (match[9]) {
  15280. tzHour = int(match[9] + match[10]);
  15281. tzMin = int(match[9] + match[11]);
  15282. }
  15283. dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
  15284. var h = int(match[4]||0) - tzHour;
  15285. var m = int(match[5]||0) - tzMin;
  15286. var s = int(match[6]||0);
  15287. var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
  15288. timeSetter.call(date, h, m, s, ms);
  15289. return date;
  15290. }
  15291. return string;
  15292. }
  15293. return function(date, format, timezone) {
  15294. var text = '',
  15295. parts = [],
  15296. fn, match;
  15297. format = format || 'mediumDate';
  15298. format = $locale.DATETIME_FORMATS[format] || format;
  15299. if (isString(date)) {
  15300. date = NUMBER_STRING.test(date) ? int(date) : jsonStringToDate(date);
  15301. }
  15302. if (isNumber(date)) {
  15303. date = new Date(date);
  15304. }
  15305. if (!isDate(date)) {
  15306. return date;
  15307. }
  15308. while(format) {
  15309. match = DATE_FORMATS_SPLIT.exec(format);
  15310. if (match) {
  15311. parts = concat(parts, match, 1);
  15312. format = parts.pop();
  15313. } else {
  15314. parts.push(format);
  15315. format = null;
  15316. }
  15317. }
  15318. if (timezone && timezone === 'UTC') {
  15319. date = new Date(date.getTime());
  15320. date.setMinutes(date.getMinutes() + date.getTimezoneOffset());
  15321. }
  15322. forEach(parts, function(value){
  15323. fn = DATE_FORMATS[value];
  15324. text += fn ? fn(date, $locale.DATETIME_FORMATS)
  15325. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  15326. });
  15327. return text;
  15328. };
  15329. }
  15330. /**
  15331. * @ngdoc filter
  15332. * @name json
  15333. * @kind function
  15334. *
  15335. * @description
  15336. * Allows you to convert a JavaScript object into JSON string.
  15337. *
  15338. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  15339. * the binding is automatically converted to JSON.
  15340. *
  15341. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  15342. * @returns {string} JSON string.
  15343. *
  15344. *
  15345. * @example
  15346. <example>
  15347. <file name="index.html">
  15348. <pre>{{ {'name':'value'} | json }}</pre>
  15349. </file>
  15350. <file name="protractor.js" type="protractor">
  15351. it('should jsonify filtered objects', function() {
  15352. expect(element(by.binding("{'name':'value'}")).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  15353. });
  15354. </file>
  15355. </example>
  15356. *
  15357. */
  15358. function jsonFilter() {
  15359. return function(object) {
  15360. return toJson(object, true);
  15361. };
  15362. }
  15363. /**
  15364. * @ngdoc filter
  15365. * @name lowercase
  15366. * @kind function
  15367. * @description
  15368. * Converts string to lowercase.
  15369. * @see angular.lowercase
  15370. */
  15371. var lowercaseFilter = valueFn(lowercase);
  15372. /**
  15373. * @ngdoc filter
  15374. * @name uppercase
  15375. * @kind function
  15376. * @description
  15377. * Converts string to uppercase.
  15378. * @see angular.uppercase
  15379. */
  15380. var uppercaseFilter = valueFn(uppercase);
  15381. /**
  15382. * @ngdoc filter
  15383. * @name limitTo
  15384. * @kind function
  15385. *
  15386. * @description
  15387. * Creates a new array or string containing only a specified number of elements. The elements
  15388. * are taken from either the beginning or the end of the source array, string or number, as specified by
  15389. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  15390. * converted to a string.
  15391. *
  15392. * @param {Array|string|number} input Source array, string or number to be limited.
  15393. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  15394. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  15395. * If the number is negative, `limit` number of items from the end of the source array/string
  15396. * are copied. The `limit` will be trimmed if it exceeds `array.length`
  15397. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  15398. * had less than `limit` elements.
  15399. *
  15400. * @example
  15401. <example module="limitToExample">
  15402. <file name="index.html">
  15403. <script>
  15404. angular.module('limitToExample', [])
  15405. .controller('ExampleController', ['$scope', function($scope) {
  15406. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  15407. $scope.letters = "abcdefghi";
  15408. $scope.longNumber = 2345432342;
  15409. $scope.numLimit = 3;
  15410. $scope.letterLimit = 3;
  15411. $scope.longNumberLimit = 3;
  15412. }]);
  15413. </script>
  15414. <div ng-controller="ExampleController">
  15415. Limit {{numbers}} to: <input type="number" step="1" ng-model="numLimit">
  15416. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  15417. Limit {{letters}} to: <input type="number" step="1" ng-model="letterLimit">
  15418. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  15419. Limit {{longNumber}} to: <input type="number" step="1" ng-model="longNumberLimit">
  15420. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  15421. </div>
  15422. </file>
  15423. <file name="protractor.js" type="protractor">
  15424. var numLimitInput = element(by.model('numLimit'));
  15425. var letterLimitInput = element(by.model('letterLimit'));
  15426. var longNumberLimitInput = element(by.model('longNumberLimit'));
  15427. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  15428. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  15429. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  15430. it('should limit the number array to first three items', function() {
  15431. expect(numLimitInput.getAttribute('value')).toBe('3');
  15432. expect(letterLimitInput.getAttribute('value')).toBe('3');
  15433. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  15434. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  15435. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  15436. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  15437. });
  15438. // There is a bug in safari and protractor that doesn't like the minus key
  15439. // it('should update the output when -3 is entered', function() {
  15440. // numLimitInput.clear();
  15441. // numLimitInput.sendKeys('-3');
  15442. // letterLimitInput.clear();
  15443. // letterLimitInput.sendKeys('-3');
  15444. // longNumberLimitInput.clear();
  15445. // longNumberLimitInput.sendKeys('-3');
  15446. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  15447. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  15448. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  15449. // });
  15450. it('should not exceed the maximum size of input array', function() {
  15451. numLimitInput.clear();
  15452. numLimitInput.sendKeys('100');
  15453. letterLimitInput.clear();
  15454. letterLimitInput.sendKeys('100');
  15455. longNumberLimitInput.clear();
  15456. longNumberLimitInput.sendKeys('100');
  15457. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  15458. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  15459. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  15460. });
  15461. </file>
  15462. </example>
  15463. */
  15464. function limitToFilter(){
  15465. return function(input, limit) {
  15466. if (isNumber(input)) input = input.toString();
  15467. if (!isArray(input) && !isString(input)) return input;
  15468. if (Math.abs(Number(limit)) === Infinity) {
  15469. limit = Number(limit);
  15470. } else {
  15471. limit = int(limit);
  15472. }
  15473. if (isString(input)) {
  15474. //NaN check on limit
  15475. if (limit) {
  15476. return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
  15477. } else {
  15478. return "";
  15479. }
  15480. }
  15481. var out = [],
  15482. i, n;
  15483. // if abs(limit) exceeds maximum length, trim it
  15484. if (limit > input.length)
  15485. limit = input.length;
  15486. else if (limit < -input.length)
  15487. limit = -input.length;
  15488. if (limit > 0) {
  15489. i = 0;
  15490. n = limit;
  15491. } else {
  15492. i = input.length + limit;
  15493. n = input.length;
  15494. }
  15495. for (; i<n; i++) {
  15496. out.push(input[i]);
  15497. }
  15498. return out;
  15499. };
  15500. }
  15501. /**
  15502. * @ngdoc filter
  15503. * @name orderBy
  15504. * @kind function
  15505. *
  15506. * @description
  15507. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  15508. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  15509. * correctly, make sure they are actually being saved as numbers and not strings.
  15510. *
  15511. * @param {Array} array The array to sort.
  15512. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  15513. * used by the comparator to determine the order of elements.
  15514. *
  15515. * Can be one of:
  15516. *
  15517. * - `function`: Getter function. The result of this function will be sorted using the
  15518. * `<`, `=`, `>` operator.
  15519. * - `string`: An Angular expression. The result of this expression is used to compare elements
  15520. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  15521. * 3 first characters of a property called `name`). The result of a constant expression
  15522. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  15523. * to sort object by the value of their `special name` property). An expression can be
  15524. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  15525. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  15526. * element itself is used to compare where sorting.
  15527. * - `Array`: An array of function or string predicates. The first predicate in the array
  15528. * is used for sorting, but when two items are equivalent, the next predicate is used.
  15529. *
  15530. * If the predicate is missing or empty then it defaults to `'+'`.
  15531. *
  15532. * @param {boolean=} reverse Reverse the order of the array.
  15533. * @returns {Array} Sorted copy of the source array.
  15534. *
  15535. * @example
  15536. <example module="orderByExample">
  15537. <file name="index.html">
  15538. <script>
  15539. angular.module('orderByExample', [])
  15540. .controller('ExampleController', ['$scope', function($scope) {
  15541. $scope.friends =
  15542. [{name:'John', phone:'555-1212', age:10},
  15543. {name:'Mary', phone:'555-9876', age:19},
  15544. {name:'Mike', phone:'555-4321', age:21},
  15545. {name:'Adam', phone:'555-5678', age:35},
  15546. {name:'Julie', phone:'555-8765', age:29}];
  15547. $scope.predicate = '-age';
  15548. }]);
  15549. </script>
  15550. <div ng-controller="ExampleController">
  15551. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  15552. <hr/>
  15553. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  15554. <table class="friend">
  15555. <tr>
  15556. <th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
  15557. (<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
  15558. <th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
  15559. <th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
  15560. </tr>
  15561. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  15562. <td>{{friend.name}}</td>
  15563. <td>{{friend.phone}}</td>
  15564. <td>{{friend.age}}</td>
  15565. </tr>
  15566. </table>
  15567. </div>
  15568. </file>
  15569. </example>
  15570. *
  15571. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  15572. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  15573. * desired parameters.
  15574. *
  15575. * Example:
  15576. *
  15577. * @example
  15578. <example module="orderByExample">
  15579. <file name="index.html">
  15580. <div ng-controller="ExampleController">
  15581. <table class="friend">
  15582. <tr>
  15583. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  15584. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  15585. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  15586. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  15587. </tr>
  15588. <tr ng-repeat="friend in friends">
  15589. <td>{{friend.name}}</td>
  15590. <td>{{friend.phone}}</td>
  15591. <td>{{friend.age}}</td>
  15592. </tr>
  15593. </table>
  15594. </div>
  15595. </file>
  15596. <file name="script.js">
  15597. angular.module('orderByExample', [])
  15598. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  15599. var orderBy = $filter('orderBy');
  15600. $scope.friends = [
  15601. { name: 'John', phone: '555-1212', age: 10 },
  15602. { name: 'Mary', phone: '555-9876', age: 19 },
  15603. { name: 'Mike', phone: '555-4321', age: 21 },
  15604. { name: 'Adam', phone: '555-5678', age: 35 },
  15605. { name: 'Julie', phone: '555-8765', age: 29 }
  15606. ];
  15607. $scope.order = function(predicate, reverse) {
  15608. $scope.friends = orderBy($scope.friends, predicate, reverse);
  15609. };
  15610. $scope.order('-age',false);
  15611. }]);
  15612. </file>
  15613. </example>
  15614. */
  15615. orderByFilter.$inject = ['$parse'];
  15616. function orderByFilter($parse){
  15617. return function(array, sortPredicate, reverseOrder) {
  15618. if (!(isArrayLike(array))) return array;
  15619. sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
  15620. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  15621. sortPredicate = sortPredicate.map(function(predicate){
  15622. var descending = false, get = predicate || identity;
  15623. if (isString(predicate)) {
  15624. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  15625. descending = predicate.charAt(0) == '-';
  15626. predicate = predicate.substring(1);
  15627. }
  15628. if ( predicate === '' ) {
  15629. // Effectively no predicate was passed so we compare identity
  15630. return reverseComparator(function(a,b) {
  15631. return compare(a, b);
  15632. }, descending);
  15633. }
  15634. get = $parse(predicate);
  15635. if (get.constant) {
  15636. var key = get();
  15637. return reverseComparator(function(a,b) {
  15638. return compare(a[key], b[key]);
  15639. }, descending);
  15640. }
  15641. }
  15642. return reverseComparator(function(a,b){
  15643. return compare(get(a),get(b));
  15644. }, descending);
  15645. });
  15646. var arrayCopy = [];
  15647. for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
  15648. return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
  15649. function comparator(o1, o2){
  15650. for ( var i = 0; i < sortPredicate.length; i++) {
  15651. var comp = sortPredicate[i](o1, o2);
  15652. if (comp !== 0) return comp;
  15653. }
  15654. return 0;
  15655. }
  15656. function reverseComparator(comp, descending) {
  15657. return descending
  15658. ? function(a,b){return comp(b,a);}
  15659. : comp;
  15660. }
  15661. function compare(v1, v2){
  15662. var t1 = typeof v1;
  15663. var t2 = typeof v2;
  15664. if (t1 == t2) {
  15665. if (isDate(v1) && isDate(v2)) {
  15666. v1 = v1.valueOf();
  15667. v2 = v2.valueOf();
  15668. }
  15669. if (t1 == "string") {
  15670. v1 = v1.toLowerCase();
  15671. v2 = v2.toLowerCase();
  15672. }
  15673. if (v1 === v2) return 0;
  15674. return v1 < v2 ? -1 : 1;
  15675. } else {
  15676. return t1 < t2 ? -1 : 1;
  15677. }
  15678. }
  15679. };
  15680. }
  15681. function ngDirective(directive) {
  15682. if (isFunction(directive)) {
  15683. directive = {
  15684. link: directive
  15685. };
  15686. }
  15687. directive.restrict = directive.restrict || 'AC';
  15688. return valueFn(directive);
  15689. }
  15690. /**
  15691. * @ngdoc directive
  15692. * @name a
  15693. * @restrict E
  15694. *
  15695. * @description
  15696. * Modifies the default behavior of the html A tag so that the default action is prevented when
  15697. * the href attribute is empty.
  15698. *
  15699. * This change permits the easy creation of action links with the `ngClick` directive
  15700. * without changing the location or causing page reloads, e.g.:
  15701. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  15702. */
  15703. var htmlAnchorDirective = valueFn({
  15704. restrict: 'E',
  15705. compile: function(element, attr) {
  15706. if (!attr.href && !attr.xlinkHref && !attr.name) {
  15707. return function(scope, element) {
  15708. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  15709. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  15710. 'xlink:href' : 'href';
  15711. element.on('click', function(event){
  15712. // if we have no href url, then don't navigate anywhere.
  15713. if (!element.attr(href)) {
  15714. event.preventDefault();
  15715. }
  15716. });
  15717. };
  15718. }
  15719. }
  15720. });
  15721. /**
  15722. * @ngdoc directive
  15723. * @name ngHref
  15724. * @restrict A
  15725. * @priority 99
  15726. *
  15727. * @description
  15728. * Using Angular markup like `{{hash}}` in an href attribute will
  15729. * make the link go to the wrong URL if the user clicks it before
  15730. * Angular has a chance to replace the `{{hash}}` markup with its
  15731. * value. Until Angular replaces the markup the link will be broken
  15732. * and will most likely return a 404 error.
  15733. *
  15734. * The `ngHref` directive solves this problem.
  15735. *
  15736. * The wrong way to write it:
  15737. * ```html
  15738. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  15739. * ```
  15740. *
  15741. * The correct way to write it:
  15742. * ```html
  15743. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  15744. * ```
  15745. *
  15746. * @element A
  15747. * @param {template} ngHref any string which can contain `{{}}` markup.
  15748. *
  15749. * @example
  15750. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  15751. * in links and their different behaviors:
  15752. <example>
  15753. <file name="index.html">
  15754. <input ng-model="value" /><br />
  15755. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  15756. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  15757. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  15758. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  15759. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  15760. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  15761. </file>
  15762. <file name="protractor.js" type="protractor">
  15763. it('should execute ng-click but not reload when href without value', function() {
  15764. element(by.id('link-1')).click();
  15765. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  15766. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  15767. });
  15768. it('should execute ng-click but not reload when href empty string', function() {
  15769. element(by.id('link-2')).click();
  15770. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  15771. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  15772. });
  15773. it('should execute ng-click and change url when ng-href specified', function() {
  15774. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  15775. element(by.id('link-3')).click();
  15776. // At this point, we navigate away from an Angular page, so we need
  15777. // to use browser.driver to get the base webdriver.
  15778. browser.wait(function() {
  15779. return browser.driver.getCurrentUrl().then(function(url) {
  15780. return url.match(/\/123$/);
  15781. });
  15782. }, 5000, 'page should navigate to /123');
  15783. });
  15784. xit('should execute ng-click but not reload when href empty string and name specified', function() {
  15785. element(by.id('link-4')).click();
  15786. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  15787. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  15788. });
  15789. it('should execute ng-click but not reload when no href but name specified', function() {
  15790. element(by.id('link-5')).click();
  15791. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  15792. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  15793. });
  15794. it('should only change url when only ng-href', function() {
  15795. element(by.model('value')).clear();
  15796. element(by.model('value')).sendKeys('6');
  15797. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  15798. element(by.id('link-6')).click();
  15799. // At this point, we navigate away from an Angular page, so we need
  15800. // to use browser.driver to get the base webdriver.
  15801. browser.wait(function() {
  15802. return browser.driver.getCurrentUrl().then(function(url) {
  15803. return url.match(/\/6$/);
  15804. });
  15805. }, 5000, 'page should navigate to /6');
  15806. });
  15807. </file>
  15808. </example>
  15809. */
  15810. /**
  15811. * @ngdoc directive
  15812. * @name ngSrc
  15813. * @restrict A
  15814. * @priority 99
  15815. *
  15816. * @description
  15817. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  15818. * work right: The browser will fetch from the URL with the literal
  15819. * text `{{hash}}` until Angular replaces the expression inside
  15820. * `{{hash}}`. The `ngSrc` directive solves this problem.
  15821. *
  15822. * The buggy way to write it:
  15823. * ```html
  15824. * <img src="http://www.gravatar.com/avatar/{{hash}}"/>
  15825. * ```
  15826. *
  15827. * The correct way to write it:
  15828. * ```html
  15829. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
  15830. * ```
  15831. *
  15832. * @element IMG
  15833. * @param {template} ngSrc any string which can contain `{{}}` markup.
  15834. */
  15835. /**
  15836. * @ngdoc directive
  15837. * @name ngSrcset
  15838. * @restrict A
  15839. * @priority 99
  15840. *
  15841. * @description
  15842. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  15843. * work right: The browser will fetch from the URL with the literal
  15844. * text `{{hash}}` until Angular replaces the expression inside
  15845. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  15846. *
  15847. * The buggy way to write it:
  15848. * ```html
  15849. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  15850. * ```
  15851. *
  15852. * The correct way to write it:
  15853. * ```html
  15854. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
  15855. * ```
  15856. *
  15857. * @element IMG
  15858. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  15859. */
  15860. /**
  15861. * @ngdoc directive
  15862. * @name ngDisabled
  15863. * @restrict A
  15864. * @priority 100
  15865. *
  15866. * @description
  15867. *
  15868. * We shouldn't do this, because it will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
  15869. * ```html
  15870. * <div ng-init="scope = { isDisabled: false }">
  15871. * <button disabled="{{scope.isDisabled}}">Disabled</button>
  15872. * </div>
  15873. * ```
  15874. *
  15875. * The HTML specification does not require browsers to preserve the values of boolean attributes
  15876. * such as disabled. (Their presence means true and their absence means false.)
  15877. * If we put an Angular interpolation expression into such an attribute then the
  15878. * binding information would be lost when the browser removes the attribute.
  15879. * The `ngDisabled` directive solves this problem for the `disabled` attribute.
  15880. * This complementary directive is not removed by the browser and so provides
  15881. * a permanent reliable place to store the binding information.
  15882. *
  15883. * @example
  15884. <example>
  15885. <file name="index.html">
  15886. Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
  15887. <button ng-model="button" ng-disabled="checked">Button</button>
  15888. </file>
  15889. <file name="protractor.js" type="protractor">
  15890. it('should toggle button', function() {
  15891. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  15892. element(by.model('checked')).click();
  15893. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  15894. });
  15895. </file>
  15896. </example>
  15897. *
  15898. * @element INPUT
  15899. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  15900. * then special attribute "disabled" will be set on the element
  15901. */
  15902. /**
  15903. * @ngdoc directive
  15904. * @name ngChecked
  15905. * @restrict A
  15906. * @priority 100
  15907. *
  15908. * @description
  15909. * The HTML specification does not require browsers to preserve the values of boolean attributes
  15910. * such as checked. (Their presence means true and their absence means false.)
  15911. * If we put an Angular interpolation expression into such an attribute then the
  15912. * binding information would be lost when the browser removes the attribute.
  15913. * The `ngChecked` directive solves this problem for the `checked` attribute.
  15914. * This complementary directive is not removed by the browser and so provides
  15915. * a permanent reliable place to store the binding information.
  15916. * @example
  15917. <example>
  15918. <file name="index.html">
  15919. Check me to check both: <input type="checkbox" ng-model="master"><br/>
  15920. <input id="checkSlave" type="checkbox" ng-checked="master">
  15921. </file>
  15922. <file name="protractor.js" type="protractor">
  15923. it('should check both checkBoxes', function() {
  15924. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  15925. element(by.model('master')).click();
  15926. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  15927. });
  15928. </file>
  15929. </example>
  15930. *
  15931. * @element INPUT
  15932. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  15933. * then special attribute "checked" will be set on the element
  15934. */
  15935. /**
  15936. * @ngdoc directive
  15937. * @name ngReadonly
  15938. * @restrict A
  15939. * @priority 100
  15940. *
  15941. * @description
  15942. * The HTML specification does not require browsers to preserve the values of boolean attributes
  15943. * such as readonly. (Their presence means true and their absence means false.)
  15944. * If we put an Angular interpolation expression into such an attribute then the
  15945. * binding information would be lost when the browser removes the attribute.
  15946. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  15947. * This complementary directive is not removed by the browser and so provides
  15948. * a permanent reliable place to store the binding information.
  15949. * @example
  15950. <example>
  15951. <file name="index.html">
  15952. Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
  15953. <input type="text" ng-readonly="checked" value="I'm Angular"/>
  15954. </file>
  15955. <file name="protractor.js" type="protractor">
  15956. it('should toggle readonly attr', function() {
  15957. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  15958. element(by.model('checked')).click();
  15959. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  15960. });
  15961. </file>
  15962. </example>
  15963. *
  15964. * @element INPUT
  15965. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  15966. * then special attribute "readonly" will be set on the element
  15967. */
  15968. /**
  15969. * @ngdoc directive
  15970. * @name ngSelected
  15971. * @restrict A
  15972. * @priority 100
  15973. *
  15974. * @description
  15975. * The HTML specification does not require browsers to preserve the values of boolean attributes
  15976. * such as selected. (Their presence means true and their absence means false.)
  15977. * If we put an Angular interpolation expression into such an attribute then the
  15978. * binding information would be lost when the browser removes the attribute.
  15979. * The `ngSelected` directive solves this problem for the `selected` attribute.
  15980. * This complementary directive is not removed by the browser and so provides
  15981. * a permanent reliable place to store the binding information.
  15982. *
  15983. * @example
  15984. <example>
  15985. <file name="index.html">
  15986. Check me to select: <input type="checkbox" ng-model="selected"><br/>
  15987. <select>
  15988. <option>Hello!</option>
  15989. <option id="greet" ng-selected="selected">Greetings!</option>
  15990. </select>
  15991. </file>
  15992. <file name="protractor.js" type="protractor">
  15993. it('should select Greetings!', function() {
  15994. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  15995. element(by.model('selected')).click();
  15996. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  15997. });
  15998. </file>
  15999. </example>
  16000. *
  16001. * @element OPTION
  16002. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  16003. * then special attribute "selected" will be set on the element
  16004. */
  16005. /**
  16006. * @ngdoc directive
  16007. * @name ngOpen
  16008. * @restrict A
  16009. * @priority 100
  16010. *
  16011. * @description
  16012. * The HTML specification does not require browsers to preserve the values of boolean attributes
  16013. * such as open. (Their presence means true and their absence means false.)
  16014. * If we put an Angular interpolation expression into such an attribute then the
  16015. * binding information would be lost when the browser removes the attribute.
  16016. * The `ngOpen` directive solves this problem for the `open` attribute.
  16017. * This complementary directive is not removed by the browser and so provides
  16018. * a permanent reliable place to store the binding information.
  16019. * @example
  16020. <example>
  16021. <file name="index.html">
  16022. Check me check multiple: <input type="checkbox" ng-model="open"><br/>
  16023. <details id="details" ng-open="open">
  16024. <summary>Show/Hide me</summary>
  16025. </details>
  16026. </file>
  16027. <file name="protractor.js" type="protractor">
  16028. it('should toggle open', function() {
  16029. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  16030. element(by.model('open')).click();
  16031. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  16032. });
  16033. </file>
  16034. </example>
  16035. *
  16036. * @element DETAILS
  16037. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  16038. * then special attribute "open" will be set on the element
  16039. */
  16040. var ngAttributeAliasDirectives = {};
  16041. // boolean attrs are evaluated
  16042. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  16043. // binding to multiple is not supported
  16044. if (propName == "multiple") return;
  16045. var normalized = directiveNormalize('ng-' + attrName);
  16046. ngAttributeAliasDirectives[normalized] = function() {
  16047. return {
  16048. restrict: 'A',
  16049. priority: 100,
  16050. link: function(scope, element, attr) {
  16051. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  16052. attr.$set(attrName, !!value);
  16053. });
  16054. }
  16055. };
  16056. };
  16057. });
  16058. // aliased input attrs are evaluated
  16059. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  16060. ngAttributeAliasDirectives[ngAttr] = function() {
  16061. return {
  16062. priority: 100,
  16063. link: function(scope, element, attr) {
  16064. //special case ngPattern when a literal regular expression value
  16065. //is used as the expression (this way we don't have to watch anything).
  16066. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  16067. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  16068. if (match) {
  16069. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  16070. return;
  16071. }
  16072. }
  16073. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  16074. attr.$set(ngAttr, value);
  16075. });
  16076. }
  16077. };
  16078. };
  16079. });
  16080. // ng-src, ng-srcset, ng-href are interpolated
  16081. forEach(['src', 'srcset', 'href'], function(attrName) {
  16082. var normalized = directiveNormalize('ng-' + attrName);
  16083. ngAttributeAliasDirectives[normalized] = function() {
  16084. return {
  16085. priority: 99, // it needs to run after the attributes are interpolated
  16086. link: function(scope, element, attr) {
  16087. var propName = attrName,
  16088. name = attrName;
  16089. if (attrName === 'href' &&
  16090. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  16091. name = 'xlinkHref';
  16092. attr.$attr[name] = 'xlink:href';
  16093. propName = null;
  16094. }
  16095. attr.$observe(normalized, function(value) {
  16096. if (!value) {
  16097. if (attrName === 'href') {
  16098. attr.$set(name, null);
  16099. }
  16100. return;
  16101. }
  16102. attr.$set(name, value);
  16103. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  16104. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  16105. // to set the property as well to achieve the desired effect.
  16106. // we use attr[attrName] value since $set can sanitize the url.
  16107. if (msie && propName) element.prop(propName, attr[name]);
  16108. });
  16109. }
  16110. };
  16111. };
  16112. });
  16113. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  16114. */
  16115. var nullFormCtrl = {
  16116. $addControl: noop,
  16117. $$renameControl: nullFormRenameControl,
  16118. $removeControl: noop,
  16119. $setValidity: noop,
  16120. $setDirty: noop,
  16121. $setPristine: noop,
  16122. $setSubmitted: noop
  16123. },
  16124. SUBMITTED_CLASS = 'ng-submitted';
  16125. function nullFormRenameControl(control, name) {
  16126. control.$name = name;
  16127. }
  16128. /**
  16129. * @ngdoc type
  16130. * @name form.FormController
  16131. *
  16132. * @property {boolean} $pristine True if user has not interacted with the form yet.
  16133. * @property {boolean} $dirty True if user has already interacted with the form.
  16134. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  16135. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  16136. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  16137. *
  16138. * @property {Object} $error Is an object hash, containing references to controls or
  16139. * forms with failing validators, where:
  16140. *
  16141. * - keys are validation tokens (error names),
  16142. * - values are arrays of controls or forms that have a failing validator for given error name.
  16143. *
  16144. * Built-in validation tokens:
  16145. *
  16146. * - `email`
  16147. * - `max`
  16148. * - `maxlength`
  16149. * - `min`
  16150. * - `minlength`
  16151. * - `number`
  16152. * - `pattern`
  16153. * - `required`
  16154. * - `url`
  16155. *
  16156. * @description
  16157. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  16158. * such as being valid/invalid or dirty/pristine.
  16159. *
  16160. * Each {@link ng.directive:form form} directive creates an instance
  16161. * of `FormController`.
  16162. *
  16163. */
  16164. //asks for $scope to fool the BC controller module
  16165. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  16166. function FormController(element, attrs, $scope, $animate, $interpolate) {
  16167. var form = this,
  16168. controls = [];
  16169. var parentForm = form.$$parentForm = element.parent().controller('form') || nullFormCtrl;
  16170. // init state
  16171. form.$error = {};
  16172. form.$$success = {};
  16173. form.$pending = undefined;
  16174. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  16175. form.$dirty = false;
  16176. form.$pristine = true;
  16177. form.$valid = true;
  16178. form.$invalid = false;
  16179. form.$submitted = false;
  16180. parentForm.$addControl(form);
  16181. /**
  16182. * @ngdoc method
  16183. * @name form.FormController#$rollbackViewValue
  16184. *
  16185. * @description
  16186. * Rollback all form controls pending updates to the `$modelValue`.
  16187. *
  16188. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16189. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  16190. * a form that uses `ng-model-options` to pend updates.
  16191. */
  16192. form.$rollbackViewValue = function() {
  16193. forEach(controls, function(control) {
  16194. control.$rollbackViewValue();
  16195. });
  16196. };
  16197. /**
  16198. * @ngdoc method
  16199. * @name form.FormController#$commitViewValue
  16200. *
  16201. * @description
  16202. * Commit all form controls pending updates to the `$modelValue`.
  16203. *
  16204. * Updates may be pending by a debounced event or because the input is waiting for a some future
  16205. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  16206. * usually handles calling this in response to input events.
  16207. */
  16208. form.$commitViewValue = function() {
  16209. forEach(controls, function(control) {
  16210. control.$commitViewValue();
  16211. });
  16212. };
  16213. /**
  16214. * @ngdoc method
  16215. * @name form.FormController#$addControl
  16216. *
  16217. * @description
  16218. * Register a control with the form.
  16219. *
  16220. * Input elements using ngModelController do this automatically when they are linked.
  16221. */
  16222. form.$addControl = function(control) {
  16223. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  16224. // and not added to the scope. Now we throw an error.
  16225. assertNotHasOwnProperty(control.$name, 'input');
  16226. controls.push(control);
  16227. if (control.$name) {
  16228. form[control.$name] = control;
  16229. }
  16230. };
  16231. // Private API: rename a form control
  16232. form.$$renameControl = function(control, newName) {
  16233. var oldName = control.$name;
  16234. if (form[oldName] === control) {
  16235. delete form[oldName];
  16236. }
  16237. form[newName] = control;
  16238. control.$name = newName;
  16239. };
  16240. /**
  16241. * @ngdoc method
  16242. * @name form.FormController#$removeControl
  16243. *
  16244. * @description
  16245. * Deregister a control from the form.
  16246. *
  16247. * Input elements using ngModelController do this automatically when they are destroyed.
  16248. */
  16249. form.$removeControl = function(control) {
  16250. if (control.$name && form[control.$name] === control) {
  16251. delete form[control.$name];
  16252. }
  16253. forEach(form.$pending, function(value, name) {
  16254. form.$setValidity(name, null, control);
  16255. });
  16256. forEach(form.$error, function(value, name) {
  16257. form.$setValidity(name, null, control);
  16258. });
  16259. arrayRemove(controls, control);
  16260. };
  16261. /**
  16262. * @ngdoc method
  16263. * @name form.FormController#$setValidity
  16264. *
  16265. * @description
  16266. * Sets the validity of a form control.
  16267. *
  16268. * This method will also propagate to parent forms.
  16269. */
  16270. addSetValidityMethod({
  16271. ctrl: this,
  16272. $element: element,
  16273. set: function(object, property, control) {
  16274. var list = object[property];
  16275. if (!list) {
  16276. object[property] = [control];
  16277. } else {
  16278. var index = list.indexOf(control);
  16279. if (index === -1) {
  16280. list.push(control);
  16281. }
  16282. }
  16283. },
  16284. unset: function(object, property, control) {
  16285. var list = object[property];
  16286. if (!list) {
  16287. return;
  16288. }
  16289. arrayRemove(list, control);
  16290. if (list.length === 0) {
  16291. delete object[property];
  16292. }
  16293. },
  16294. parentForm: parentForm,
  16295. $animate: $animate
  16296. });
  16297. /**
  16298. * @ngdoc method
  16299. * @name form.FormController#$setDirty
  16300. *
  16301. * @description
  16302. * Sets the form to a dirty state.
  16303. *
  16304. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  16305. * state (ng-dirty class). This method will also propagate to parent forms.
  16306. */
  16307. form.$setDirty = function() {
  16308. $animate.removeClass(element, PRISTINE_CLASS);
  16309. $animate.addClass(element, DIRTY_CLASS);
  16310. form.$dirty = true;
  16311. form.$pristine = false;
  16312. parentForm.$setDirty();
  16313. };
  16314. /**
  16315. * @ngdoc method
  16316. * @name form.FormController#$setPristine
  16317. *
  16318. * @description
  16319. * Sets the form to its pristine state.
  16320. *
  16321. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  16322. * state (ng-pristine class). This method will also propagate to all the controls contained
  16323. * in this form.
  16324. *
  16325. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  16326. * saving or resetting it.
  16327. */
  16328. form.$setPristine = function () {
  16329. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  16330. form.$dirty = false;
  16331. form.$pristine = true;
  16332. form.$submitted = false;
  16333. forEach(controls, function(control) {
  16334. control.$setPristine();
  16335. });
  16336. };
  16337. /**
  16338. * @ngdoc method
  16339. * @name form.FormController#$setUntouched
  16340. *
  16341. * @description
  16342. * Sets the form to its untouched state.
  16343. *
  16344. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  16345. * untouched state (ng-untouched class).
  16346. *
  16347. * Setting a form controls back to their untouched state is often useful when setting the form
  16348. * back to its pristine state.
  16349. */
  16350. form.$setUntouched = function () {
  16351. forEach(controls, function(control) {
  16352. control.$setUntouched();
  16353. });
  16354. };
  16355. /**
  16356. * @ngdoc method
  16357. * @name form.FormController#$setSubmitted
  16358. *
  16359. * @description
  16360. * Sets the form to its submitted state.
  16361. */
  16362. form.$setSubmitted = function () {
  16363. $animate.addClass(element, SUBMITTED_CLASS);
  16364. form.$submitted = true;
  16365. parentForm.$setSubmitted();
  16366. };
  16367. }
  16368. /**
  16369. * @ngdoc directive
  16370. * @name ngForm
  16371. * @restrict EAC
  16372. *
  16373. * @description
  16374. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  16375. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  16376. * sub-group of controls needs to be determined.
  16377. *
  16378. * Note: the purpose of `ngForm` is to group controls,
  16379. * but not to be a replacement for the `<form>` tag with all of its capabilities
  16380. * (e.g. posting to the server, ...).
  16381. *
  16382. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  16383. * related scope, under this name.
  16384. *
  16385. */
  16386. /**
  16387. * @ngdoc directive
  16388. * @name form
  16389. * @restrict E
  16390. *
  16391. * @description
  16392. * Directive that instantiates
  16393. * {@link form.FormController FormController}.
  16394. *
  16395. * If the `name` attribute is specified, the form controller is published onto the current scope under
  16396. * this name.
  16397. *
  16398. * # Alias: {@link ng.directive:ngForm `ngForm`}
  16399. *
  16400. * In Angular forms can be nested. This means that the outer form is valid when all of the child
  16401. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  16402. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  16403. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  16404. * using Angular validation directives in forms that are dynamically generated using the
  16405. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  16406. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  16407. * `ngForm` directive and nest these in an outer `form` element.
  16408. *
  16409. *
  16410. * # CSS classes
  16411. * - `ng-valid` is set if the form is valid.
  16412. * - `ng-invalid` is set if the form is invalid.
  16413. * - `ng-pristine` is set if the form is pristine.
  16414. * - `ng-dirty` is set if the form is dirty.
  16415. * - `ng-submitted` is set if the form was submitted.
  16416. *
  16417. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  16418. *
  16419. *
  16420. * # Submitting a form and preventing the default action
  16421. *
  16422. * Since the role of forms in client-side Angular applications is different than in classical
  16423. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  16424. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  16425. * to handle the form submission in an application-specific way.
  16426. *
  16427. * For this reason, Angular prevents the default action (form submission to the server) unless the
  16428. * `<form>` element has an `action` attribute specified.
  16429. *
  16430. * You can use one of the following two ways to specify what javascript method should be called when
  16431. * a form is submitted:
  16432. *
  16433. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  16434. * - {@link ng.directive:ngClick ngClick} directive on the first
  16435. * button or input field of type submit (input[type=submit])
  16436. *
  16437. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  16438. * or {@link ng.directive:ngClick ngClick} directives.
  16439. * This is because of the following form submission rules in the HTML specification:
  16440. *
  16441. * - If a form has only one input field then hitting enter in this field triggers form submit
  16442. * (`ngSubmit`)
  16443. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  16444. * doesn't trigger submit
  16445. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  16446. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  16447. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  16448. *
  16449. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  16450. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  16451. * to have access to the updated model.
  16452. *
  16453. * ## Animation Hooks
  16454. *
  16455. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  16456. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  16457. * other validations that are performed within the form. Animations in ngForm are similar to how
  16458. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  16459. * as JS animations.
  16460. *
  16461. * The following example shows a simple way to utilize CSS transitions to style a form element
  16462. * that has been rendered as invalid after it has been validated:
  16463. *
  16464. * <pre>
  16465. * //be sure to include ngAnimate as a module to hook into more
  16466. * //advanced animations
  16467. * .my-form {
  16468. * transition:0.5s linear all;
  16469. * background: white;
  16470. * }
  16471. * .my-form.ng-invalid {
  16472. * background: red;
  16473. * color:white;
  16474. * }
  16475. * </pre>
  16476. *
  16477. * @example
  16478. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  16479. <file name="index.html">
  16480. <script>
  16481. angular.module('formExample', [])
  16482. .controller('FormController', ['$scope', function($scope) {
  16483. $scope.userType = 'guest';
  16484. }]);
  16485. </script>
  16486. <style>
  16487. .my-form {
  16488. -webkit-transition:all linear 0.5s;
  16489. transition:all linear 0.5s;
  16490. background: transparent;
  16491. }
  16492. .my-form.ng-invalid {
  16493. background: red;
  16494. }
  16495. </style>
  16496. <form name="myForm" ng-controller="FormController" class="my-form">
  16497. userType: <input name="input" ng-model="userType" required>
  16498. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  16499. <tt>userType = {{userType}}</tt><br>
  16500. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
  16501. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
  16502. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  16503. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  16504. </form>
  16505. </file>
  16506. <file name="protractor.js" type="protractor">
  16507. it('should initialize to model', function() {
  16508. var userType = element(by.binding('userType'));
  16509. var valid = element(by.binding('myForm.input.$valid'));
  16510. expect(userType.getText()).toContain('guest');
  16511. expect(valid.getText()).toContain('true');
  16512. });
  16513. it('should be invalid if empty', function() {
  16514. var userType = element(by.binding('userType'));
  16515. var valid = element(by.binding('myForm.input.$valid'));
  16516. var userInput = element(by.model('userType'));
  16517. userInput.clear();
  16518. userInput.sendKeys('');
  16519. expect(userType.getText()).toEqual('userType =');
  16520. expect(valid.getText()).toContain('false');
  16521. });
  16522. </file>
  16523. </example>
  16524. *
  16525. * @param {string=} name Name of the form. If specified, the form controller will be published into
  16526. * related scope, under this name.
  16527. */
  16528. var formDirectiveFactory = function(isNgForm) {
  16529. return ['$timeout', function($timeout) {
  16530. var formDirective = {
  16531. name: 'form',
  16532. restrict: isNgForm ? 'EAC' : 'E',
  16533. controller: FormController,
  16534. compile: function ngFormCompile(formElement) {
  16535. // Setup initial state of the control
  16536. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  16537. return {
  16538. pre: function ngFormPreLink(scope, formElement, attr, controller) {
  16539. // if `action` attr is not present on the form, prevent the default action (submission)
  16540. if (!('action' in attr)) {
  16541. // we can't use jq events because if a form is destroyed during submission the default
  16542. // action is not prevented. see #1238
  16543. //
  16544. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  16545. // page reload if the form was destroyed by submission of the form via a click handler
  16546. // on a button in the form. Looks like an IE9 specific bug.
  16547. var handleFormSubmission = function(event) {
  16548. scope.$apply(function() {
  16549. controller.$commitViewValue();
  16550. controller.$setSubmitted();
  16551. });
  16552. event.preventDefault
  16553. ? event.preventDefault()
  16554. : event.returnValue = false; // IE
  16555. };
  16556. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16557. // unregister the preventDefault listener so that we don't not leak memory but in a
  16558. // way that will achieve the prevention of the default action.
  16559. formElement.on('$destroy', function() {
  16560. $timeout(function() {
  16561. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  16562. }, 0, false);
  16563. });
  16564. }
  16565. var parentFormCtrl = controller.$$parentForm,
  16566. alias = controller.$name;
  16567. if (alias) {
  16568. setter(scope, alias, controller, alias);
  16569. attr.$observe(attr.name ? 'name' : 'ngForm', function(newValue) {
  16570. if (alias === newValue) return;
  16571. setter(scope, alias, undefined, alias);
  16572. alias = newValue;
  16573. setter(scope, alias, controller, alias);
  16574. parentFormCtrl.$$renameControl(controller, alias);
  16575. });
  16576. }
  16577. formElement.on('$destroy', function() {
  16578. parentFormCtrl.$removeControl(controller);
  16579. if (alias) {
  16580. setter(scope, alias, undefined, alias);
  16581. }
  16582. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  16583. });
  16584. }
  16585. };
  16586. }
  16587. };
  16588. return formDirective;
  16589. }];
  16590. };
  16591. var formDirective = formDirectiveFactory();
  16592. var ngFormDirective = formDirectiveFactory(true);
  16593. /* global VALID_CLASS: true,
  16594. INVALID_CLASS: true,
  16595. PRISTINE_CLASS: true,
  16596. DIRTY_CLASS: true,
  16597. UNTOUCHED_CLASS: true,
  16598. TOUCHED_CLASS: true,
  16599. */
  16600. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  16601. var ISO_DATE_REGEXP = /\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z)/;
  16602. var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
  16603. 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;
  16604. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
  16605. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  16606. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16607. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  16608. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  16609. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  16610. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  16611. var $ngModelMinErr = new minErr('ngModel');
  16612. var inputType = {
  16613. /**
  16614. * @ngdoc input
  16615. * @name input[text]
  16616. *
  16617. * @description
  16618. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  16619. *
  16620. * *NOTE* Not every feature offered is available for all input types.
  16621. *
  16622. * @param {string} ngModel Assignable angular expression to data-bind to.
  16623. * @param {string=} name Property name of the form under which the control is published.
  16624. * @param {string=} required Adds `required` validation error key if the value is not entered.
  16625. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16626. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16627. * `required` when you want to data-bind to the `required` attribute.
  16628. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  16629. * minlength.
  16630. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  16631. * maxlength.
  16632. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  16633. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  16634. * patterns defined as scope expressions.
  16635. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16636. * interaction with the input element.
  16637. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  16638. * This parameter is ignored for input[type=password] controls, which will never trim the
  16639. * input.
  16640. *
  16641. * @example
  16642. <example name="text-input-directive" module="textInputExample">
  16643. <file name="index.html">
  16644. <script>
  16645. angular.module('textInputExample', [])
  16646. .controller('ExampleController', ['$scope', function($scope) {
  16647. $scope.text = 'guest';
  16648. $scope.word = /^\s*\w*\s*$/;
  16649. }]);
  16650. </script>
  16651. <form name="myForm" ng-controller="ExampleController">
  16652. Single word: <input type="text" name="input" ng-model="text"
  16653. ng-pattern="word" required ng-trim="false">
  16654. <span class="error" ng-show="myForm.input.$error.required">
  16655. Required!</span>
  16656. <span class="error" ng-show="myForm.input.$error.pattern">
  16657. Single word only!</span>
  16658. <tt>text = {{text}}</tt><br/>
  16659. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16660. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16661. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16662. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16663. </form>
  16664. </file>
  16665. <file name="protractor.js" type="protractor">
  16666. var text = element(by.binding('text'));
  16667. var valid = element(by.binding('myForm.input.$valid'));
  16668. var input = element(by.model('text'));
  16669. it('should initialize to model', function() {
  16670. expect(text.getText()).toContain('guest');
  16671. expect(valid.getText()).toContain('true');
  16672. });
  16673. it('should be invalid if empty', function() {
  16674. input.clear();
  16675. input.sendKeys('');
  16676. expect(text.getText()).toEqual('text =');
  16677. expect(valid.getText()).toContain('false');
  16678. });
  16679. it('should be invalid if multi word', function() {
  16680. input.clear();
  16681. input.sendKeys('hello world');
  16682. expect(valid.getText()).toContain('false');
  16683. });
  16684. </file>
  16685. </example>
  16686. */
  16687. 'text': textInputType,
  16688. /**
  16689. * @ngdoc input
  16690. * @name input[date]
  16691. *
  16692. * @description
  16693. * Input with date validation and transformation. In browsers that do not yet support
  16694. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  16695. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  16696. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  16697. * expected input format via a placeholder or label. The model must always be a Date object.
  16698. *
  16699. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16700. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16701. *
  16702. * @param {string} ngModel Assignable angular expression to data-bind to.
  16703. * @param {string=} name Property name of the form under which the control is published.
  16704. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16705. * valid ISO date string (yyyy-MM-dd).
  16706. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16707. * a valid ISO date string (yyyy-MM-dd).
  16708. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16709. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16710. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16711. * `required` when you want to data-bind to the `required` attribute.
  16712. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16713. * interaction with the input element.
  16714. *
  16715. * @example
  16716. <example name="date-input-directive" module="dateInputExample">
  16717. <file name="index.html">
  16718. <script>
  16719. angular.module('dateInputExample', [])
  16720. .controller('DateController', ['$scope', function($scope) {
  16721. $scope.value = new Date(2013, 9, 22);
  16722. }]);
  16723. </script>
  16724. <form name="myForm" ng-controller="DateController as dateCtrl">
  16725. Pick a date in 2013:
  16726. <input type="date" id="exampleInput" name="input" ng-model="value"
  16727. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  16728. <span class="error" ng-show="myForm.input.$error.required">
  16729. Required!</span>
  16730. <span class="error" ng-show="myForm.input.$error.date">
  16731. Not a valid date!</span>
  16732. <tt>value = {{value | date: "yyyy-MM-dd"}}</tt><br/>
  16733. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16734. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16735. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16736. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16737. </form>
  16738. </file>
  16739. <file name="protractor.js" type="protractor">
  16740. var value = element(by.binding('value | date: "yyyy-MM-dd"'));
  16741. var valid = element(by.binding('myForm.input.$valid'));
  16742. var input = element(by.model('value'));
  16743. // currently protractor/webdriver does not support
  16744. // sending keys to all known HTML5 input controls
  16745. // for various browsers (see https://github.com/angular/protractor/issues/562).
  16746. function setInput(val) {
  16747. // set the value of the element and force validation.
  16748. var scr = "var ipt = document.getElementById('exampleInput'); " +
  16749. "ipt.value = '" + val + "';" +
  16750. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  16751. browser.executeScript(scr);
  16752. }
  16753. it('should initialize to model', function() {
  16754. expect(value.getText()).toContain('2013-10-22');
  16755. expect(valid.getText()).toContain('myForm.input.$valid = true');
  16756. });
  16757. it('should be invalid if empty', function() {
  16758. setInput('');
  16759. expect(value.getText()).toEqual('value =');
  16760. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16761. });
  16762. it('should be invalid if over max', function() {
  16763. setInput('2015-01-01');
  16764. expect(value.getText()).toContain('');
  16765. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16766. });
  16767. </file>
  16768. </example>
  16769. */
  16770. 'date': createDateInputType('date', DATE_REGEXP,
  16771. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  16772. 'yyyy-MM-dd'),
  16773. /**
  16774. * @ngdoc input
  16775. * @name input[dateTimeLocal]
  16776. *
  16777. * @description
  16778. * Input with datetime validation and transformation. In browsers that do not yet support
  16779. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  16780. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`. The model must be a Date object.
  16781. *
  16782. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16783. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16784. *
  16785. * @param {string} ngModel Assignable angular expression to data-bind to.
  16786. * @param {string=} name Property name of the form under which the control is published.
  16787. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16788. * valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  16789. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16790. * a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss).
  16791. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16792. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16793. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16794. * `required` when you want to data-bind to the `required` attribute.
  16795. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16796. * interaction with the input element.
  16797. *
  16798. * @example
  16799. <example name="datetimelocal-input-directive" module="dateExample">
  16800. <file name="index.html">
  16801. <script>
  16802. angular.module('dateExample', [])
  16803. .controller('DateController', ['$scope', function($scope) {
  16804. $scope.value = new Date(2010, 11, 28, 14, 57);
  16805. }]);
  16806. </script>
  16807. <form name="myForm" ng-controller="DateController as dateCtrl">
  16808. Pick a date between in 2013:
  16809. <input type="datetime-local" id="exampleInput" name="input" ng-model="value"
  16810. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  16811. <span class="error" ng-show="myForm.input.$error.required">
  16812. Required!</span>
  16813. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  16814. Not a valid date!</span>
  16815. <tt>value = {{value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  16816. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16817. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16818. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16819. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16820. </form>
  16821. </file>
  16822. <file name="protractor.js" type="protractor">
  16823. var value = element(by.binding('value | date: "yyyy-MM-ddTHH:mm:ss"'));
  16824. var valid = element(by.binding('myForm.input.$valid'));
  16825. var input = element(by.model('value'));
  16826. // currently protractor/webdriver does not support
  16827. // sending keys to all known HTML5 input controls
  16828. // for various browsers (https://github.com/angular/protractor/issues/562).
  16829. function setInput(val) {
  16830. // set the value of the element and force validation.
  16831. var scr = "var ipt = document.getElementById('exampleInput'); " +
  16832. "ipt.value = '" + val + "';" +
  16833. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  16834. browser.executeScript(scr);
  16835. }
  16836. it('should initialize to model', function() {
  16837. expect(value.getText()).toContain('2010-12-28T14:57:00');
  16838. expect(valid.getText()).toContain('myForm.input.$valid = true');
  16839. });
  16840. it('should be invalid if empty', function() {
  16841. setInput('');
  16842. expect(value.getText()).toEqual('value =');
  16843. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16844. });
  16845. it('should be invalid if over max', function() {
  16846. setInput('2015-01-01T23:59:00');
  16847. expect(value.getText()).toContain('');
  16848. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16849. });
  16850. </file>
  16851. </example>
  16852. */
  16853. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  16854. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  16855. 'yyyy-MM-ddTHH:mm:ss.sss'),
  16856. /**
  16857. * @ngdoc input
  16858. * @name input[time]
  16859. *
  16860. * @description
  16861. * Input with time validation and transformation. In browsers that do not yet support
  16862. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  16863. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  16864. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  16865. *
  16866. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16867. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16868. *
  16869. * @param {string} ngModel Assignable angular expression to data-bind to.
  16870. * @param {string=} name Property name of the form under which the control is published.
  16871. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16872. * valid ISO time format (HH:mm:ss).
  16873. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be a
  16874. * valid ISO time format (HH:mm:ss).
  16875. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16876. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16877. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16878. * `required` when you want to data-bind to the `required` attribute.
  16879. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16880. * interaction with the input element.
  16881. *
  16882. * @example
  16883. <example name="time-input-directive" module="timeExample">
  16884. <file name="index.html">
  16885. <script>
  16886. angular.module('timeExample', [])
  16887. .controller('DateController', ['$scope', function($scope) {
  16888. $scope.value = new Date(1970, 0, 1, 14, 57, 0);
  16889. }]);
  16890. </script>
  16891. <form name="myForm" ng-controller="DateController as dateCtrl">
  16892. Pick a between 8am and 5pm:
  16893. <input type="time" id="exampleInput" name="input" ng-model="value"
  16894. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  16895. <span class="error" ng-show="myForm.input.$error.required">
  16896. Required!</span>
  16897. <span class="error" ng-show="myForm.input.$error.time">
  16898. Not a valid date!</span>
  16899. <tt>value = {{value | date: "HH:mm:ss"}}</tt><br/>
  16900. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16901. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16902. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16903. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16904. </form>
  16905. </file>
  16906. <file name="protractor.js" type="protractor">
  16907. var value = element(by.binding('value | date: "HH:mm:ss"'));
  16908. var valid = element(by.binding('myForm.input.$valid'));
  16909. var input = element(by.model('value'));
  16910. // currently protractor/webdriver does not support
  16911. // sending keys to all known HTML5 input controls
  16912. // for various browsers (https://github.com/angular/protractor/issues/562).
  16913. function setInput(val) {
  16914. // set the value of the element and force validation.
  16915. var scr = "var ipt = document.getElementById('exampleInput'); " +
  16916. "ipt.value = '" + val + "';" +
  16917. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  16918. browser.executeScript(scr);
  16919. }
  16920. it('should initialize to model', function() {
  16921. expect(value.getText()).toContain('14:57:00');
  16922. expect(valid.getText()).toContain('myForm.input.$valid = true');
  16923. });
  16924. it('should be invalid if empty', function() {
  16925. setInput('');
  16926. expect(value.getText()).toEqual('value =');
  16927. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16928. });
  16929. it('should be invalid if over max', function() {
  16930. setInput('23:59:00');
  16931. expect(value.getText()).toContain('');
  16932. expect(valid.getText()).toContain('myForm.input.$valid = false');
  16933. });
  16934. </file>
  16935. </example>
  16936. */
  16937. 'time': createDateInputType('time', TIME_REGEXP,
  16938. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  16939. 'HH:mm:ss.sss'),
  16940. /**
  16941. * @ngdoc input
  16942. * @name input[week]
  16943. *
  16944. * @description
  16945. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  16946. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  16947. * week format (yyyy-W##), for example: `2013-W02`. The model must always be a Date object.
  16948. *
  16949. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  16950. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  16951. *
  16952. * @param {string} ngModel Assignable angular expression to data-bind to.
  16953. * @param {string=} name Property name of the form under which the control is published.
  16954. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  16955. * valid ISO week format (yyyy-W##).
  16956. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  16957. * a valid ISO week format (yyyy-W##).
  16958. * @param {string=} required Sets `required` validation error key if the value is not entered.
  16959. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  16960. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  16961. * `required` when you want to data-bind to the `required` attribute.
  16962. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  16963. * interaction with the input element.
  16964. *
  16965. * @example
  16966. <example name="week-input-directive" module="weekExample">
  16967. <file name="index.html">
  16968. <script>
  16969. angular.module('weekExample', [])
  16970. .controller('DateController', ['$scope', function($scope) {
  16971. $scope.value = new Date(2013, 0, 3);
  16972. }]);
  16973. </script>
  16974. <form name="myForm" ng-controller="DateController as dateCtrl">
  16975. Pick a date between in 2013:
  16976. <input id="exampleInput" type="week" name="input" ng-model="value"
  16977. placeholder="YYYY-W##" min="2012-W32" max="2013-W52" required />
  16978. <span class="error" ng-show="myForm.input.$error.required">
  16979. Required!</span>
  16980. <span class="error" ng-show="myForm.input.$error.week">
  16981. Not a valid date!</span>
  16982. <tt>value = {{value | date: "yyyy-Www"}}</tt><br/>
  16983. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  16984. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  16985. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  16986. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  16987. </form>
  16988. </file>
  16989. <file name="protractor.js" type="protractor">
  16990. var value = element(by.binding('value | date: "yyyy-Www"'));
  16991. var valid = element(by.binding('myForm.input.$valid'));
  16992. var input = element(by.model('value'));
  16993. // currently protractor/webdriver does not support
  16994. // sending keys to all known HTML5 input controls
  16995. // for various browsers (https://github.com/angular/protractor/issues/562).
  16996. function setInput(val) {
  16997. // set the value of the element and force validation.
  16998. var scr = "var ipt = document.getElementById('exampleInput'); " +
  16999. "ipt.value = '" + val + "';" +
  17000. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17001. browser.executeScript(scr);
  17002. }
  17003. it('should initialize to model', function() {
  17004. expect(value.getText()).toContain('2013-W01');
  17005. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17006. });
  17007. it('should be invalid if empty', function() {
  17008. setInput('');
  17009. expect(value.getText()).toEqual('value =');
  17010. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17011. });
  17012. it('should be invalid if over max', function() {
  17013. setInput('2015-W01');
  17014. expect(value.getText()).toContain('');
  17015. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17016. });
  17017. </file>
  17018. </example>
  17019. */
  17020. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  17021. /**
  17022. * @ngdoc input
  17023. * @name input[month]
  17024. *
  17025. * @description
  17026. * Input with month validation and transformation. In browsers that do not yet support
  17027. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  17028. * month format (yyyy-MM), for example: `2009-01`. The model must always be a Date object. In the event the model is
  17029. * not set to the first of the month, the first of that model's month is assumed.
  17030. *
  17031. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  17032. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  17033. *
  17034. * @param {string} ngModel Assignable angular expression to data-bind to.
  17035. * @param {string=} name Property name of the form under which the control is published.
  17036. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be
  17037. * a valid ISO month format (yyyy-MM).
  17038. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must
  17039. * be a valid ISO month format (yyyy-MM).
  17040. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17041. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17042. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17043. * `required` when you want to data-bind to the `required` attribute.
  17044. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17045. * interaction with the input element.
  17046. *
  17047. * @example
  17048. <example name="month-input-directive" module="monthExample">
  17049. <file name="index.html">
  17050. <script>
  17051. angular.module('monthExample', [])
  17052. .controller('DateController', ['$scope', function($scope) {
  17053. $scope.value = new Date(2013, 9, 1);
  17054. }]);
  17055. </script>
  17056. <form name="myForm" ng-controller="DateController as dateCtrl">
  17057. Pick a month int 2013:
  17058. <input id="exampleInput" type="month" name="input" ng-model="value"
  17059. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  17060. <span class="error" ng-show="myForm.input.$error.required">
  17061. Required!</span>
  17062. <span class="error" ng-show="myForm.input.$error.month">
  17063. Not a valid month!</span>
  17064. <tt>value = {{value | date: "yyyy-MM"}}</tt><br/>
  17065. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17066. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17067. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17068. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17069. </form>
  17070. </file>
  17071. <file name="protractor.js" type="protractor">
  17072. var value = element(by.binding('value | date: "yyyy-MM"'));
  17073. var valid = element(by.binding('myForm.input.$valid'));
  17074. var input = element(by.model('value'));
  17075. // currently protractor/webdriver does not support
  17076. // sending keys to all known HTML5 input controls
  17077. // for various browsers (https://github.com/angular/protractor/issues/562).
  17078. function setInput(val) {
  17079. // set the value of the element and force validation.
  17080. var scr = "var ipt = document.getElementById('exampleInput'); " +
  17081. "ipt.value = '" + val + "';" +
  17082. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  17083. browser.executeScript(scr);
  17084. }
  17085. it('should initialize to model', function() {
  17086. expect(value.getText()).toContain('2013-10');
  17087. expect(valid.getText()).toContain('myForm.input.$valid = true');
  17088. });
  17089. it('should be invalid if empty', function() {
  17090. setInput('');
  17091. expect(value.getText()).toEqual('value =');
  17092. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17093. });
  17094. it('should be invalid if over max', function() {
  17095. setInput('2015-01');
  17096. expect(value.getText()).toContain('');
  17097. expect(valid.getText()).toContain('myForm.input.$valid = false');
  17098. });
  17099. </file>
  17100. </example>
  17101. */
  17102. 'month': createDateInputType('month', MONTH_REGEXP,
  17103. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  17104. 'yyyy-MM'),
  17105. /**
  17106. * @ngdoc input
  17107. * @name input[number]
  17108. *
  17109. * @description
  17110. * Text input with number validation and transformation. Sets the `number` validation
  17111. * error if not a valid number.
  17112. *
  17113. * @param {string} ngModel Assignable angular expression to data-bind to.
  17114. * @param {string=} name Property name of the form under which the control is published.
  17115. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  17116. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  17117. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17118. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17119. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17120. * `required` when you want to data-bind to the `required` attribute.
  17121. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17122. * minlength.
  17123. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17124. * maxlength.
  17125. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17126. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17127. * patterns defined as scope expressions.
  17128. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17129. * interaction with the input element.
  17130. *
  17131. * @example
  17132. <example name="number-input-directive" module="numberExample">
  17133. <file name="index.html">
  17134. <script>
  17135. angular.module('numberExample', [])
  17136. .controller('ExampleController', ['$scope', function($scope) {
  17137. $scope.value = 12;
  17138. }]);
  17139. </script>
  17140. <form name="myForm" ng-controller="ExampleController">
  17141. Number: <input type="number" name="input" ng-model="value"
  17142. min="0" max="99" required>
  17143. <span class="error" ng-show="myForm.input.$error.required">
  17144. Required!</span>
  17145. <span class="error" ng-show="myForm.input.$error.number">
  17146. Not valid number!</span>
  17147. <tt>value = {{value}}</tt><br/>
  17148. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17149. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17150. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17151. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17152. </form>
  17153. </file>
  17154. <file name="protractor.js" type="protractor">
  17155. var value = element(by.binding('value'));
  17156. var valid = element(by.binding('myForm.input.$valid'));
  17157. var input = element(by.model('value'));
  17158. it('should initialize to model', function() {
  17159. expect(value.getText()).toContain('12');
  17160. expect(valid.getText()).toContain('true');
  17161. });
  17162. it('should be invalid if empty', function() {
  17163. input.clear();
  17164. input.sendKeys('');
  17165. expect(value.getText()).toEqual('value =');
  17166. expect(valid.getText()).toContain('false');
  17167. });
  17168. it('should be invalid if over max', function() {
  17169. input.clear();
  17170. input.sendKeys('123');
  17171. expect(value.getText()).toEqual('value =');
  17172. expect(valid.getText()).toContain('false');
  17173. });
  17174. </file>
  17175. </example>
  17176. */
  17177. 'number': numberInputType,
  17178. /**
  17179. * @ngdoc input
  17180. * @name input[url]
  17181. *
  17182. * @description
  17183. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  17184. * valid URL.
  17185. *
  17186. * @param {string} ngModel Assignable angular expression to data-bind to.
  17187. * @param {string=} name Property name of the form under which the control is published.
  17188. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17189. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17190. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17191. * `required` when you want to data-bind to the `required` attribute.
  17192. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17193. * minlength.
  17194. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17195. * maxlength.
  17196. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17197. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17198. * patterns defined as scope expressions.
  17199. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17200. * interaction with the input element.
  17201. *
  17202. * @example
  17203. <example name="url-input-directive" module="urlExample">
  17204. <file name="index.html">
  17205. <script>
  17206. angular.module('urlExample', [])
  17207. .controller('ExampleController', ['$scope', function($scope) {
  17208. $scope.text = 'http://google.com';
  17209. }]);
  17210. </script>
  17211. <form name="myForm" ng-controller="ExampleController">
  17212. URL: <input type="url" name="input" ng-model="text" required>
  17213. <span class="error" ng-show="myForm.input.$error.required">
  17214. Required!</span>
  17215. <span class="error" ng-show="myForm.input.$error.url">
  17216. Not valid url!</span>
  17217. <tt>text = {{text}}</tt><br/>
  17218. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17219. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17220. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17221. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17222. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  17223. </form>
  17224. </file>
  17225. <file name="protractor.js" type="protractor">
  17226. var text = element(by.binding('text'));
  17227. var valid = element(by.binding('myForm.input.$valid'));
  17228. var input = element(by.model('text'));
  17229. it('should initialize to model', function() {
  17230. expect(text.getText()).toContain('http://google.com');
  17231. expect(valid.getText()).toContain('true');
  17232. });
  17233. it('should be invalid if empty', function() {
  17234. input.clear();
  17235. input.sendKeys('');
  17236. expect(text.getText()).toEqual('text =');
  17237. expect(valid.getText()).toContain('false');
  17238. });
  17239. it('should be invalid if not url', function() {
  17240. input.clear();
  17241. input.sendKeys('box');
  17242. expect(valid.getText()).toContain('false');
  17243. });
  17244. </file>
  17245. </example>
  17246. */
  17247. 'url': urlInputType,
  17248. /**
  17249. * @ngdoc input
  17250. * @name input[email]
  17251. *
  17252. * @description
  17253. * Text input with email validation. Sets the `email` validation error key if not a valid email
  17254. * address.
  17255. *
  17256. * @param {string} ngModel Assignable angular expression to data-bind to.
  17257. * @param {string=} name Property name of the form under which the control is published.
  17258. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17259. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17260. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17261. * `required` when you want to data-bind to the `required` attribute.
  17262. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17263. * minlength.
  17264. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17265. * maxlength.
  17266. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17267. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17268. * patterns defined as scope expressions.
  17269. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17270. * interaction with the input element.
  17271. *
  17272. * @example
  17273. <example name="email-input-directive" module="emailExample">
  17274. <file name="index.html">
  17275. <script>
  17276. angular.module('emailExample', [])
  17277. .controller('ExampleController', ['$scope', function($scope) {
  17278. $scope.text = 'me@example.com';
  17279. }]);
  17280. </script>
  17281. <form name="myForm" ng-controller="ExampleController">
  17282. Email: <input type="email" name="input" ng-model="text" required>
  17283. <span class="error" ng-show="myForm.input.$error.required">
  17284. Required!</span>
  17285. <span class="error" ng-show="myForm.input.$error.email">
  17286. Not valid email!</span>
  17287. <tt>text = {{text}}</tt><br/>
  17288. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  17289. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  17290. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  17291. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  17292. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  17293. </form>
  17294. </file>
  17295. <file name="protractor.js" type="protractor">
  17296. var text = element(by.binding('text'));
  17297. var valid = element(by.binding('myForm.input.$valid'));
  17298. var input = element(by.model('text'));
  17299. it('should initialize to model', function() {
  17300. expect(text.getText()).toContain('me@example.com');
  17301. expect(valid.getText()).toContain('true');
  17302. });
  17303. it('should be invalid if empty', function() {
  17304. input.clear();
  17305. input.sendKeys('');
  17306. expect(text.getText()).toEqual('text =');
  17307. expect(valid.getText()).toContain('false');
  17308. });
  17309. it('should be invalid if not email', function() {
  17310. input.clear();
  17311. input.sendKeys('xxx');
  17312. expect(valid.getText()).toContain('false');
  17313. });
  17314. </file>
  17315. </example>
  17316. */
  17317. 'email': emailInputType,
  17318. /**
  17319. * @ngdoc input
  17320. * @name input[radio]
  17321. *
  17322. * @description
  17323. * HTML radio button.
  17324. *
  17325. * @param {string} ngModel Assignable angular expression to data-bind to.
  17326. * @param {string} value The value to which the expression should be set when selected.
  17327. * @param {string=} name Property name of the form under which the control is published.
  17328. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17329. * interaction with the input element.
  17330. * @param {string} ngValue Angular expression which sets the value to which the expression should
  17331. * be set when selected.
  17332. *
  17333. * @example
  17334. <example name="radio-input-directive" module="radioExample">
  17335. <file name="index.html">
  17336. <script>
  17337. angular.module('radioExample', [])
  17338. .controller('ExampleController', ['$scope', function($scope) {
  17339. $scope.color = 'blue';
  17340. $scope.specialValue = {
  17341. "id": "12345",
  17342. "value": "green"
  17343. };
  17344. }]);
  17345. </script>
  17346. <form name="myForm" ng-controller="ExampleController">
  17347. <input type="radio" ng-model="color" value="red"> Red <br/>
  17348. <input type="radio" ng-model="color" ng-value="specialValue"> Green <br/>
  17349. <input type="radio" ng-model="color" value="blue"> Blue <br/>
  17350. <tt>color = {{color | json}}</tt><br/>
  17351. </form>
  17352. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  17353. </file>
  17354. <file name="protractor.js" type="protractor">
  17355. it('should change state', function() {
  17356. var color = element(by.binding('color'));
  17357. expect(color.getText()).toContain('blue');
  17358. element.all(by.model('color')).get(0).click();
  17359. expect(color.getText()).toContain('red');
  17360. });
  17361. </file>
  17362. </example>
  17363. */
  17364. 'radio': radioInputType,
  17365. /**
  17366. * @ngdoc input
  17367. * @name input[checkbox]
  17368. *
  17369. * @description
  17370. * HTML checkbox.
  17371. *
  17372. * @param {string} ngModel Assignable angular expression to data-bind to.
  17373. * @param {string=} name Property name of the form under which the control is published.
  17374. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  17375. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  17376. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17377. * interaction with the input element.
  17378. *
  17379. * @example
  17380. <example name="checkbox-input-directive" module="checkboxExample">
  17381. <file name="index.html">
  17382. <script>
  17383. angular.module('checkboxExample', [])
  17384. .controller('ExampleController', ['$scope', function($scope) {
  17385. $scope.value1 = true;
  17386. $scope.value2 = 'YES'
  17387. }]);
  17388. </script>
  17389. <form name="myForm" ng-controller="ExampleController">
  17390. Value1: <input type="checkbox" ng-model="value1"> <br/>
  17391. Value2: <input type="checkbox" ng-model="value2"
  17392. ng-true-value="'YES'" ng-false-value="'NO'"> <br/>
  17393. <tt>value1 = {{value1}}</tt><br/>
  17394. <tt>value2 = {{value2}}</tt><br/>
  17395. </form>
  17396. </file>
  17397. <file name="protractor.js" type="protractor">
  17398. it('should change state', function() {
  17399. var value1 = element(by.binding('value1'));
  17400. var value2 = element(by.binding('value2'));
  17401. expect(value1.getText()).toContain('true');
  17402. expect(value2.getText()).toContain('YES');
  17403. element(by.model('value1')).click();
  17404. element(by.model('value2')).click();
  17405. expect(value1.getText()).toContain('false');
  17406. expect(value2.getText()).toContain('NO');
  17407. });
  17408. </file>
  17409. </example>
  17410. */
  17411. 'checkbox': checkboxInputType,
  17412. 'hidden': noop,
  17413. 'button': noop,
  17414. 'submit': noop,
  17415. 'reset': noop,
  17416. 'file': noop
  17417. };
  17418. function testFlags(validity, flags) {
  17419. var i, flag;
  17420. if (flags) {
  17421. for (i=0; i<flags.length; ++i) {
  17422. flag = flags[i];
  17423. if (validity[flag]) {
  17424. return true;
  17425. }
  17426. }
  17427. }
  17428. return false;
  17429. }
  17430. function stringBasedInputType(ctrl) {
  17431. ctrl.$formatters.push(function(value) {
  17432. return ctrl.$isEmpty(value) ? value : value.toString();
  17433. });
  17434. }
  17435. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17436. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17437. stringBasedInputType(ctrl);
  17438. }
  17439. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17440. var validity = element.prop(VALIDITY_STATE_PROPERTY);
  17441. var placeholder = element[0].placeholder, noevent = {};
  17442. var type = lowercase(element[0].type);
  17443. // In composition mode, users are still inputing intermediate text buffer,
  17444. // hold the listener until composition is done.
  17445. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  17446. if (!$sniffer.android) {
  17447. var composing = false;
  17448. element.on('compositionstart', function(data) {
  17449. composing = true;
  17450. });
  17451. element.on('compositionend', function() {
  17452. composing = false;
  17453. listener();
  17454. });
  17455. }
  17456. var listener = function(ev) {
  17457. if (composing) return;
  17458. var value = element.val(),
  17459. event = ev && ev.type;
  17460. // IE (11 and under) seem to emit an 'input' event if the placeholder value changes.
  17461. // We don't want to dirty the value when this happens, so we abort here. Unfortunately,
  17462. // IE also sends input events for other non-input-related things, (such as focusing on a
  17463. // form control), so this change is not entirely enough to solve this.
  17464. if (msie && (ev || noevent).type === 'input' && element[0].placeholder !== placeholder) {
  17465. placeholder = element[0].placeholder;
  17466. return;
  17467. }
  17468. // By default we will trim the value
  17469. // If the attribute ng-trim exists we will avoid trimming
  17470. // If input type is 'password', the value is never trimmed
  17471. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  17472. value = trim(value);
  17473. }
  17474. // If a control is suffering from bad input (due to native validators), browsers discard its
  17475. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  17476. // control's value is the same empty value twice in a row.
  17477. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  17478. ctrl.$setViewValue(value, event);
  17479. }
  17480. };
  17481. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  17482. // input event on backspace, delete or cut
  17483. if ($sniffer.hasEvent('input')) {
  17484. element.on('input', listener);
  17485. } else {
  17486. var timeout;
  17487. var deferListener = function(ev) {
  17488. if (!timeout) {
  17489. timeout = $browser.defer(function() {
  17490. listener(ev);
  17491. timeout = null;
  17492. });
  17493. }
  17494. };
  17495. element.on('keydown', function(event) {
  17496. var key = event.keyCode;
  17497. // ignore
  17498. // command modifiers arrows
  17499. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  17500. deferListener(event);
  17501. });
  17502. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  17503. if ($sniffer.hasEvent('paste')) {
  17504. element.on('paste cut', deferListener);
  17505. }
  17506. }
  17507. // if user paste into input using mouse on older browser
  17508. // or form autocomplete on newer browser, we need "change" event to catch it
  17509. element.on('change', listener);
  17510. ctrl.$render = function() {
  17511. element.val(ctrl.$isEmpty(ctrl.$modelValue) ? '' : ctrl.$viewValue);
  17512. };
  17513. }
  17514. function weekParser(isoWeek, existingDate) {
  17515. if (isDate(isoWeek)) {
  17516. return isoWeek;
  17517. }
  17518. if (isString(isoWeek)) {
  17519. WEEK_REGEXP.lastIndex = 0;
  17520. var parts = WEEK_REGEXP.exec(isoWeek);
  17521. if (parts) {
  17522. var year = +parts[1],
  17523. week = +parts[2],
  17524. hours = 0,
  17525. minutes = 0,
  17526. seconds = 0,
  17527. milliseconds = 0,
  17528. firstThurs = getFirstThursdayOfYear(year),
  17529. addDays = (week - 1) * 7;
  17530. if (existingDate) {
  17531. hours = existingDate.getHours();
  17532. minutes = existingDate.getMinutes();
  17533. seconds = existingDate.getSeconds();
  17534. milliseconds = existingDate.getMilliseconds();
  17535. }
  17536. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  17537. }
  17538. }
  17539. return NaN;
  17540. }
  17541. function createDateParser(regexp, mapping) {
  17542. return function(iso, date) {
  17543. var parts, map;
  17544. if (isDate(iso)) {
  17545. return iso;
  17546. }
  17547. if (isString(iso)) {
  17548. // When a date is JSON'ified to wraps itself inside of an extra
  17549. // set of double quotes. This makes the date parsing code unable
  17550. // to match the date string and parse it as a date.
  17551. if (iso.charAt(0) == '"' && iso.charAt(iso.length-1) == '"') {
  17552. iso = iso.substring(1, iso.length-1);
  17553. }
  17554. if (ISO_DATE_REGEXP.test(iso)) {
  17555. return new Date(iso);
  17556. }
  17557. regexp.lastIndex = 0;
  17558. parts = regexp.exec(iso);
  17559. if (parts) {
  17560. parts.shift();
  17561. if (date) {
  17562. map = {
  17563. yyyy: date.getFullYear(),
  17564. MM: date.getMonth() + 1,
  17565. dd: date.getDate(),
  17566. HH: date.getHours(),
  17567. mm: date.getMinutes(),
  17568. ss: date.getSeconds(),
  17569. sss: date.getMilliseconds() / 1000
  17570. };
  17571. } else {
  17572. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  17573. }
  17574. forEach(parts, function(part, index) {
  17575. if (index < mapping.length) {
  17576. map[mapping[index]] = +part;
  17577. }
  17578. });
  17579. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  17580. }
  17581. }
  17582. return NaN;
  17583. };
  17584. }
  17585. function createDateInputType(type, regexp, parseDate, format) {
  17586. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  17587. badInputChecker(scope, element, attr, ctrl);
  17588. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17589. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  17590. var previousDate;
  17591. ctrl.$$parserName = type;
  17592. ctrl.$parsers.push(function(value) {
  17593. if (ctrl.$isEmpty(value)) return null;
  17594. if (regexp.test(value)) {
  17595. // Note: We cannot read ctrl.$modelValue, as there might be a different
  17596. // parser/formatter in the processing chain so that the model
  17597. // contains some different data format!
  17598. var parsedDate = parseDate(value, previousDate);
  17599. if (timezone === 'UTC') {
  17600. parsedDate.setMinutes(parsedDate.getMinutes() - parsedDate.getTimezoneOffset());
  17601. }
  17602. return parsedDate;
  17603. }
  17604. return undefined;
  17605. });
  17606. ctrl.$formatters.push(function(value) {
  17607. if (!ctrl.$isEmpty(value)) {
  17608. if (!isDate(value)) {
  17609. throw $ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  17610. }
  17611. previousDate = value;
  17612. if (previousDate && timezone === 'UTC') {
  17613. var timezoneOffset = 60000 * previousDate.getTimezoneOffset();
  17614. previousDate = new Date(previousDate.getTime() + timezoneOffset);
  17615. }
  17616. return $filter('date')(value, format, timezone);
  17617. } else {
  17618. previousDate = null;
  17619. }
  17620. return '';
  17621. });
  17622. if (isDefined(attr.min) || attr.ngMin) {
  17623. var minVal;
  17624. ctrl.$validators.min = function(value) {
  17625. return ctrl.$isEmpty(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  17626. };
  17627. attr.$observe('min', function(val) {
  17628. minVal = parseObservedDateValue(val);
  17629. ctrl.$validate();
  17630. });
  17631. }
  17632. if (isDefined(attr.max) || attr.ngMax) {
  17633. var maxVal;
  17634. ctrl.$validators.max = function(value) {
  17635. return ctrl.$isEmpty(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  17636. };
  17637. attr.$observe('max', function(val) {
  17638. maxVal = parseObservedDateValue(val);
  17639. ctrl.$validate();
  17640. });
  17641. }
  17642. // Override the standard $isEmpty to detect invalid dates as well
  17643. ctrl.$isEmpty = function(value) {
  17644. // Invalid Date: getTime() returns NaN
  17645. return !value || (value.getTime && value.getTime() !== value.getTime());
  17646. };
  17647. function parseObservedDateValue(val) {
  17648. return isDefined(val) ? (isDate(val) ? val : parseDate(val)) : undefined;
  17649. }
  17650. };
  17651. }
  17652. function badInputChecker(scope, element, attr, ctrl) {
  17653. var node = element[0];
  17654. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  17655. if (nativeValidation) {
  17656. ctrl.$parsers.push(function(value) {
  17657. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  17658. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  17659. // - also sets validity.badInput (should only be validity.typeMismatch).
  17660. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  17661. // - can ignore this case as we can still read out the erroneous email...
  17662. return validity.badInput && !validity.typeMismatch ? undefined : value;
  17663. });
  17664. }
  17665. }
  17666. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17667. badInputChecker(scope, element, attr, ctrl);
  17668. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17669. ctrl.$$parserName = 'number';
  17670. ctrl.$parsers.push(function(value) {
  17671. if (ctrl.$isEmpty(value)) return null;
  17672. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  17673. return undefined;
  17674. });
  17675. ctrl.$formatters.push(function(value) {
  17676. if (!ctrl.$isEmpty(value)) {
  17677. if (!isNumber(value)) {
  17678. throw $ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  17679. }
  17680. value = value.toString();
  17681. }
  17682. return value;
  17683. });
  17684. if (attr.min || attr.ngMin) {
  17685. var minVal;
  17686. ctrl.$validators.min = function(value) {
  17687. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  17688. };
  17689. attr.$observe('min', function(val) {
  17690. if (isDefined(val) && !isNumber(val)) {
  17691. val = parseFloat(val, 10);
  17692. }
  17693. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  17694. // TODO(matsko): implement validateLater to reduce number of validations
  17695. ctrl.$validate();
  17696. });
  17697. }
  17698. if (attr.max || attr.ngMax) {
  17699. var maxVal;
  17700. ctrl.$validators.max = function(value) {
  17701. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  17702. };
  17703. attr.$observe('max', function(val) {
  17704. if (isDefined(val) && !isNumber(val)) {
  17705. val = parseFloat(val, 10);
  17706. }
  17707. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  17708. // TODO(matsko): implement validateLater to reduce number of validations
  17709. ctrl.$validate();
  17710. });
  17711. }
  17712. }
  17713. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17714. // Note: no badInputChecker here by purpose as `url` is only a validation
  17715. // in browsers, i.e. we can always read out input.value even if it is not valid!
  17716. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17717. stringBasedInputType(ctrl);
  17718. ctrl.$$parserName = 'url';
  17719. ctrl.$validators.url = function(value) {
  17720. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  17721. };
  17722. }
  17723. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  17724. // Note: no badInputChecker here by purpose as `url` is only a validation
  17725. // in browsers, i.e. we can always read out input.value even if it is not valid!
  17726. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  17727. stringBasedInputType(ctrl);
  17728. ctrl.$$parserName = 'email';
  17729. ctrl.$validators.email = function(value) {
  17730. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  17731. };
  17732. }
  17733. function radioInputType(scope, element, attr, ctrl) {
  17734. // make the name unique, if not defined
  17735. if (isUndefined(attr.name)) {
  17736. element.attr('name', nextUid());
  17737. }
  17738. var listener = function(ev) {
  17739. if (element[0].checked) {
  17740. ctrl.$setViewValue(attr.value, ev && ev.type);
  17741. }
  17742. };
  17743. element.on('click', listener);
  17744. ctrl.$render = function() {
  17745. var value = attr.value;
  17746. element[0].checked = (value == ctrl.$viewValue);
  17747. };
  17748. attr.$observe('value', ctrl.$render);
  17749. }
  17750. function parseConstantExpr($parse, context, name, expression, fallback) {
  17751. var parseFn;
  17752. if (isDefined(expression)) {
  17753. parseFn = $parse(expression);
  17754. if (!parseFn.constant) {
  17755. throw minErr('ngModel')('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  17756. '`{1}`.', name, expression);
  17757. }
  17758. return parseFn(context);
  17759. }
  17760. return fallback;
  17761. }
  17762. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  17763. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  17764. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  17765. var listener = function(ev) {
  17766. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  17767. };
  17768. element.on('click', listener);
  17769. ctrl.$render = function() {
  17770. element[0].checked = ctrl.$viewValue;
  17771. };
  17772. // Override the standard `$isEmpty` because an empty checkbox is never equal to the trueValue
  17773. ctrl.$isEmpty = function(value) {
  17774. return value !== trueValue;
  17775. };
  17776. ctrl.$formatters.push(function(value) {
  17777. return equals(value, trueValue);
  17778. });
  17779. ctrl.$parsers.push(function(value) {
  17780. return value ? trueValue : falseValue;
  17781. });
  17782. }
  17783. /**
  17784. * @ngdoc directive
  17785. * @name textarea
  17786. * @restrict E
  17787. *
  17788. * @description
  17789. * HTML textarea element control with angular data-binding. The data-binding and validation
  17790. * properties of this element are exactly the same as those of the
  17791. * {@link ng.directive:input input element}.
  17792. *
  17793. * @param {string} ngModel Assignable angular expression to data-bind to.
  17794. * @param {string=} name Property name of the form under which the control is published.
  17795. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17796. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  17797. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  17798. * `required` when you want to data-bind to the `required` attribute.
  17799. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17800. * minlength.
  17801. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17802. * maxlength.
  17803. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17804. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17805. * patterns defined as scope expressions.
  17806. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17807. * interaction with the input element.
  17808. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  17809. */
  17810. /**
  17811. * @ngdoc directive
  17812. * @name input
  17813. * @restrict E
  17814. *
  17815. * @description
  17816. * HTML input element control with angular data-binding. Input control follows HTML5 input types
  17817. * and polyfills the HTML5 validation behavior for older browsers.
  17818. *
  17819. * *NOTE* Not every feature offered is available for all input types.
  17820. *
  17821. * @param {string} ngModel Assignable angular expression to data-bind to.
  17822. * @param {string=} name Property name of the form under which the control is published.
  17823. * @param {string=} required Sets `required` validation error key if the value is not entered.
  17824. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  17825. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  17826. * minlength.
  17827. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  17828. * maxlength.
  17829. * @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
  17830. * RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
  17831. * patterns defined as scope expressions.
  17832. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  17833. * interaction with the input element.
  17834. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  17835. * This parameter is ignored for input[type=password] controls, which will never trim the
  17836. * input.
  17837. *
  17838. * @example
  17839. <example name="input-directive" module="inputExample">
  17840. <file name="index.html">
  17841. <script>
  17842. angular.module('inputExample', [])
  17843. .controller('ExampleController', ['$scope', function($scope) {
  17844. $scope.user = {name: 'guest', last: 'visitor'};
  17845. }]);
  17846. </script>
  17847. <div ng-controller="ExampleController">
  17848. <form name="myForm">
  17849. User name: <input type="text" name="userName" ng-model="user.name" required>
  17850. <span class="error" ng-show="myForm.userName.$error.required">
  17851. Required!</span><br>
  17852. Last name: <input type="text" name="lastName" ng-model="user.last"
  17853. ng-minlength="3" ng-maxlength="10">
  17854. <span class="error" ng-show="myForm.lastName.$error.minlength">
  17855. Too short!</span>
  17856. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  17857. Too long!</span><br>
  17858. </form>
  17859. <hr>
  17860. <tt>user = {{user}}</tt><br/>
  17861. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
  17862. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
  17863. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
  17864. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
  17865. <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
  17866. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
  17867. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
  17868. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
  17869. </div>
  17870. </file>
  17871. <file name="protractor.js" type="protractor">
  17872. var user = element(by.exactBinding('user'));
  17873. var userNameValid = element(by.binding('myForm.userName.$valid'));
  17874. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  17875. var lastNameError = element(by.binding('myForm.lastName.$error'));
  17876. var formValid = element(by.binding('myForm.$valid'));
  17877. var userNameInput = element(by.model('user.name'));
  17878. var userLastInput = element(by.model('user.last'));
  17879. it('should initialize to model', function() {
  17880. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  17881. expect(userNameValid.getText()).toContain('true');
  17882. expect(formValid.getText()).toContain('true');
  17883. });
  17884. it('should be invalid if empty when required', function() {
  17885. userNameInput.clear();
  17886. userNameInput.sendKeys('');
  17887. expect(user.getText()).toContain('{"last":"visitor"}');
  17888. expect(userNameValid.getText()).toContain('false');
  17889. expect(formValid.getText()).toContain('false');
  17890. });
  17891. it('should be valid if empty when min length is set', function() {
  17892. userLastInput.clear();
  17893. userLastInput.sendKeys('');
  17894. expect(user.getText()).toContain('{"name":"guest","last":""}');
  17895. expect(lastNameValid.getText()).toContain('true');
  17896. expect(formValid.getText()).toContain('true');
  17897. });
  17898. it('should be invalid if less than required min length', function() {
  17899. userLastInput.clear();
  17900. userLastInput.sendKeys('xx');
  17901. expect(user.getText()).toContain('{"name":"guest"}');
  17902. expect(lastNameValid.getText()).toContain('false');
  17903. expect(lastNameError.getText()).toContain('minlength');
  17904. expect(formValid.getText()).toContain('false');
  17905. });
  17906. it('should be invalid if longer than max length', function() {
  17907. userLastInput.clear();
  17908. userLastInput.sendKeys('some ridiculously long name');
  17909. expect(user.getText()).toContain('{"name":"guest"}');
  17910. expect(lastNameValid.getText()).toContain('false');
  17911. expect(lastNameError.getText()).toContain('maxlength');
  17912. expect(formValid.getText()).toContain('false');
  17913. });
  17914. </file>
  17915. </example>
  17916. */
  17917. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  17918. function($browser, $sniffer, $filter, $parse) {
  17919. return {
  17920. restrict: 'E',
  17921. require: ['?ngModel'],
  17922. link: {
  17923. pre: function(scope, element, attr, ctrls) {
  17924. if (ctrls[0]) {
  17925. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  17926. $browser, $filter, $parse);
  17927. }
  17928. }
  17929. }
  17930. };
  17931. }];
  17932. var VALID_CLASS = 'ng-valid',
  17933. INVALID_CLASS = 'ng-invalid',
  17934. PRISTINE_CLASS = 'ng-pristine',
  17935. DIRTY_CLASS = 'ng-dirty',
  17936. UNTOUCHED_CLASS = 'ng-untouched',
  17937. TOUCHED_CLASS = 'ng-touched',
  17938. PENDING_CLASS = 'ng-pending';
  17939. /**
  17940. * @ngdoc type
  17941. * @name ngModel.NgModelController
  17942. *
  17943. * @property {string} $viewValue Actual string value in the view.
  17944. * @property {*} $modelValue The value in the model, that the control is bound to.
  17945. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  17946. the control reads value from the DOM. Each function is called, in turn, passing the value
  17947. through to the next. The last return value is used to populate the model.
  17948. Used to sanitize / convert the value as well as validation. For validation,
  17949. the parsers should update the validity state using
  17950. {@link ngModel.NgModelController#$setValidity $setValidity()},
  17951. and return `undefined` for invalid values.
  17952. *
  17953. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  17954. the model value changes. Each function is called, in turn, passing the value through to the
  17955. next. Used to format / convert values for display in the control and validation.
  17956. * ```js
  17957. * function formatter(value) {
  17958. * if (value) {
  17959. * return value.toUpperCase();
  17960. * }
  17961. * }
  17962. * ngModel.$formatters.push(formatter);
  17963. * ```
  17964. *
  17965. * @property {Object.<string, function>} $validators A collection of validators that are applied
  17966. * whenever the model value changes. The key value within the object refers to the name of the
  17967. * validator while the function refers to the validation operation. The validation operation is
  17968. * provided with the model value as an argument and must return a true or false value depending
  17969. * on the response of that validation.
  17970. *
  17971. * ```js
  17972. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  17973. * var value = modelValue || viewValue;
  17974. * return /[0-9]+/.test(value) &&
  17975. * /[a-z]+/.test(value) &&
  17976. * /[A-Z]+/.test(value) &&
  17977. * /\W+/.test(value);
  17978. * };
  17979. * ```
  17980. *
  17981. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  17982. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  17983. * is expected to return a promise when it is run during the model validation process. Once the promise
  17984. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  17985. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  17986. * value will only be updated once all validators have been fulfilled. Also, keep in mind that all
  17987. * asynchronous validators will only run once all synchronous validators have passed.
  17988. *
  17989. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  17990. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  17991. *
  17992. * ```js
  17993. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  17994. * var value = modelValue || viewValue;
  17995. *
  17996. * // Lookup user by username
  17997. * return $http.get('/api/users/' + value).
  17998. * then(function resolved() {
  17999. * //username exists, this means validation fails
  18000. * return $q.reject('exists');
  18001. * }, function rejected() {
  18002. * //username does not exist, therefore this validation passes
  18003. * return true;
  18004. * });
  18005. * };
  18006. * ```
  18007. *
  18008. * @param {string} name The name of the validator.
  18009. * @param {Function} validationFn The validation function that will be run.
  18010. *
  18011. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  18012. * view value has changed. It is called with no arguments, and its return value is ignored.
  18013. * This can be used in place of additional $watches against the model value.
  18014. *
  18015. * @property {Object} $error An object hash with all failing validator ids as keys.
  18016. * @property {Object} $pending An object hash with all pending validator ids as keys.
  18017. *
  18018. * @property {boolean} $untouched True if control has not lost focus yet.
  18019. * @property {boolean} $touched True if control has lost focus.
  18020. * @property {boolean} $pristine True if user has not interacted with the control yet.
  18021. * @property {boolean} $dirty True if user has already interacted with the control.
  18022. * @property {boolean} $valid True if there is no error.
  18023. * @property {boolean} $invalid True if at least one error on the control.
  18024. *
  18025. * @description
  18026. *
  18027. * `NgModelController` provides API for the `ng-model` directive. The controller contains
  18028. * services for data-binding, validation, CSS updates, and value formatting and parsing. It
  18029. * purposefully does not contain any logic which deals with DOM rendering or listening to
  18030. * DOM events. Such DOM related logic should be provided by other directives which make use of
  18031. * `NgModelController` for data-binding.
  18032. *
  18033. * ## Custom Control Example
  18034. * This example shows how to use `NgModelController` with a custom control to achieve
  18035. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  18036. * collaborate together to achieve the desired result.
  18037. *
  18038. * Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  18039. * contents be edited in place by the user. This will not work on older browsers.
  18040. *
  18041. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  18042. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  18043. * However, as we are using `$sce` the model can still decide to to provide unsafe content if it marks
  18044. * that content using the `$sce` service.
  18045. *
  18046. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  18047. <file name="style.css">
  18048. [contenteditable] {
  18049. border: 1px solid black;
  18050. background-color: white;
  18051. min-height: 20px;
  18052. }
  18053. .ng-invalid {
  18054. border: 1px solid red;
  18055. }
  18056. </file>
  18057. <file name="script.js">
  18058. angular.module('customControl', ['ngSanitize']).
  18059. directive('contenteditable', ['$sce', function($sce) {
  18060. return {
  18061. restrict: 'A', // only activate on element attribute
  18062. require: '?ngModel', // get a hold of NgModelController
  18063. link: function(scope, element, attrs, ngModel) {
  18064. if (!ngModel) return; // do nothing if no ng-model
  18065. // Specify how UI should be updated
  18066. ngModel.$render = function() {
  18067. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  18068. };
  18069. // Listen for change events to enable binding
  18070. element.on('blur keyup change', function() {
  18071. scope.$apply(read);
  18072. });
  18073. read(); // initialize
  18074. // Write data to the model
  18075. function read() {
  18076. var html = element.html();
  18077. // When we clear the content editable the browser leaves a <br> behind
  18078. // If strip-br attribute is provided then we strip this out
  18079. if ( attrs.stripBr && html == '<br>' ) {
  18080. html = '';
  18081. }
  18082. ngModel.$setViewValue(html);
  18083. }
  18084. }
  18085. };
  18086. }]);
  18087. </file>
  18088. <file name="index.html">
  18089. <form name="myForm">
  18090. <div contenteditable
  18091. name="myWidget" ng-model="userContent"
  18092. strip-br="true"
  18093. required>Change me!</div>
  18094. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  18095. <hr>
  18096. <textarea ng-model="userContent"></textarea>
  18097. </form>
  18098. </file>
  18099. <file name="protractor.js" type="protractor">
  18100. it('should data-bind and become invalid', function() {
  18101. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  18102. // SafariDriver can't handle contenteditable
  18103. // and Firefox driver can't clear contenteditables very well
  18104. return;
  18105. }
  18106. var contentEditable = element(by.css('[contenteditable]'));
  18107. var content = 'Change me!';
  18108. expect(contentEditable.getText()).toEqual(content);
  18109. contentEditable.clear();
  18110. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  18111. expect(contentEditable.getText()).toEqual('');
  18112. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  18113. });
  18114. </file>
  18115. * </example>
  18116. *
  18117. *
  18118. */
  18119. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  18120. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  18121. this.$viewValue = Number.NaN;
  18122. this.$modelValue = Number.NaN;
  18123. this.$validators = {};
  18124. this.$asyncValidators = {};
  18125. this.$parsers = [];
  18126. this.$formatters = [];
  18127. this.$viewChangeListeners = [];
  18128. this.$untouched = true;
  18129. this.$touched = false;
  18130. this.$pristine = true;
  18131. this.$dirty = false;
  18132. this.$valid = true;
  18133. this.$invalid = false;
  18134. this.$error = {}; // keep invalid keys here
  18135. this.$$success = {}; // keep valid keys here
  18136. this.$pending = undefined; // keep pending keys here
  18137. this.$name = $interpolate($attr.name || '', false)($scope);
  18138. var parsedNgModel = $parse($attr.ngModel),
  18139. pendingDebounce = null,
  18140. ctrl = this;
  18141. var ngModelGet = function ngModelGet() {
  18142. var modelValue = parsedNgModel($scope);
  18143. if (ctrl.$options && ctrl.$options.getterSetter && isFunction(modelValue)) {
  18144. modelValue = modelValue();
  18145. }
  18146. return modelValue;
  18147. };
  18148. var ngModelSet = function ngModelSet(newValue) {
  18149. var getterSetter;
  18150. if (ctrl.$options && ctrl.$options.getterSetter &&
  18151. isFunction(getterSetter = parsedNgModel($scope))) {
  18152. getterSetter(ctrl.$modelValue);
  18153. } else {
  18154. parsedNgModel.assign($scope, ctrl.$modelValue);
  18155. }
  18156. };
  18157. this.$$setOptions = function(options) {
  18158. ctrl.$options = options;
  18159. if (!parsedNgModel.assign && (!options || !options.getterSetter)) {
  18160. throw $ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  18161. $attr.ngModel, startingTag($element));
  18162. }
  18163. };
  18164. /**
  18165. * @ngdoc method
  18166. * @name ngModel.NgModelController#$render
  18167. *
  18168. * @description
  18169. * Called when the view needs to be updated. It is expected that the user of the ng-model
  18170. * directive will implement this method.
  18171. *
  18172. * The `$render()` method is invoked in the following situations:
  18173. *
  18174. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  18175. * committed value then `$render()` is called to update the input control.
  18176. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  18177. * the `$viewValue` are different to last time.
  18178. *
  18179. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  18180. * `$modelValue` and `$viewValue` are actually different to their previous value. If `$modelValue`
  18181. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  18182. * invoked if you only change a property on the objects.
  18183. */
  18184. this.$render = noop;
  18185. /**
  18186. * @ngdoc method
  18187. * @name ngModel.NgModelController#$isEmpty
  18188. *
  18189. * @description
  18190. * This is called when we need to determine if the value of the input is empty.
  18191. *
  18192. * For instance, the required directive does this to work out if the input has data or not.
  18193. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  18194. *
  18195. * You can override this for input directives whose concept of being empty is different to the
  18196. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  18197. * implies empty.
  18198. *
  18199. * @param {*} value Model value to check.
  18200. * @returns {boolean} True if `value` is empty.
  18201. */
  18202. this.$isEmpty = function(value) {
  18203. return isUndefined(value) || value === '' || value === null || value !== value;
  18204. };
  18205. var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
  18206. currentValidationRunId = 0;
  18207. /**
  18208. * @ngdoc method
  18209. * @name ngModel.NgModelController#$setValidity
  18210. *
  18211. * @description
  18212. * Change the validity state, and notifies the form.
  18213. *
  18214. * This method can be called within $parsers/$formatters. However, if possible, please use the
  18215. * `ngModel.$validators` pipeline which is designed to call this method automatically.
  18216. *
  18217. * @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
  18218. * to `$error[validationErrorKey]` and `$pending[validationErrorKey]`
  18219. * so that it is available for data-binding.
  18220. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  18221. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  18222. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  18223. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  18224. * or skipped (null).
  18225. */
  18226. addSetValidityMethod({
  18227. ctrl: this,
  18228. $element: $element,
  18229. set: function(object, property) {
  18230. object[property] = true;
  18231. },
  18232. unset: function(object, property) {
  18233. delete object[property];
  18234. },
  18235. parentForm: parentForm,
  18236. $animate: $animate
  18237. });
  18238. /**
  18239. * @ngdoc method
  18240. * @name ngModel.NgModelController#$setPristine
  18241. *
  18242. * @description
  18243. * Sets the control to its pristine state.
  18244. *
  18245. * This method can be called to remove the 'ng-dirty' class and set the control to its pristine
  18246. * state (ng-pristine class). A model is considered to be pristine when the model has not been changed
  18247. * from when first compiled within then form.
  18248. */
  18249. this.$setPristine = function () {
  18250. ctrl.$dirty = false;
  18251. ctrl.$pristine = true;
  18252. $animate.removeClass($element, DIRTY_CLASS);
  18253. $animate.addClass($element, PRISTINE_CLASS);
  18254. };
  18255. /**
  18256. * @ngdoc method
  18257. * @name ngModel.NgModelController#$setUntouched
  18258. *
  18259. * @description
  18260. * Sets the control to its untouched state.
  18261. *
  18262. * This method can be called to remove the 'ng-touched' class and set the control to its
  18263. * untouched state (ng-untouched class). Upon compilation, a model is set as untouched
  18264. * by default, however this function can be used to restore that state if the model has
  18265. * already been touched by the user.
  18266. */
  18267. this.$setUntouched = function() {
  18268. ctrl.$touched = false;
  18269. ctrl.$untouched = true;
  18270. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  18271. };
  18272. /**
  18273. * @ngdoc method
  18274. * @name ngModel.NgModelController#$setTouched
  18275. *
  18276. * @description
  18277. * Sets the control to its touched state.
  18278. *
  18279. * This method can be called to remove the 'ng-untouched' class and set the control to its
  18280. * touched state (ng-touched class). A model is considered to be touched when the user has
  18281. * first interacted (focussed) on the model input element and then shifted focus away (blurred)
  18282. * from the input element.
  18283. */
  18284. this.$setTouched = function() {
  18285. ctrl.$touched = true;
  18286. ctrl.$untouched = false;
  18287. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  18288. };
  18289. /**
  18290. * @ngdoc method
  18291. * @name ngModel.NgModelController#$rollbackViewValue
  18292. *
  18293. * @description
  18294. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  18295. * which may be caused by a pending debounced event or because the input is waiting for a some
  18296. * future event.
  18297. *
  18298. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  18299. * as blur you can have a situation where there is a period when the `$viewValue`
  18300. * is out of synch with the ngModel's `$modelValue`.
  18301. *
  18302. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  18303. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  18304. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  18305. *
  18306. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  18307. * input which may have such events pending. This is important in order to make sure that the
  18308. * input field will be updated with the new model value and any pending operations are cancelled.
  18309. *
  18310. * <example name="ng-model-cancel-update" module="cancel-update-example">
  18311. * <file name="app.js">
  18312. * angular.module('cancel-update-example', [])
  18313. *
  18314. * .controller('CancelUpdateController', ['$scope', function($scope) {
  18315. * $scope.resetWithCancel = function (e) {
  18316. * if (e.keyCode == 27) {
  18317. * $scope.myForm.myInput1.$rollbackViewValue();
  18318. * $scope.myValue = '';
  18319. * }
  18320. * };
  18321. * $scope.resetWithoutCancel = function (e) {
  18322. * if (e.keyCode == 27) {
  18323. * $scope.myValue = '';
  18324. * }
  18325. * };
  18326. * }]);
  18327. * </file>
  18328. * <file name="index.html">
  18329. * <div ng-controller="CancelUpdateController">
  18330. * <p>Try typing something in each input. See that the model only updates when you
  18331. * blur off the input.
  18332. * </p>
  18333. * <p>Now see what happens if you start typing then press the Escape key</p>
  18334. *
  18335. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  18336. * <p>With $rollbackViewValue()</p>
  18337. * <input name="myInput1" ng-model="myValue" ng-keydown="resetWithCancel($event)"><br/>
  18338. * myValue: "{{ myValue }}"
  18339. *
  18340. * <p>Without $rollbackViewValue()</p>
  18341. * <input name="myInput2" ng-model="myValue" ng-keydown="resetWithoutCancel($event)"><br/>
  18342. * myValue: "{{ myValue }}"
  18343. * </form>
  18344. * </div>
  18345. * </file>
  18346. * </example>
  18347. */
  18348. this.$rollbackViewValue = function() {
  18349. $timeout.cancel(pendingDebounce);
  18350. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  18351. ctrl.$render();
  18352. };
  18353. /**
  18354. * @ngdoc method
  18355. * @name ngModel.NgModelController#$validate
  18356. *
  18357. * @description
  18358. * Runs each of the registered validators (first synchronous validators and then asynchronous validators).
  18359. */
  18360. this.$validate = function() {
  18361. // ignore $validate before model is initialized
  18362. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  18363. return;
  18364. }
  18365. this.$$parseAndValidate();
  18366. };
  18367. this.$$runValidators = function(parseValid, modelValue, viewValue, doneCallback) {
  18368. currentValidationRunId++;
  18369. var localValidationRunId = currentValidationRunId;
  18370. // check parser error
  18371. if (!processParseErrors(parseValid)) {
  18372. validationDone(false);
  18373. return;
  18374. }
  18375. if (!processSyncValidators()) {
  18376. validationDone(false);
  18377. return;
  18378. }
  18379. processAsyncValidators();
  18380. function processParseErrors(parseValid) {
  18381. var errorKey = ctrl.$$parserName || 'parse';
  18382. if (parseValid === undefined) {
  18383. setValidity(errorKey, null);
  18384. } else {
  18385. setValidity(errorKey, parseValid);
  18386. if (!parseValid) {
  18387. forEach(ctrl.$validators, function(v, name) {
  18388. setValidity(name, null);
  18389. });
  18390. forEach(ctrl.$asyncValidators, function(v, name) {
  18391. setValidity(name, null);
  18392. });
  18393. return false;
  18394. }
  18395. }
  18396. return true;
  18397. }
  18398. function processSyncValidators() {
  18399. var syncValidatorsValid = true;
  18400. forEach(ctrl.$validators, function(validator, name) {
  18401. var result = validator(modelValue, viewValue);
  18402. syncValidatorsValid = syncValidatorsValid && result;
  18403. setValidity(name, result);
  18404. });
  18405. if (!syncValidatorsValid) {
  18406. forEach(ctrl.$asyncValidators, function(v, name) {
  18407. setValidity(name, null);
  18408. });
  18409. return false;
  18410. }
  18411. return true;
  18412. }
  18413. function processAsyncValidators() {
  18414. var validatorPromises = [];
  18415. var allValid = true;
  18416. forEach(ctrl.$asyncValidators, function(validator, name) {
  18417. var promise = validator(modelValue, viewValue);
  18418. if (!isPromiseLike(promise)) {
  18419. throw $ngModelMinErr("$asyncValidators",
  18420. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  18421. }
  18422. setValidity(name, undefined);
  18423. validatorPromises.push(promise.then(function() {
  18424. setValidity(name, true);
  18425. }, function(error) {
  18426. allValid = false;
  18427. setValidity(name, false);
  18428. }));
  18429. });
  18430. if (!validatorPromises.length) {
  18431. validationDone(true);
  18432. } else {
  18433. $q.all(validatorPromises).then(function() {
  18434. validationDone(allValid);
  18435. }, noop);
  18436. }
  18437. }
  18438. function setValidity(name, isValid) {
  18439. if (localValidationRunId === currentValidationRunId) {
  18440. ctrl.$setValidity(name, isValid);
  18441. }
  18442. }
  18443. function validationDone(allValid) {
  18444. if (localValidationRunId === currentValidationRunId) {
  18445. doneCallback(allValid);
  18446. }
  18447. }
  18448. };
  18449. /**
  18450. * @ngdoc method
  18451. * @name ngModel.NgModelController#$commitViewValue
  18452. *
  18453. * @description
  18454. * Commit a pending update to the `$modelValue`.
  18455. *
  18456. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18457. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  18458. * usually handles calling this in response to input events.
  18459. */
  18460. this.$commitViewValue = function() {
  18461. var viewValue = ctrl.$viewValue;
  18462. $timeout.cancel(pendingDebounce);
  18463. // If the view value has not changed then we should just exit, except in the case where there is
  18464. // a native validator on the element. In this case the validation state may have changed even though
  18465. // the viewValue has stayed empty.
  18466. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  18467. return;
  18468. }
  18469. ctrl.$$lastCommittedViewValue = viewValue;
  18470. // change to dirty
  18471. if (ctrl.$pristine) {
  18472. ctrl.$dirty = true;
  18473. ctrl.$pristine = false;
  18474. $animate.removeClass($element, PRISTINE_CLASS);
  18475. $animate.addClass($element, DIRTY_CLASS);
  18476. parentForm.$setDirty();
  18477. }
  18478. this.$$parseAndValidate();
  18479. };
  18480. this.$$parseAndValidate = function() {
  18481. var viewValue = ctrl.$$lastCommittedViewValue;
  18482. var modelValue = viewValue;
  18483. var parserValid = isUndefined(modelValue) ? undefined : true;
  18484. if (parserValid) {
  18485. for(var i = 0; i < ctrl.$parsers.length; i++) {
  18486. modelValue = ctrl.$parsers[i](modelValue);
  18487. if (isUndefined(modelValue)) {
  18488. parserValid = false;
  18489. break;
  18490. }
  18491. }
  18492. }
  18493. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  18494. // ctrl.$modelValue has not been touched yet...
  18495. ctrl.$modelValue = ngModelGet();
  18496. }
  18497. var prevModelValue = ctrl.$modelValue;
  18498. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  18499. if (allowInvalid) {
  18500. ctrl.$modelValue = modelValue;
  18501. writeToModelIfNeeded();
  18502. }
  18503. ctrl.$$runValidators(parserValid, modelValue, viewValue, function(allValid) {
  18504. if (!allowInvalid) {
  18505. // Note: Don't check ctrl.$valid here, as we could have
  18506. // external validators (e.g. calculated on the server),
  18507. // that just call $setValidity and need the model value
  18508. // to calculate their validity.
  18509. ctrl.$modelValue = allValid ? modelValue : undefined;
  18510. writeToModelIfNeeded();
  18511. }
  18512. });
  18513. function writeToModelIfNeeded() {
  18514. if (ctrl.$modelValue !== prevModelValue) {
  18515. ctrl.$$writeModelToScope();
  18516. }
  18517. }
  18518. };
  18519. this.$$writeModelToScope = function() {
  18520. ngModelSet(ctrl.$modelValue);
  18521. forEach(ctrl.$viewChangeListeners, function(listener) {
  18522. try {
  18523. listener();
  18524. } catch(e) {
  18525. $exceptionHandler(e);
  18526. }
  18527. });
  18528. };
  18529. /**
  18530. * @ngdoc method
  18531. * @name ngModel.NgModelController#$setViewValue
  18532. *
  18533. * @description
  18534. * Update the view value.
  18535. *
  18536. * This method should be called when an input directive want to change the view value; typically,
  18537. * this is done from within a DOM event handler.
  18538. *
  18539. * For example {@link ng.directive:input input} calls it when the value of the input changes and
  18540. * {@link ng.directive:select select} calls it when an option is selected.
  18541. *
  18542. * If the new `value` is an object (rather than a string or a number), we should make a copy of the
  18543. * object before passing it to `$setViewValue`. This is because `ngModel` does not perform a deep
  18544. * watch of objects, it only looks for a change of identity. If you only change the property of
  18545. * the object then ngModel will not realise that the object has changed and will not invoke the
  18546. * `$parsers` and `$validators` pipelines.
  18547. *
  18548. * For this reason, you should not change properties of the copy once it has been passed to
  18549. * `$setViewValue`. Otherwise you may cause the model value on the scope to change incorrectly.
  18550. *
  18551. * When this method is called, the new `value` will be staged for committing through the `$parsers`
  18552. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  18553. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  18554. * **expression** specified in the `ng-model` attribute.
  18555. *
  18556. * Lastly, all the registered change listeners, in the `$viewChangeListeners` list, are called.
  18557. *
  18558. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  18559. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  18560. * `updateOn` events is triggered on the DOM element.
  18561. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  18562. * directive is used with a custom debounce for this particular event.
  18563. *
  18564. * Note that calling this function does not trigger a `$digest`.
  18565. *
  18566. * @param {string} value Value from the view.
  18567. * @param {string} trigger Event that triggered the update.
  18568. */
  18569. this.$setViewValue = function(value, trigger) {
  18570. ctrl.$viewValue = value;
  18571. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  18572. ctrl.$$debounceViewValueCommit(trigger);
  18573. }
  18574. };
  18575. this.$$debounceViewValueCommit = function(trigger) {
  18576. var debounceDelay = 0,
  18577. options = ctrl.$options,
  18578. debounce;
  18579. if (options && isDefined(options.debounce)) {
  18580. debounce = options.debounce;
  18581. if (isNumber(debounce)) {
  18582. debounceDelay = debounce;
  18583. } else if (isNumber(debounce[trigger])) {
  18584. debounceDelay = debounce[trigger];
  18585. } else if (isNumber(debounce['default'])) {
  18586. debounceDelay = debounce['default'];
  18587. }
  18588. }
  18589. $timeout.cancel(pendingDebounce);
  18590. if (debounceDelay) {
  18591. pendingDebounce = $timeout(function() {
  18592. ctrl.$commitViewValue();
  18593. }, debounceDelay);
  18594. } else if ($rootScope.$$phase) {
  18595. ctrl.$commitViewValue();
  18596. } else {
  18597. $scope.$apply(function() {
  18598. ctrl.$commitViewValue();
  18599. });
  18600. }
  18601. };
  18602. // model -> value
  18603. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  18604. // 1. scope value is 'a'
  18605. // 2. user enters 'b'
  18606. // 3. ng-change kicks in and reverts scope value to 'a'
  18607. // -> scope value did not change since the last digest as
  18608. // ng-change executes in apply phase
  18609. // 4. view should be changed back to 'a'
  18610. $scope.$watch(function ngModelWatch() {
  18611. var modelValue = ngModelGet();
  18612. // if scope model value and ngModel value are out of sync
  18613. // TODO(perf): why not move this to the action fn?
  18614. if (modelValue !== ctrl.$modelValue) {
  18615. ctrl.$modelValue = modelValue;
  18616. var formatters = ctrl.$formatters,
  18617. idx = formatters.length;
  18618. var viewValue = modelValue;
  18619. while(idx--) {
  18620. viewValue = formatters[idx](viewValue);
  18621. }
  18622. if (ctrl.$viewValue !== viewValue) {
  18623. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  18624. ctrl.$render();
  18625. ctrl.$$runValidators(undefined, modelValue, viewValue, noop);
  18626. }
  18627. }
  18628. return modelValue;
  18629. });
  18630. }];
  18631. /**
  18632. * @ngdoc directive
  18633. * @name ngModel
  18634. *
  18635. * @element input
  18636. *
  18637. * @description
  18638. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  18639. * property on the scope using {@link ngModel.NgModelController NgModelController},
  18640. * which is created and exposed by this directive.
  18641. *
  18642. * `ngModel` is responsible for:
  18643. *
  18644. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  18645. * require.
  18646. * - Providing validation behavior (i.e. required, number, email, url).
  18647. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  18648. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  18649. * - Registering the control with its parent {@link ng.directive:form form}.
  18650. *
  18651. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  18652. * current scope. If the property doesn't already exist on this scope, it will be created
  18653. * implicitly and added to the scope.
  18654. *
  18655. * For best practices on using `ngModel`, see:
  18656. *
  18657. * - [https://github.com/angular/angular.js/wiki/Understanding-Scopes]
  18658. *
  18659. * For basic examples, how to use `ngModel`, see:
  18660. *
  18661. * - {@link ng.directive:input input}
  18662. * - {@link input[text] text}
  18663. * - {@link input[checkbox] checkbox}
  18664. * - {@link input[radio] radio}
  18665. * - {@link input[number] number}
  18666. * - {@link input[email] email}
  18667. * - {@link input[url] url}
  18668. * - {@link input[date] date}
  18669. * - {@link input[dateTimeLocal] dateTimeLocal}
  18670. * - {@link input[time] time}
  18671. * - {@link input[month] month}
  18672. * - {@link input[week] week}
  18673. * - {@link ng.directive:select select}
  18674. * - {@link ng.directive:textarea textarea}
  18675. *
  18676. * # CSS classes
  18677. * The following CSS classes are added and removed on the associated input/select/textarea element
  18678. * depending on the validity of the model.
  18679. *
  18680. * - `ng-valid` is set if the model is valid.
  18681. * - `ng-invalid` is set if the model is invalid.
  18682. * - `ng-pristine` is set if the model is pristine.
  18683. * - `ng-dirty` is set if the model is dirty.
  18684. *
  18685. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18686. *
  18687. * ## Animation Hooks
  18688. *
  18689. * Animations within models are triggered when any of the associated CSS classes are added and removed
  18690. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  18691. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  18692. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  18693. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  18694. *
  18695. * The following example shows a simple way to utilize CSS transitions to style an input element
  18696. * that has been rendered as invalid after it has been validated:
  18697. *
  18698. * <pre>
  18699. * //be sure to include ngAnimate as a module to hook into more
  18700. * //advanced animations
  18701. * .my-input {
  18702. * transition:0.5s linear all;
  18703. * background: white;
  18704. * }
  18705. * .my-input.ng-invalid {
  18706. * background: red;
  18707. * color:white;
  18708. * }
  18709. * </pre>
  18710. *
  18711. * @example
  18712. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  18713. <file name="index.html">
  18714. <script>
  18715. angular.module('inputExample', [])
  18716. .controller('ExampleController', ['$scope', function($scope) {
  18717. $scope.val = '1';
  18718. }]);
  18719. </script>
  18720. <style>
  18721. .my-input {
  18722. -webkit-transition:all linear 0.5s;
  18723. transition:all linear 0.5s;
  18724. background: transparent;
  18725. }
  18726. .my-input.ng-invalid {
  18727. color:white;
  18728. background: red;
  18729. }
  18730. </style>
  18731. Update input to see transitions when valid/invalid.
  18732. Integer is a valid value.
  18733. <form name="testForm" ng-controller="ExampleController">
  18734. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input" />
  18735. </form>
  18736. </file>
  18737. * </example>
  18738. *
  18739. * ## Binding to a getter/setter
  18740. *
  18741. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  18742. * function that returns a representation of the model when called with zero arguments, and sets
  18743. * the internal state of a model when called with an argument. It's sometimes useful to use this
  18744. * for models that have an internal representation that's different than what the model exposes
  18745. * to the view.
  18746. *
  18747. * <div class="alert alert-success">
  18748. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  18749. * frequently than other parts of your code.
  18750. * </div>
  18751. *
  18752. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  18753. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  18754. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  18755. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  18756. *
  18757. * The following example shows how to use `ngModel` with a getter/setter:
  18758. *
  18759. * @example
  18760. * <example name="ngModel-getter-setter" module="getterSetterExample">
  18761. <file name="index.html">
  18762. <div ng-controller="ExampleController">
  18763. <form name="userForm">
  18764. Name:
  18765. <input type="text" name="userName"
  18766. ng-model="user.name"
  18767. ng-model-options="{ getterSetter: true }" />
  18768. </form>
  18769. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  18770. </div>
  18771. </file>
  18772. <file name="app.js">
  18773. angular.module('getterSetterExample', [])
  18774. .controller('ExampleController', ['$scope', function($scope) {
  18775. var _name = 'Brian';
  18776. $scope.user = {
  18777. name: function (newName) {
  18778. if (angular.isDefined(newName)) {
  18779. _name = newName;
  18780. }
  18781. return _name;
  18782. }
  18783. };
  18784. }]);
  18785. </file>
  18786. * </example>
  18787. */
  18788. var ngModelDirective = function() {
  18789. return {
  18790. restrict: 'A',
  18791. require: ['ngModel', '^?form', '^?ngModelOptions'],
  18792. controller: NgModelController,
  18793. // Prelink needs to run before any input directive
  18794. // so that we can set the NgModelOptions in NgModelController
  18795. // before anyone else uses it.
  18796. priority: 1,
  18797. compile: function ngModelCompile(element) {
  18798. // Setup initial state of the control
  18799. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  18800. return {
  18801. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  18802. var modelCtrl = ctrls[0],
  18803. formCtrl = ctrls[1] || nullFormCtrl;
  18804. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  18805. // notify others, especially parent forms
  18806. formCtrl.$addControl(modelCtrl);
  18807. attr.$observe('name', function(newValue) {
  18808. if (modelCtrl.$name !== newValue) {
  18809. formCtrl.$$renameControl(modelCtrl, newValue);
  18810. }
  18811. });
  18812. scope.$on('$destroy', function() {
  18813. formCtrl.$removeControl(modelCtrl);
  18814. });
  18815. },
  18816. post: function ngModelPostLink(scope, element, attr, ctrls) {
  18817. var modelCtrl = ctrls[0];
  18818. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  18819. element.on(modelCtrl.$options.updateOn, function(ev) {
  18820. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  18821. });
  18822. }
  18823. element.on('blur', function(ev) {
  18824. if (modelCtrl.$touched) return;
  18825. scope.$apply(function() {
  18826. modelCtrl.$setTouched();
  18827. });
  18828. });
  18829. }
  18830. };
  18831. }
  18832. };
  18833. };
  18834. /**
  18835. * @ngdoc directive
  18836. * @name ngChange
  18837. *
  18838. * @description
  18839. * Evaluate the given expression when the user changes the input.
  18840. * The expression is evaluated immediately, unlike the JavaScript onchange event
  18841. * which only triggers at the end of a change (usually, when the user leaves the
  18842. * form element or presses the return key).
  18843. *
  18844. * The `ngChange` expression is only evaluated when a change in the input value causes
  18845. * a new value to be committed to the model.
  18846. *
  18847. * It will not be evaluated:
  18848. * * if the value returned from the `$parsers` transformation pipeline has not changed
  18849. * * if the input has continued to be invalid since the model will stay `null`
  18850. * * if the model is changed programmatically and not by a change to the input value
  18851. *
  18852. *
  18853. * Note, this directive requires `ngModel` to be present.
  18854. *
  18855. * @element input
  18856. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  18857. * in input value.
  18858. *
  18859. * @example
  18860. * <example name="ngChange-directive" module="changeExample">
  18861. * <file name="index.html">
  18862. * <script>
  18863. * angular.module('changeExample', [])
  18864. * .controller('ExampleController', ['$scope', function($scope) {
  18865. * $scope.counter = 0;
  18866. * $scope.change = function() {
  18867. * $scope.counter++;
  18868. * };
  18869. * }]);
  18870. * </script>
  18871. * <div ng-controller="ExampleController">
  18872. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  18873. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  18874. * <label for="ng-change-example2">Confirmed</label><br />
  18875. * <tt>debug = {{confirmed}}</tt><br/>
  18876. * <tt>counter = {{counter}}</tt><br/>
  18877. * </div>
  18878. * </file>
  18879. * <file name="protractor.js" type="protractor">
  18880. * var counter = element(by.binding('counter'));
  18881. * var debug = element(by.binding('confirmed'));
  18882. *
  18883. * it('should evaluate the expression if changing from view', function() {
  18884. * expect(counter.getText()).toContain('0');
  18885. *
  18886. * element(by.id('ng-change-example1')).click();
  18887. *
  18888. * expect(counter.getText()).toContain('1');
  18889. * expect(debug.getText()).toContain('true');
  18890. * });
  18891. *
  18892. * it('should not evaluate the expression if changing from model', function() {
  18893. * element(by.id('ng-change-example2')).click();
  18894. * expect(counter.getText()).toContain('0');
  18895. * expect(debug.getText()).toContain('true');
  18896. * });
  18897. * </file>
  18898. * </example>
  18899. */
  18900. var ngChangeDirective = valueFn({
  18901. restrict: 'A',
  18902. require: 'ngModel',
  18903. link: function(scope, element, attr, ctrl) {
  18904. ctrl.$viewChangeListeners.push(function() {
  18905. scope.$eval(attr.ngChange);
  18906. });
  18907. }
  18908. });
  18909. var requiredDirective = function() {
  18910. return {
  18911. restrict: 'A',
  18912. require: '?ngModel',
  18913. link: function(scope, elm, attr, ctrl) {
  18914. if (!ctrl) return;
  18915. attr.required = true; // force truthy in case we are on non input element
  18916. ctrl.$validators.required = function(value) {
  18917. return !attr.required || !ctrl.$isEmpty(value);
  18918. };
  18919. attr.$observe('required', function() {
  18920. ctrl.$validate();
  18921. });
  18922. }
  18923. };
  18924. };
  18925. var patternDirective = function() {
  18926. return {
  18927. restrict: 'A',
  18928. require: '?ngModel',
  18929. link: function(scope, elm, attr, ctrl) {
  18930. if (!ctrl) return;
  18931. var regexp, patternExp = attr.ngPattern || attr.pattern;
  18932. attr.$observe('pattern', function(regex) {
  18933. if (isString(regex) && regex.length > 0) {
  18934. regex = new RegExp(regex);
  18935. }
  18936. if (regex && !regex.test) {
  18937. throw minErr('ngPattern')('noregexp',
  18938. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  18939. regex, startingTag(elm));
  18940. }
  18941. regexp = regex || undefined;
  18942. ctrl.$validate();
  18943. });
  18944. ctrl.$validators.pattern = function(value) {
  18945. return ctrl.$isEmpty(value) || isUndefined(regexp) || regexp.test(value);
  18946. };
  18947. }
  18948. };
  18949. };
  18950. var maxlengthDirective = function() {
  18951. return {
  18952. restrict: 'A',
  18953. require: '?ngModel',
  18954. link: function(scope, elm, attr, ctrl) {
  18955. if (!ctrl) return;
  18956. var maxlength = 0;
  18957. attr.$observe('maxlength', function(value) {
  18958. maxlength = int(value) || 0;
  18959. ctrl.$validate();
  18960. });
  18961. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  18962. return ctrl.$isEmpty(modelValue) || viewValue.length <= maxlength;
  18963. };
  18964. }
  18965. };
  18966. };
  18967. var minlengthDirective = function() {
  18968. return {
  18969. restrict: 'A',
  18970. require: '?ngModel',
  18971. link: function(scope, elm, attr, ctrl) {
  18972. if (!ctrl) return;
  18973. var minlength = 0;
  18974. attr.$observe('minlength', function(value) {
  18975. minlength = int(value) || 0;
  18976. ctrl.$validate();
  18977. });
  18978. ctrl.$validators.minlength = function(modelValue, viewValue) {
  18979. return ctrl.$isEmpty(modelValue) || viewValue.length >= minlength;
  18980. };
  18981. }
  18982. };
  18983. };
  18984. /**
  18985. * @ngdoc directive
  18986. * @name ngList
  18987. *
  18988. * @description
  18989. * Text input that converts between a delimited string and an array of strings. The default
  18990. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  18991. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  18992. *
  18993. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  18994. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  18995. * list item is respected. This implies that the user of the directive is responsible for
  18996. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  18997. * tab or newline character.
  18998. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  18999. * when joining the list items back together) and whitespace around each list item is stripped
  19000. * before it is added to the model.
  19001. *
  19002. * ### Example with Validation
  19003. *
  19004. * <example name="ngList-directive" module="listExample">
  19005. * <file name="app.js">
  19006. * angular.module('listExample', [])
  19007. * .controller('ExampleController', ['$scope', function($scope) {
  19008. * $scope.names = ['morpheus', 'neo', 'trinity'];
  19009. * }]);
  19010. * </file>
  19011. * <file name="index.html">
  19012. * <form name="myForm" ng-controller="ExampleController">
  19013. * List: <input name="namesInput" ng-model="names" ng-list required>
  19014. * <span class="error" ng-show="myForm.namesInput.$error.required">
  19015. * Required!</span>
  19016. * <br>
  19017. * <tt>names = {{names}}</tt><br/>
  19018. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  19019. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  19020. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19021. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19022. * </form>
  19023. * </file>
  19024. * <file name="protractor.js" type="protractor">
  19025. * var listInput = element(by.model('names'));
  19026. * var names = element(by.exactBinding('names'));
  19027. * var valid = element(by.binding('myForm.namesInput.$valid'));
  19028. * var error = element(by.css('span.error'));
  19029. *
  19030. * it('should initialize to model', function() {
  19031. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  19032. * expect(valid.getText()).toContain('true');
  19033. * expect(error.getCssValue('display')).toBe('none');
  19034. * });
  19035. *
  19036. * it('should be invalid if empty', function() {
  19037. * listInput.clear();
  19038. * listInput.sendKeys('');
  19039. *
  19040. * expect(names.getText()).toContain('');
  19041. * expect(valid.getText()).toContain('false');
  19042. * expect(error.getCssValue('display')).not.toBe('none');
  19043. * });
  19044. * </file>
  19045. * </example>
  19046. *
  19047. * ### Example - splitting on whitespace
  19048. * <example name="ngList-directive-newlines">
  19049. * <file name="index.html">
  19050. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  19051. * <pre>{{ list | json }}</pre>
  19052. * </file>
  19053. * <file name="protractor.js" type="protractor">
  19054. * it("should split the text by newlines", function() {
  19055. * var listInput = element(by.model('list'));
  19056. * var output = element(by.binding('list | json'));
  19057. * listInput.sendKeys('abc\ndef\nghi');
  19058. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  19059. * });
  19060. * </file>
  19061. * </example>
  19062. *
  19063. * @element input
  19064. * @param {string=} ngList optional delimiter that should be used to split the value.
  19065. */
  19066. var ngListDirective = function() {
  19067. return {
  19068. restrict: 'A',
  19069. priority: 100,
  19070. require: 'ngModel',
  19071. link: function(scope, element, attr, ctrl) {
  19072. // We want to control whitespace trimming so we use this convoluted approach
  19073. // to access the ngList attribute, which doesn't pre-trim the attribute
  19074. var ngList = element.attr(attr.$attr.ngList) || ', ';
  19075. var trimValues = attr.ngTrim !== 'false';
  19076. var separator = trimValues ? trim(ngList) : ngList;
  19077. var parse = function(viewValue) {
  19078. // If the viewValue is invalid (say required but empty) it will be `undefined`
  19079. if (isUndefined(viewValue)) return;
  19080. var list = [];
  19081. if (viewValue) {
  19082. forEach(viewValue.split(separator), function(value) {
  19083. if (value) list.push(trimValues ? trim(value) : value);
  19084. });
  19085. }
  19086. return list;
  19087. };
  19088. ctrl.$parsers.push(parse);
  19089. ctrl.$formatters.push(function(value) {
  19090. if (isArray(value)) {
  19091. return value.join(ngList);
  19092. }
  19093. return undefined;
  19094. });
  19095. // Override the standard $isEmpty because an empty array means the input is empty.
  19096. ctrl.$isEmpty = function(value) {
  19097. return !value || !value.length;
  19098. };
  19099. }
  19100. };
  19101. };
  19102. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  19103. /**
  19104. * @ngdoc directive
  19105. * @name ngValue
  19106. *
  19107. * @description
  19108. * Binds the given expression to the value of `input[select]` or `input[radio]`, so
  19109. * that when the element is selected, the `ngModel` of that element is set to the
  19110. * bound value.
  19111. *
  19112. * `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
  19113. * shown below.
  19114. *
  19115. * @element input
  19116. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  19117. * of the `input` element
  19118. *
  19119. * @example
  19120. <example name="ngValue-directive" module="valueExample">
  19121. <file name="index.html">
  19122. <script>
  19123. angular.module('valueExample', [])
  19124. .controller('ExampleController', ['$scope', function($scope) {
  19125. $scope.names = ['pizza', 'unicorns', 'robots'];
  19126. $scope.my = { favorite: 'unicorns' };
  19127. }]);
  19128. </script>
  19129. <form ng-controller="ExampleController">
  19130. <h2>Which is your favorite?</h2>
  19131. <label ng-repeat="name in names" for="{{name}}">
  19132. {{name}}
  19133. <input type="radio"
  19134. ng-model="my.favorite"
  19135. ng-value="name"
  19136. id="{{name}}"
  19137. name="favorite">
  19138. </label>
  19139. <div>You chose {{my.favorite}}</div>
  19140. </form>
  19141. </file>
  19142. <file name="protractor.js" type="protractor">
  19143. var favorite = element(by.binding('my.favorite'));
  19144. it('should initialize to model', function() {
  19145. expect(favorite.getText()).toContain('unicorns');
  19146. });
  19147. it('should bind the values to the inputs', function() {
  19148. element.all(by.model('my.favorite')).get(0).click();
  19149. expect(favorite.getText()).toContain('pizza');
  19150. });
  19151. </file>
  19152. </example>
  19153. */
  19154. var ngValueDirective = function() {
  19155. return {
  19156. restrict: 'A',
  19157. priority: 100,
  19158. compile: function(tpl, tplAttr) {
  19159. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  19160. return function ngValueConstantLink(scope, elm, attr) {
  19161. attr.$set('value', scope.$eval(attr.ngValue));
  19162. };
  19163. } else {
  19164. return function ngValueLink(scope, elm, attr) {
  19165. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  19166. attr.$set('value', value);
  19167. });
  19168. };
  19169. }
  19170. }
  19171. };
  19172. };
  19173. /**
  19174. * @ngdoc directive
  19175. * @name ngModelOptions
  19176. *
  19177. * @description
  19178. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  19179. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  19180. * takes place when a timer expires; this timer will be reset after another change takes place.
  19181. *
  19182. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  19183. * be different than the value in the actual model. This means that if you update the model you
  19184. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  19185. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  19186. *
  19187. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  19188. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  19189. * important because `form` controllers are published to the related scope under the name in their
  19190. * `name` attribute.
  19191. *
  19192. * Any pending changes will take place immediately when an enclosing form is submitted via the
  19193. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  19194. * to have access to the updated model.
  19195. *
  19196. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  19197. *
  19198. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  19199. * - `updateOn`: string specifying which event should be the input bound to. You can set several
  19200. * events using an space delimited list. There is a special event called `default` that
  19201. * matches the default events belonging of the control.
  19202. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  19203. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  19204. * custom value for each event. For example:
  19205. * `ng-model-options="{ updateOn: 'default blur', debounce: {'default': 500, 'blur': 0} }"`
  19206. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  19207. * not validate correctly instead of the default behavior of setting the model to undefined.
  19208. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  19209. `ngModel` as getters/setters.
  19210. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  19211. * `<input type="date">`, `<input type="time">`, ... . Right now, the only supported value is `'UTC'`,
  19212. * otherwise the default timezone of the browser will be used.
  19213. *
  19214. * @example
  19215. The following example shows how to override immediate updates. Changes on the inputs within the
  19216. form will update the model only when the control loses focus (blur event). If `escape` key is
  19217. pressed while the input field is focused, the value is reset to the value in the current model.
  19218. <example name="ngModelOptions-directive-blur" module="optionsExample">
  19219. <file name="index.html">
  19220. <div ng-controller="ExampleController">
  19221. <form name="userForm">
  19222. Name:
  19223. <input type="text" name="userName"
  19224. ng-model="user.name"
  19225. ng-model-options="{ updateOn: 'blur' }"
  19226. ng-keyup="cancel($event)" /><br />
  19227. Other data:
  19228. <input type="text" ng-model="user.data" /><br />
  19229. </form>
  19230. <pre>user.name = <span ng-bind="user.name"></span></pre>
  19231. </div>
  19232. </file>
  19233. <file name="app.js">
  19234. angular.module('optionsExample', [])
  19235. .controller('ExampleController', ['$scope', function($scope) {
  19236. $scope.user = { name: 'say', data: '' };
  19237. $scope.cancel = function (e) {
  19238. if (e.keyCode == 27) {
  19239. $scope.userForm.userName.$rollbackViewValue();
  19240. }
  19241. };
  19242. }]);
  19243. </file>
  19244. <file name="protractor.js" type="protractor">
  19245. var model = element(by.binding('user.name'));
  19246. var input = element(by.model('user.name'));
  19247. var other = element(by.model('user.data'));
  19248. it('should allow custom events', function() {
  19249. input.sendKeys(' hello');
  19250. input.click();
  19251. expect(model.getText()).toEqual('say');
  19252. other.click();
  19253. expect(model.getText()).toEqual('say hello');
  19254. });
  19255. it('should $rollbackViewValue when model changes', function() {
  19256. input.sendKeys(' hello');
  19257. expect(input.getAttribute('value')).toEqual('say hello');
  19258. input.sendKeys(protractor.Key.ESCAPE);
  19259. expect(input.getAttribute('value')).toEqual('say');
  19260. other.click();
  19261. expect(model.getText()).toEqual('say');
  19262. });
  19263. </file>
  19264. </example>
  19265. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  19266. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  19267. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  19268. <file name="index.html">
  19269. <div ng-controller="ExampleController">
  19270. <form name="userForm">
  19271. Name:
  19272. <input type="text" name="userName"
  19273. ng-model="user.name"
  19274. ng-model-options="{ debounce: 1000 }" />
  19275. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button><br />
  19276. </form>
  19277. <pre>user.name = <span ng-bind="user.name"></span></pre>
  19278. </div>
  19279. </file>
  19280. <file name="app.js">
  19281. angular.module('optionsExample', [])
  19282. .controller('ExampleController', ['$scope', function($scope) {
  19283. $scope.user = { name: 'say' };
  19284. }]);
  19285. </file>
  19286. </example>
  19287. This one shows how to bind to getter/setters:
  19288. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  19289. <file name="index.html">
  19290. <div ng-controller="ExampleController">
  19291. <form name="userForm">
  19292. Name:
  19293. <input type="text" name="userName"
  19294. ng-model="user.name"
  19295. ng-model-options="{ getterSetter: true }" />
  19296. </form>
  19297. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  19298. </div>
  19299. </file>
  19300. <file name="app.js">
  19301. angular.module('getterSetterExample', [])
  19302. .controller('ExampleController', ['$scope', function($scope) {
  19303. var _name = 'Brian';
  19304. $scope.user = {
  19305. name: function (newName) {
  19306. return angular.isDefined(newName) ? (_name = newName) : _name;
  19307. }
  19308. };
  19309. }]);
  19310. </file>
  19311. </example>
  19312. */
  19313. var ngModelOptionsDirective = function() {
  19314. return {
  19315. restrict: 'A',
  19316. controller: ['$scope', '$attrs', function($scope, $attrs) {
  19317. var that = this;
  19318. this.$options = $scope.$eval($attrs.ngModelOptions);
  19319. // Allow adding/overriding bound events
  19320. if (this.$options.updateOn !== undefined) {
  19321. this.$options.updateOnDefault = false;
  19322. // extract "default" pseudo-event from list of events that can trigger a model update
  19323. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  19324. that.$options.updateOnDefault = true;
  19325. return ' ';
  19326. }));
  19327. } else {
  19328. this.$options.updateOnDefault = true;
  19329. }
  19330. }]
  19331. };
  19332. };
  19333. // helper methods
  19334. function addSetValidityMethod(context) {
  19335. var ctrl = context.ctrl,
  19336. $element = context.$element,
  19337. classCache = {},
  19338. set = context.set,
  19339. unset = context.unset,
  19340. parentForm = context.parentForm,
  19341. $animate = context.$animate;
  19342. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  19343. ctrl.$setValidity = setValidity;
  19344. function setValidity(validationErrorKey, state, options) {
  19345. if (state === undefined) {
  19346. createAndSet('$pending', validationErrorKey, options);
  19347. } else {
  19348. unsetAndCleanup('$pending', validationErrorKey, options);
  19349. }
  19350. if (!isBoolean(state)) {
  19351. unset(ctrl.$error, validationErrorKey, options);
  19352. unset(ctrl.$$success, validationErrorKey, options);
  19353. } else {
  19354. if (state) {
  19355. unset(ctrl.$error, validationErrorKey, options);
  19356. set(ctrl.$$success, validationErrorKey, options);
  19357. } else {
  19358. set(ctrl.$error, validationErrorKey, options);
  19359. unset(ctrl.$$success, validationErrorKey, options);
  19360. }
  19361. }
  19362. if (ctrl.$pending) {
  19363. cachedToggleClass(PENDING_CLASS, true);
  19364. ctrl.$valid = ctrl.$invalid = undefined;
  19365. toggleValidationCss('', null);
  19366. } else {
  19367. cachedToggleClass(PENDING_CLASS, false);
  19368. ctrl.$valid = isObjectEmpty(ctrl.$error);
  19369. ctrl.$invalid = !ctrl.$valid;
  19370. toggleValidationCss('', ctrl.$valid);
  19371. }
  19372. // re-read the state as the set/unset methods could have
  19373. // combined state in ctrl.$error[validationError] (used for forms),
  19374. // where setting/unsetting only increments/decrements the value,
  19375. // and does not replace it.
  19376. var combinedState;
  19377. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  19378. combinedState = undefined;
  19379. } else if (ctrl.$error[validationErrorKey]) {
  19380. combinedState = false;
  19381. } else if (ctrl.$$success[validationErrorKey]) {
  19382. combinedState = true;
  19383. } else {
  19384. combinedState = null;
  19385. }
  19386. toggleValidationCss(validationErrorKey, combinedState);
  19387. parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  19388. }
  19389. function createAndSet(name, value, options) {
  19390. if (!ctrl[name]) {
  19391. ctrl[name] = {};
  19392. }
  19393. set(ctrl[name], value, options);
  19394. }
  19395. function unsetAndCleanup(name, value, options) {
  19396. if (ctrl[name]) {
  19397. unset(ctrl[name], value, options);
  19398. }
  19399. if (isObjectEmpty(ctrl[name])) {
  19400. ctrl[name] = undefined;
  19401. }
  19402. }
  19403. function cachedToggleClass(className, switchValue) {
  19404. if (switchValue && !classCache[className]) {
  19405. $animate.addClass($element, className);
  19406. classCache[className] = true;
  19407. } else if (!switchValue && classCache[className]) {
  19408. $animate.removeClass($element, className);
  19409. classCache[className] = false;
  19410. }
  19411. }
  19412. function toggleValidationCss(validationErrorKey, isValid) {
  19413. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  19414. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  19415. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  19416. }
  19417. }
  19418. function isObjectEmpty(obj) {
  19419. if (obj) {
  19420. for (var prop in obj) {
  19421. return false;
  19422. }
  19423. }
  19424. return true;
  19425. }
  19426. /**
  19427. * @ngdoc directive
  19428. * @name ngBind
  19429. * @restrict AC
  19430. *
  19431. * @description
  19432. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  19433. * with the value of a given expression, and to update the text content when the value of that
  19434. * expression changes.
  19435. *
  19436. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  19437. * `{{ expression }}` which is similar but less verbose.
  19438. *
  19439. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  19440. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  19441. * element attribute, it makes the bindings invisible to the user while the page is loading.
  19442. *
  19443. * An alternative solution to this problem would be using the
  19444. * {@link ng.directive:ngCloak ngCloak} directive.
  19445. *
  19446. *
  19447. * @element ANY
  19448. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  19449. *
  19450. * @example
  19451. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  19452. <example module="bindExample">
  19453. <file name="index.html">
  19454. <script>
  19455. angular.module('bindExample', [])
  19456. .controller('ExampleController', ['$scope', function($scope) {
  19457. $scope.name = 'Whirled';
  19458. }]);
  19459. </script>
  19460. <div ng-controller="ExampleController">
  19461. Enter name: <input type="text" ng-model="name"><br>
  19462. Hello <span ng-bind="name"></span>!
  19463. </div>
  19464. </file>
  19465. <file name="protractor.js" type="protractor">
  19466. it('should check ng-bind', function() {
  19467. var nameInput = element(by.model('name'));
  19468. expect(element(by.binding('name')).getText()).toBe('Whirled');
  19469. nameInput.clear();
  19470. nameInput.sendKeys('world');
  19471. expect(element(by.binding('name')).getText()).toBe('world');
  19472. });
  19473. </file>
  19474. </example>
  19475. */
  19476. var ngBindDirective = ['$compile', function($compile) {
  19477. return {
  19478. restrict: 'AC',
  19479. compile: function ngBindCompile(templateElement) {
  19480. $compile.$$addBindingClass(templateElement);
  19481. return function ngBindLink(scope, element, attr) {
  19482. $compile.$$addBindingInfo(element, attr.ngBind);
  19483. element = element[0];
  19484. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  19485. element.textContent = value === undefined ? '' : value;
  19486. });
  19487. };
  19488. }
  19489. };
  19490. }];
  19491. /**
  19492. * @ngdoc directive
  19493. * @name ngBindTemplate
  19494. *
  19495. * @description
  19496. * The `ngBindTemplate` directive specifies that the element
  19497. * text content should be replaced with the interpolation of the template
  19498. * in the `ngBindTemplate` attribute.
  19499. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  19500. * expressions. This directive is needed since some HTML elements
  19501. * (such as TITLE and OPTION) cannot contain SPAN elements.
  19502. *
  19503. * @element ANY
  19504. * @param {string} ngBindTemplate template of form
  19505. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  19506. *
  19507. * @example
  19508. * Try it here: enter text in text box and watch the greeting change.
  19509. <example module="bindExample">
  19510. <file name="index.html">
  19511. <script>
  19512. angular.module('bindExample', [])
  19513. .controller('ExampleController', ['$scope', function ($scope) {
  19514. $scope.salutation = 'Hello';
  19515. $scope.name = 'World';
  19516. }]);
  19517. </script>
  19518. <div ng-controller="ExampleController">
  19519. Salutation: <input type="text" ng-model="salutation"><br>
  19520. Name: <input type="text" ng-model="name"><br>
  19521. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  19522. </div>
  19523. </file>
  19524. <file name="protractor.js" type="protractor">
  19525. it('should check ng-bind', function() {
  19526. var salutationElem = element(by.binding('salutation'));
  19527. var salutationInput = element(by.model('salutation'));
  19528. var nameInput = element(by.model('name'));
  19529. expect(salutationElem.getText()).toBe('Hello World!');
  19530. salutationInput.clear();
  19531. salutationInput.sendKeys('Greetings');
  19532. nameInput.clear();
  19533. nameInput.sendKeys('user');
  19534. expect(salutationElem.getText()).toBe('Greetings user!');
  19535. });
  19536. </file>
  19537. </example>
  19538. */
  19539. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  19540. return {
  19541. compile: function ngBindTemplateCompile(templateElement) {
  19542. $compile.$$addBindingClass(templateElement);
  19543. return function ngBindTemplateLink(scope, element, attr) {
  19544. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  19545. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  19546. element = element[0];
  19547. attr.$observe('ngBindTemplate', function(value) {
  19548. element.textContent = value === undefined ? '' : value;
  19549. });
  19550. };
  19551. }
  19552. };
  19553. }];
  19554. /**
  19555. * @ngdoc directive
  19556. * @name ngBindHtml
  19557. *
  19558. * @description
  19559. * Creates a binding that will innerHTML the result of evaluating the `expression` into the current
  19560. * element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
  19561. * ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
  19562. * is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
  19563. * core Angular). In order to use {@link ngSanitize} in your module's dependencies, you need to
  19564. * include "angular-sanitize.js" in your application.
  19565. *
  19566. * You may also bypass sanitization for values you know are safe. To do so, bind to
  19567. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  19568. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  19569. *
  19570. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  19571. * will have an exception (instead of an exploit.)
  19572. *
  19573. * @element ANY
  19574. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  19575. *
  19576. * @example
  19577. <example module="bindHtmlExample" deps="angular-sanitize.js">
  19578. <file name="index.html">
  19579. <div ng-controller="ExampleController">
  19580. <p ng-bind-html="myHTML"></p>
  19581. </div>
  19582. </file>
  19583. <file name="script.js">
  19584. angular.module('bindHtmlExample', ['ngSanitize'])
  19585. .controller('ExampleController', ['$scope', function($scope) {
  19586. $scope.myHTML =
  19587. 'I am an <code>HTML</code>string with ' +
  19588. '<a href="#">links!</a> and other <em>stuff</em>';
  19589. }]);
  19590. </file>
  19591. <file name="protractor.js" type="protractor">
  19592. it('should check ng-bind-html', function() {
  19593. expect(element(by.binding('myHTML')).getText()).toBe(
  19594. 'I am an HTMLstring with links! and other stuff');
  19595. });
  19596. </file>
  19597. </example>
  19598. */
  19599. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  19600. return {
  19601. restrict: 'A',
  19602. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  19603. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  19604. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  19605. return (value || '').toString();
  19606. });
  19607. $compile.$$addBindingClass(tElement);
  19608. return function ngBindHtmlLink(scope, element, attr) {
  19609. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  19610. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  19611. // we re-evaluate the expr because we want a TrustedValueHolderType
  19612. // for $sce, not a string
  19613. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  19614. });
  19615. };
  19616. }
  19617. };
  19618. }];
  19619. function classDirective(name, selector) {
  19620. name = 'ngClass' + name;
  19621. return ['$animate', function($animate) {
  19622. return {
  19623. restrict: 'AC',
  19624. link: function(scope, element, attr) {
  19625. var oldVal;
  19626. scope.$watch(attr[name], ngClassWatchAction, true);
  19627. attr.$observe('class', function(value) {
  19628. ngClassWatchAction(scope.$eval(attr[name]));
  19629. });
  19630. if (name !== 'ngClass') {
  19631. scope.$watch('$index', function($index, old$index) {
  19632. // jshint bitwise: false
  19633. var mod = $index & 1;
  19634. if (mod !== (old$index & 1)) {
  19635. var classes = arrayClasses(scope.$eval(attr[name]));
  19636. mod === selector ?
  19637. addClasses(classes) :
  19638. removeClasses(classes);
  19639. }
  19640. });
  19641. }
  19642. function addClasses(classes) {
  19643. var newClasses = digestClassCounts(classes, 1);
  19644. attr.$addClass(newClasses);
  19645. }
  19646. function removeClasses(classes) {
  19647. var newClasses = digestClassCounts(classes, -1);
  19648. attr.$removeClass(newClasses);
  19649. }
  19650. function digestClassCounts (classes, count) {
  19651. var classCounts = element.data('$classCounts') || {};
  19652. var classesToUpdate = [];
  19653. forEach(classes, function (className) {
  19654. if (count > 0 || classCounts[className]) {
  19655. classCounts[className] = (classCounts[className] || 0) + count;
  19656. if (classCounts[className] === +(count > 0)) {
  19657. classesToUpdate.push(className);
  19658. }
  19659. }
  19660. });
  19661. element.data('$classCounts', classCounts);
  19662. return classesToUpdate.join(' ');
  19663. }
  19664. function updateClasses (oldClasses, newClasses) {
  19665. var toAdd = arrayDifference(newClasses, oldClasses);
  19666. var toRemove = arrayDifference(oldClasses, newClasses);
  19667. toAdd = digestClassCounts(toAdd, 1);
  19668. toRemove = digestClassCounts(toRemove, -1);
  19669. if (toAdd && toAdd.length) {
  19670. $animate.addClass(element, toAdd);
  19671. }
  19672. if (toRemove && toRemove.length) {
  19673. $animate.removeClass(element, toRemove);
  19674. }
  19675. }
  19676. function ngClassWatchAction(newVal) {
  19677. if (selector === true || scope.$index % 2 === selector) {
  19678. var newClasses = arrayClasses(newVal || []);
  19679. if (!oldVal) {
  19680. addClasses(newClasses);
  19681. } else if (!equals(newVal,oldVal)) {
  19682. var oldClasses = arrayClasses(oldVal);
  19683. updateClasses(oldClasses, newClasses);
  19684. }
  19685. }
  19686. oldVal = shallowCopy(newVal);
  19687. }
  19688. }
  19689. };
  19690. function arrayDifference(tokens1, tokens2) {
  19691. var values = [];
  19692. outer:
  19693. for(var i = 0; i < tokens1.length; i++) {
  19694. var token = tokens1[i];
  19695. for(var j = 0; j < tokens2.length; j++) {
  19696. if(token == tokens2[j]) continue outer;
  19697. }
  19698. values.push(token);
  19699. }
  19700. return values;
  19701. }
  19702. function arrayClasses (classVal) {
  19703. if (isArray(classVal)) {
  19704. return classVal;
  19705. } else if (isString(classVal)) {
  19706. return classVal.split(' ');
  19707. } else if (isObject(classVal)) {
  19708. var classes = [], i = 0;
  19709. forEach(classVal, function(v, k) {
  19710. if (v) {
  19711. classes = classes.concat(k.split(' '));
  19712. }
  19713. });
  19714. return classes;
  19715. }
  19716. return classVal;
  19717. }
  19718. }];
  19719. }
  19720. /**
  19721. * @ngdoc directive
  19722. * @name ngClass
  19723. * @restrict AC
  19724. *
  19725. * @description
  19726. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  19727. * an expression that represents all classes to be added.
  19728. *
  19729. * The directive operates in three different ways, depending on which of three types the expression
  19730. * evaluates to:
  19731. *
  19732. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  19733. * names.
  19734. *
  19735. * 2. If the expression evaluates to an array, each element of the array should be a string that is
  19736. * one or more space-delimited class names.
  19737. *
  19738. * 3. If the expression evaluates to an object, then for each key-value pair of the
  19739. * object with a truthy value the corresponding key is used as a class name.
  19740. *
  19741. * The directive won't add duplicate classes if a particular class was already set.
  19742. *
  19743. * When the expression changes, the previously added classes are removed and only then the
  19744. * new classes are added.
  19745. *
  19746. * @animations
  19747. * add - happens just before the class is applied to the element
  19748. * remove - happens just before the class is removed from the element
  19749. *
  19750. * @element ANY
  19751. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  19752. * of the evaluation can be a string representing space delimited class
  19753. * names, an array, or a map of class names to boolean values. In the case of a map, the
  19754. * names of the properties whose values are truthy will be added as css classes to the
  19755. * element.
  19756. *
  19757. * @example Example that demonstrates basic bindings via ngClass directive.
  19758. <example>
  19759. <file name="index.html">
  19760. <p ng-class="{strike: deleted, bold: important, red: error}">Map Syntax Example</p>
  19761. <input type="checkbox" ng-model="deleted"> deleted (apply "strike" class)<br>
  19762. <input type="checkbox" ng-model="important"> important (apply "bold" class)<br>
  19763. <input type="checkbox" ng-model="error"> error (apply "red" class)
  19764. <hr>
  19765. <p ng-class="style">Using String Syntax</p>
  19766. <input type="text" ng-model="style" placeholder="Type: bold strike red">
  19767. <hr>
  19768. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  19769. <input ng-model="style1" placeholder="Type: bold, strike or red"><br>
  19770. <input ng-model="style2" placeholder="Type: bold, strike or red"><br>
  19771. <input ng-model="style3" placeholder="Type: bold, strike or red"><br>
  19772. </file>
  19773. <file name="style.css">
  19774. .strike {
  19775. text-decoration: line-through;
  19776. }
  19777. .bold {
  19778. font-weight: bold;
  19779. }
  19780. .red {
  19781. color: red;
  19782. }
  19783. </file>
  19784. <file name="protractor.js" type="protractor">
  19785. var ps = element.all(by.css('p'));
  19786. it('should let you toggle the class', function() {
  19787. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  19788. expect(ps.first().getAttribute('class')).not.toMatch(/red/);
  19789. element(by.model('important')).click();
  19790. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  19791. element(by.model('error')).click();
  19792. expect(ps.first().getAttribute('class')).toMatch(/red/);
  19793. });
  19794. it('should let you toggle string example', function() {
  19795. expect(ps.get(1).getAttribute('class')).toBe('');
  19796. element(by.model('style')).clear();
  19797. element(by.model('style')).sendKeys('red');
  19798. expect(ps.get(1).getAttribute('class')).toBe('red');
  19799. });
  19800. it('array example should have 3 classes', function() {
  19801. expect(ps.last().getAttribute('class')).toBe('');
  19802. element(by.model('style1')).sendKeys('bold');
  19803. element(by.model('style2')).sendKeys('strike');
  19804. element(by.model('style3')).sendKeys('red');
  19805. expect(ps.last().getAttribute('class')).toBe('bold strike red');
  19806. });
  19807. </file>
  19808. </example>
  19809. ## Animations
  19810. The example below demonstrates how to perform animations using ngClass.
  19811. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  19812. <file name="index.html">
  19813. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  19814. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  19815. <br>
  19816. <span class="base-class" ng-class="myVar">Sample Text</span>
  19817. </file>
  19818. <file name="style.css">
  19819. .base-class {
  19820. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19821. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  19822. }
  19823. .base-class.my-class {
  19824. color: red;
  19825. font-size:3em;
  19826. }
  19827. </file>
  19828. <file name="protractor.js" type="protractor">
  19829. it('should check ng-class', function() {
  19830. expect(element(by.css('.base-class')).getAttribute('class')).not.
  19831. toMatch(/my-class/);
  19832. element(by.id('setbtn')).click();
  19833. expect(element(by.css('.base-class')).getAttribute('class')).
  19834. toMatch(/my-class/);
  19835. element(by.id('clearbtn')).click();
  19836. expect(element(by.css('.base-class')).getAttribute('class')).not.
  19837. toMatch(/my-class/);
  19838. });
  19839. </file>
  19840. </example>
  19841. ## ngClass and pre-existing CSS3 Transitions/Animations
  19842. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  19843. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  19844. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  19845. to view the step by step details of {@link ng.$animate#addClass $animate.addClass} and
  19846. {@link ng.$animate#removeClass $animate.removeClass}.
  19847. */
  19848. var ngClassDirective = classDirective('', true);
  19849. /**
  19850. * @ngdoc directive
  19851. * @name ngClassOdd
  19852. * @restrict AC
  19853. *
  19854. * @description
  19855. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  19856. * {@link ng.directive:ngClass ngClass}, except they work in
  19857. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  19858. *
  19859. * This directive can be applied only within the scope of an
  19860. * {@link ng.directive:ngRepeat ngRepeat}.
  19861. *
  19862. * @element ANY
  19863. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  19864. * of the evaluation can be a string representing space delimited class names or an array.
  19865. *
  19866. * @example
  19867. <example>
  19868. <file name="index.html">
  19869. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  19870. <li ng-repeat="name in names">
  19871. <span ng-class-odd="'odd'" ng-class-even="'even'">
  19872. {{name}}
  19873. </span>
  19874. </li>
  19875. </ol>
  19876. </file>
  19877. <file name="style.css">
  19878. .odd {
  19879. color: red;
  19880. }
  19881. .even {
  19882. color: blue;
  19883. }
  19884. </file>
  19885. <file name="protractor.js" type="protractor">
  19886. it('should check ng-class-odd and ng-class-even', function() {
  19887. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  19888. toMatch(/odd/);
  19889. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  19890. toMatch(/even/);
  19891. });
  19892. </file>
  19893. </example>
  19894. */
  19895. var ngClassOddDirective = classDirective('Odd', 0);
  19896. /**
  19897. * @ngdoc directive
  19898. * @name ngClassEven
  19899. * @restrict AC
  19900. *
  19901. * @description
  19902. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  19903. * {@link ng.directive:ngClass ngClass}, except they work in
  19904. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  19905. *
  19906. * This directive can be applied only within the scope of an
  19907. * {@link ng.directive:ngRepeat ngRepeat}.
  19908. *
  19909. * @element ANY
  19910. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  19911. * result of the evaluation can be a string representing space delimited class names or an array.
  19912. *
  19913. * @example
  19914. <example>
  19915. <file name="index.html">
  19916. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  19917. <li ng-repeat="name in names">
  19918. <span ng-class-odd="'odd'" ng-class-even="'even'">
  19919. {{name}} &nbsp; &nbsp; &nbsp;
  19920. </span>
  19921. </li>
  19922. </ol>
  19923. </file>
  19924. <file name="style.css">
  19925. .odd {
  19926. color: red;
  19927. }
  19928. .even {
  19929. color: blue;
  19930. }
  19931. </file>
  19932. <file name="protractor.js" type="protractor">
  19933. it('should check ng-class-odd and ng-class-even', function() {
  19934. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  19935. toMatch(/odd/);
  19936. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  19937. toMatch(/even/);
  19938. });
  19939. </file>
  19940. </example>
  19941. */
  19942. var ngClassEvenDirective = classDirective('Even', 1);
  19943. /**
  19944. * @ngdoc directive
  19945. * @name ngCloak
  19946. * @restrict AC
  19947. *
  19948. * @description
  19949. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  19950. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  19951. * directive to avoid the undesirable flicker effect caused by the html template display.
  19952. *
  19953. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  19954. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  19955. * of the browser view.
  19956. *
  19957. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  19958. * `angular.min.js`.
  19959. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  19960. *
  19961. * ```css
  19962. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  19963. * display: none !important;
  19964. * }
  19965. * ```
  19966. *
  19967. * When this css rule is loaded by the browser, all html elements (including their children) that
  19968. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  19969. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  19970. * the compiled element visible.
  19971. *
  19972. * For the best result, the `angular.js` script must be loaded in the head section of the html
  19973. * document; alternatively, the css rule above must be included in the external stylesheet of the
  19974. * application.
  19975. *
  19976. * Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
  19977. * cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
  19978. * class `ng-cloak` in addition to the `ngCloak` directive as shown in the example below.
  19979. *
  19980. * @element ANY
  19981. *
  19982. * @example
  19983. <example>
  19984. <file name="index.html">
  19985. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  19986. <div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
  19987. </file>
  19988. <file name="protractor.js" type="protractor">
  19989. it('should remove the template directive and css class', function() {
  19990. expect($('#template1').getAttribute('ng-cloak')).
  19991. toBeNull();
  19992. expect($('#template2').getAttribute('ng-cloak')).
  19993. toBeNull();
  19994. });
  19995. </file>
  19996. </example>
  19997. *
  19998. */
  19999. var ngCloakDirective = ngDirective({
  20000. compile: function(element, attr) {
  20001. attr.$set('ngCloak', undefined);
  20002. element.removeClass('ng-cloak');
  20003. }
  20004. });
  20005. /**
  20006. * @ngdoc directive
  20007. * @name ngController
  20008. *
  20009. * @description
  20010. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  20011. * supports the principles behind the Model-View-Controller design pattern.
  20012. *
  20013. * MVC components in angular:
  20014. *
  20015. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  20016. * are accessed through bindings.
  20017. * * View — The template (HTML with data bindings) that is rendered into the View.
  20018. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  20019. * logic behind the application to decorate the scope with functions and values
  20020. *
  20021. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  20022. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  20023. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  20024. * and executed twice.
  20025. *
  20026. * @element ANY
  20027. * @scope
  20028. * @priority 500
  20029. * @param {expression} ngController Name of a constructor function registered with the current
  20030. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  20031. * that on the current scope evaluates to a constructor function.
  20032. *
  20033. * The controller instance can be published into a scope property by specifying
  20034. * `ng-controller="as propertyName"`.
  20035. *
  20036. * If the current `$controllerProvider` is configured to use globals (via
  20037. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  20038. * also be the name of a globally accessible constructor function (not recommended).
  20039. *
  20040. * @example
  20041. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  20042. * greeting are methods declared on the controller (see source tab). These methods can
  20043. * easily be called from the angular markup. Any changes to the data are automatically reflected
  20044. * in the View without the need for a manual update.
  20045. *
  20046. * Two different declaration styles are included below:
  20047. *
  20048. * * one binds methods and properties directly onto the controller using `this`:
  20049. * `ng-controller="SettingsController1 as settings"`
  20050. * * one injects `$scope` into the controller:
  20051. * `ng-controller="SettingsController2"`
  20052. *
  20053. * The second option is more common in the Angular community, and is generally used in boilerplates
  20054. * and in this guide. However, there are advantages to binding properties directly to the controller
  20055. * and avoiding scope.
  20056. *
  20057. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  20058. * multiple controllers apply to an element.
  20059. * * If you are writing your controllers as classes you have easier access to the properties and
  20060. * methods, which will appear on the scope, from inside the controller code.
  20061. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  20062. * inheritance masking primitives.
  20063. *
  20064. * This example demonstrates the `controller as` syntax.
  20065. *
  20066. * <example name="ngControllerAs" module="controllerAsExample">
  20067. * <file name="index.html">
  20068. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  20069. * Name: <input type="text" ng-model="settings.name"/>
  20070. * [ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
  20071. * Contact:
  20072. * <ul>
  20073. * <li ng-repeat="contact in settings.contacts">
  20074. * <select ng-model="contact.type">
  20075. * <option>phone</option>
  20076. * <option>email</option>
  20077. * </select>
  20078. * <input type="text" ng-model="contact.value"/>
  20079. * [ <a href="" ng-click="settings.clearContact(contact)">clear</a>
  20080. * | <a href="" ng-click="settings.removeContact(contact)">X</a> ]
  20081. * </li>
  20082. * <li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
  20083. * </ul>
  20084. * </div>
  20085. * </file>
  20086. * <file name="app.js">
  20087. * angular.module('controllerAsExample', [])
  20088. * .controller('SettingsController1', SettingsController1);
  20089. *
  20090. * function SettingsController1() {
  20091. * this.name = "John Smith";
  20092. * this.contacts = [
  20093. * {type: 'phone', value: '408 555 1212'},
  20094. * {type: 'email', value: 'john.smith@example.org'} ];
  20095. * }
  20096. *
  20097. * SettingsController1.prototype.greet = function() {
  20098. * alert(this.name);
  20099. * };
  20100. *
  20101. * SettingsController1.prototype.addContact = function() {
  20102. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  20103. * };
  20104. *
  20105. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  20106. * var index = this.contacts.indexOf(contactToRemove);
  20107. * this.contacts.splice(index, 1);
  20108. * };
  20109. *
  20110. * SettingsController1.prototype.clearContact = function(contact) {
  20111. * contact.type = 'phone';
  20112. * contact.value = '';
  20113. * };
  20114. * </file>
  20115. * <file name="protractor.js" type="protractor">
  20116. * it('should check controller as', function() {
  20117. * var container = element(by.id('ctrl-as-exmpl'));
  20118. * expect(container.element(by.model('settings.name'))
  20119. * .getAttribute('value')).toBe('John Smith');
  20120. *
  20121. * var firstRepeat =
  20122. * container.element(by.repeater('contact in settings.contacts').row(0));
  20123. * var secondRepeat =
  20124. * container.element(by.repeater('contact in settings.contacts').row(1));
  20125. *
  20126. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20127. * .toBe('408 555 1212');
  20128. *
  20129. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20130. * .toBe('john.smith@example.org');
  20131. *
  20132. * firstRepeat.element(by.linkText('clear')).click();
  20133. *
  20134. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20135. * .toBe('');
  20136. *
  20137. * container.element(by.linkText('add')).click();
  20138. *
  20139. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  20140. * .element(by.model('contact.value'))
  20141. * .getAttribute('value'))
  20142. * .toBe('yourname@example.org');
  20143. * });
  20144. * </file>
  20145. * </example>
  20146. *
  20147. * This example demonstrates the "attach to `$scope`" style of controller.
  20148. *
  20149. * <example name="ngController" module="controllerExample">
  20150. * <file name="index.html">
  20151. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  20152. * Name: <input type="text" ng-model="name"/>
  20153. * [ <a href="" ng-click="greet()">greet</a> ]<br/>
  20154. * Contact:
  20155. * <ul>
  20156. * <li ng-repeat="contact in contacts">
  20157. * <select ng-model="contact.type">
  20158. * <option>phone</option>
  20159. * <option>email</option>
  20160. * </select>
  20161. * <input type="text" ng-model="contact.value"/>
  20162. * [ <a href="" ng-click="clearContact(contact)">clear</a>
  20163. * | <a href="" ng-click="removeContact(contact)">X</a> ]
  20164. * </li>
  20165. * <li>[ <a href="" ng-click="addContact()">add</a> ]</li>
  20166. * </ul>
  20167. * </div>
  20168. * </file>
  20169. * <file name="app.js">
  20170. * angular.module('controllerExample', [])
  20171. * .controller('SettingsController2', ['$scope', SettingsController2]);
  20172. *
  20173. * function SettingsController2($scope) {
  20174. * $scope.name = "John Smith";
  20175. * $scope.contacts = [
  20176. * {type:'phone', value:'408 555 1212'},
  20177. * {type:'email', value:'john.smith@example.org'} ];
  20178. *
  20179. * $scope.greet = function() {
  20180. * alert($scope.name);
  20181. * };
  20182. *
  20183. * $scope.addContact = function() {
  20184. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  20185. * };
  20186. *
  20187. * $scope.removeContact = function(contactToRemove) {
  20188. * var index = $scope.contacts.indexOf(contactToRemove);
  20189. * $scope.contacts.splice(index, 1);
  20190. * };
  20191. *
  20192. * $scope.clearContact = function(contact) {
  20193. * contact.type = 'phone';
  20194. * contact.value = '';
  20195. * };
  20196. * }
  20197. * </file>
  20198. * <file name="protractor.js" type="protractor">
  20199. * it('should check controller', function() {
  20200. * var container = element(by.id('ctrl-exmpl'));
  20201. *
  20202. * expect(container.element(by.model('name'))
  20203. * .getAttribute('value')).toBe('John Smith');
  20204. *
  20205. * var firstRepeat =
  20206. * container.element(by.repeater('contact in contacts').row(0));
  20207. * var secondRepeat =
  20208. * container.element(by.repeater('contact in contacts').row(1));
  20209. *
  20210. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20211. * .toBe('408 555 1212');
  20212. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  20213. * .toBe('john.smith@example.org');
  20214. *
  20215. * firstRepeat.element(by.linkText('clear')).click();
  20216. *
  20217. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  20218. * .toBe('');
  20219. *
  20220. * container.element(by.linkText('add')).click();
  20221. *
  20222. * expect(container.element(by.repeater('contact in contacts').row(2))
  20223. * .element(by.model('contact.value'))
  20224. * .getAttribute('value'))
  20225. * .toBe('yourname@example.org');
  20226. * });
  20227. * </file>
  20228. *</example>
  20229. */
  20230. var ngControllerDirective = [function() {
  20231. return {
  20232. restrict: 'A',
  20233. scope: true,
  20234. controller: '@',
  20235. priority: 500
  20236. };
  20237. }];
  20238. /**
  20239. * @ngdoc directive
  20240. * @name ngCsp
  20241. *
  20242. * @element html
  20243. * @description
  20244. * Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
  20245. *
  20246. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  20247. *
  20248. * CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
  20249. * For Angular to be CSP compatible there are only two things that we need to do differently:
  20250. *
  20251. * - don't use `Function` constructor to generate optimized value getters
  20252. * - don't inject custom stylesheet into the document
  20253. *
  20254. * AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
  20255. * directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
  20256. * evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
  20257. * be raised.
  20258. *
  20259. * CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
  20260. * includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
  20261. * To make those directives work in CSP mode, include the `angular-csp.css` manually.
  20262. *
  20263. * Angular tries to autodetect if CSP is active and automatically turn on the CSP-safe mode. This
  20264. * autodetection however triggers a CSP error to be logged in the console:
  20265. *
  20266. * ```
  20267. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  20268. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  20269. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  20270. * ```
  20271. *
  20272. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  20273. * directive on the root element of the application or on the `angular.js` script tag, whichever
  20274. * appears first in the html document.
  20275. *
  20276. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  20277. *
  20278. * @example
  20279. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  20280. ```html
  20281. <!doctype html>
  20282. <html ng-app ng-csp>
  20283. ...
  20284. ...
  20285. </html>
  20286. ```
  20287. * @example
  20288. // Note: the suffix `.csp` in the example name triggers
  20289. // csp mode in our http server!
  20290. <example name="example.csp" module="cspExample" ng-csp="true">
  20291. <file name="index.html">
  20292. <div ng-controller="MainController as ctrl">
  20293. <div>
  20294. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  20295. <span id="counter">
  20296. {{ctrl.counter}}
  20297. </span>
  20298. </div>
  20299. <div>
  20300. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  20301. <span id="evilError">
  20302. {{ctrl.evilError}}
  20303. </span>
  20304. </div>
  20305. </div>
  20306. </file>
  20307. <file name="script.js">
  20308. angular.module('cspExample', [])
  20309. .controller('MainController', function() {
  20310. this.counter = 0;
  20311. this.inc = function() {
  20312. this.counter++;
  20313. };
  20314. this.evil = function() {
  20315. // jshint evil:true
  20316. try {
  20317. eval('1+2');
  20318. } catch (e) {
  20319. this.evilError = e.message;
  20320. }
  20321. };
  20322. });
  20323. </file>
  20324. <file name="protractor.js" type="protractor">
  20325. var util, webdriver;
  20326. var incBtn = element(by.id('inc'));
  20327. var counter = element(by.id('counter'));
  20328. var evilBtn = element(by.id('evil'));
  20329. var evilError = element(by.id('evilError'));
  20330. function getAndClearSevereErrors() {
  20331. return browser.manage().logs().get('browser').then(function(browserLog) {
  20332. return browserLog.filter(function(logEntry) {
  20333. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  20334. });
  20335. });
  20336. }
  20337. function clearErrors() {
  20338. getAndClearSevereErrors();
  20339. }
  20340. function expectNoErrors() {
  20341. getAndClearSevereErrors().then(function(filteredLog) {
  20342. expect(filteredLog.length).toEqual(0);
  20343. if (filteredLog.length) {
  20344. console.log('browser console errors: ' + util.inspect(filteredLog));
  20345. }
  20346. });
  20347. }
  20348. function expectError(regex) {
  20349. getAndClearSevereErrors().then(function(filteredLog) {
  20350. var found = false;
  20351. filteredLog.forEach(function(log) {
  20352. if (log.message.match(regex)) {
  20353. found = true;
  20354. }
  20355. });
  20356. if (!found) {
  20357. throw new Error('expected an error that matches ' + regex);
  20358. }
  20359. });
  20360. }
  20361. beforeEach(function() {
  20362. util = require('util');
  20363. webdriver = require('protractor/node_modules/selenium-webdriver');
  20364. });
  20365. // For now, we only test on Chrome,
  20366. // as Safari does not load the page with Protractor's injected scripts,
  20367. // and Firefox webdriver always disables content security policy (#6358)
  20368. if (browser.params.browser !== 'chrome') {
  20369. return;
  20370. }
  20371. it('should not report errors when the page is loaded', function() {
  20372. // clear errors so we are not dependent on previous tests
  20373. clearErrors();
  20374. // Need to reload the page as the page is already loaded when
  20375. // we come here
  20376. browser.driver.getCurrentUrl().then(function(url) {
  20377. browser.get(url);
  20378. });
  20379. expectNoErrors();
  20380. });
  20381. it('should evaluate expressions', function() {
  20382. expect(counter.getText()).toEqual('0');
  20383. incBtn.click();
  20384. expect(counter.getText()).toEqual('1');
  20385. expectNoErrors();
  20386. });
  20387. it('should throw and report an error when using "eval"', function() {
  20388. evilBtn.click();
  20389. expect(evilError.getText()).toMatch(/Content Security Policy/);
  20390. expectError(/Content Security Policy/);
  20391. });
  20392. </file>
  20393. </example>
  20394. */
  20395. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  20396. // bootstrap the system (before $parse is instantiated), for this reason we just have
  20397. // the csp.isActive() fn that looks for ng-csp attribute anywhere in the current doc
  20398. /**
  20399. * @ngdoc directive
  20400. * @name ngClick
  20401. *
  20402. * @description
  20403. * The ngClick directive allows you to specify custom behavior when
  20404. * an element is clicked.
  20405. *
  20406. * @element ANY
  20407. * @priority 0
  20408. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  20409. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  20410. *
  20411. * @example
  20412. <example>
  20413. <file name="index.html">
  20414. <button ng-click="count = count + 1" ng-init="count=0">
  20415. Increment
  20416. </button>
  20417. <span>
  20418. count: {{count}}
  20419. </span>
  20420. </file>
  20421. <file name="protractor.js" type="protractor">
  20422. it('should check ng-click', function() {
  20423. expect(element(by.binding('count')).getText()).toMatch('0');
  20424. element(by.css('button')).click();
  20425. expect(element(by.binding('count')).getText()).toMatch('1');
  20426. });
  20427. </file>
  20428. </example>
  20429. */
  20430. /*
  20431. * A directive that allows creation of custom onclick handlers that are defined as angular
  20432. * expressions and are compiled and executed within the current scope.
  20433. *
  20434. * Events that are handled via these handler are always configured not to propagate further.
  20435. */
  20436. var ngEventDirectives = {};
  20437. // For events that might fire synchronously during DOM manipulation
  20438. // we need to execute their event handlers asynchronously using $evalAsync,
  20439. // so that they are not executed in an inconsistent state.
  20440. var forceAsyncEvents = {
  20441. 'blur': true,
  20442. 'focus': true
  20443. };
  20444. forEach(
  20445. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  20446. function(eventName) {
  20447. var directiveName = directiveNormalize('ng-' + eventName);
  20448. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  20449. return {
  20450. restrict: 'A',
  20451. compile: function($element, attr) {
  20452. var fn = $parse(attr[directiveName]);
  20453. return function ngEventHandler(scope, element) {
  20454. element.on(eventName, function(event) {
  20455. var callback = function() {
  20456. fn(scope, {$event:event});
  20457. };
  20458. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  20459. scope.$evalAsync(callback);
  20460. } else {
  20461. scope.$apply(callback);
  20462. }
  20463. });
  20464. };
  20465. }
  20466. };
  20467. }];
  20468. }
  20469. );
  20470. /**
  20471. * @ngdoc directive
  20472. * @name ngDblclick
  20473. *
  20474. * @description
  20475. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  20476. *
  20477. * @element ANY
  20478. * @priority 0
  20479. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  20480. * a dblclick. (The Event object is available as `$event`)
  20481. *
  20482. * @example
  20483. <example>
  20484. <file name="index.html">
  20485. <button ng-dblclick="count = count + 1" ng-init="count=0">
  20486. Increment (on double click)
  20487. </button>
  20488. count: {{count}}
  20489. </file>
  20490. </example>
  20491. */
  20492. /**
  20493. * @ngdoc directive
  20494. * @name ngMousedown
  20495. *
  20496. * @description
  20497. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  20498. *
  20499. * @element ANY
  20500. * @priority 0
  20501. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  20502. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  20503. *
  20504. * @example
  20505. <example>
  20506. <file name="index.html">
  20507. <button ng-mousedown="count = count + 1" ng-init="count=0">
  20508. Increment (on mouse down)
  20509. </button>
  20510. count: {{count}}
  20511. </file>
  20512. </example>
  20513. */
  20514. /**
  20515. * @ngdoc directive
  20516. * @name ngMouseup
  20517. *
  20518. * @description
  20519. * Specify custom behavior on mouseup event.
  20520. *
  20521. * @element ANY
  20522. * @priority 0
  20523. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  20524. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  20525. *
  20526. * @example
  20527. <example>
  20528. <file name="index.html">
  20529. <button ng-mouseup="count = count + 1" ng-init="count=0">
  20530. Increment (on mouse up)
  20531. </button>
  20532. count: {{count}}
  20533. </file>
  20534. </example>
  20535. */
  20536. /**
  20537. * @ngdoc directive
  20538. * @name ngMouseover
  20539. *
  20540. * @description
  20541. * Specify custom behavior on mouseover event.
  20542. *
  20543. * @element ANY
  20544. * @priority 0
  20545. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  20546. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  20547. *
  20548. * @example
  20549. <example>
  20550. <file name="index.html">
  20551. <button ng-mouseover="count = count + 1" ng-init="count=0">
  20552. Increment (when mouse is over)
  20553. </button>
  20554. count: {{count}}
  20555. </file>
  20556. </example>
  20557. */
  20558. /**
  20559. * @ngdoc directive
  20560. * @name ngMouseenter
  20561. *
  20562. * @description
  20563. * Specify custom behavior on mouseenter event.
  20564. *
  20565. * @element ANY
  20566. * @priority 0
  20567. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  20568. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  20569. *
  20570. * @example
  20571. <example>
  20572. <file name="index.html">
  20573. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  20574. Increment (when mouse enters)
  20575. </button>
  20576. count: {{count}}
  20577. </file>
  20578. </example>
  20579. */
  20580. /**
  20581. * @ngdoc directive
  20582. * @name ngMouseleave
  20583. *
  20584. * @description
  20585. * Specify custom behavior on mouseleave event.
  20586. *
  20587. * @element ANY
  20588. * @priority 0
  20589. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  20590. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  20591. *
  20592. * @example
  20593. <example>
  20594. <file name="index.html">
  20595. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  20596. Increment (when mouse leaves)
  20597. </button>
  20598. count: {{count}}
  20599. </file>
  20600. </example>
  20601. */
  20602. /**
  20603. * @ngdoc directive
  20604. * @name ngMousemove
  20605. *
  20606. * @description
  20607. * Specify custom behavior on mousemove event.
  20608. *
  20609. * @element ANY
  20610. * @priority 0
  20611. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  20612. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  20613. *
  20614. * @example
  20615. <example>
  20616. <file name="index.html">
  20617. <button ng-mousemove="count = count + 1" ng-init="count=0">
  20618. Increment (when mouse moves)
  20619. </button>
  20620. count: {{count}}
  20621. </file>
  20622. </example>
  20623. */
  20624. /**
  20625. * @ngdoc directive
  20626. * @name ngKeydown
  20627. *
  20628. * @description
  20629. * Specify custom behavior on keydown event.
  20630. *
  20631. * @element ANY
  20632. * @priority 0
  20633. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  20634. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  20635. *
  20636. * @example
  20637. <example>
  20638. <file name="index.html">
  20639. <input ng-keydown="count = count + 1" ng-init="count=0">
  20640. key down count: {{count}}
  20641. </file>
  20642. </example>
  20643. */
  20644. /**
  20645. * @ngdoc directive
  20646. * @name ngKeyup
  20647. *
  20648. * @description
  20649. * Specify custom behavior on keyup event.
  20650. *
  20651. * @element ANY
  20652. * @priority 0
  20653. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  20654. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  20655. *
  20656. * @example
  20657. <example>
  20658. <file name="index.html">
  20659. <p>Typing in the input box below updates the key count</p>
  20660. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  20661. <p>Typing in the input box below updates the keycode</p>
  20662. <input ng-keyup="event=$event">
  20663. <p>event keyCode: {{ event.keyCode }}</p>
  20664. <p>event altKey: {{ event.altKey }}</p>
  20665. </file>
  20666. </example>
  20667. */
  20668. /**
  20669. * @ngdoc directive
  20670. * @name ngKeypress
  20671. *
  20672. * @description
  20673. * Specify custom behavior on keypress event.
  20674. *
  20675. * @element ANY
  20676. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  20677. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  20678. * and can be interrogated for keyCode, altKey, etc.)
  20679. *
  20680. * @example
  20681. <example>
  20682. <file name="index.html">
  20683. <input ng-keypress="count = count + 1" ng-init="count=0">
  20684. key press count: {{count}}
  20685. </file>
  20686. </example>
  20687. */
  20688. /**
  20689. * @ngdoc directive
  20690. * @name ngSubmit
  20691. *
  20692. * @description
  20693. * Enables binding angular expressions to onsubmit events.
  20694. *
  20695. * Additionally it prevents the default action (which for form means sending the request to the
  20696. * server and reloading the current page), but only if the form does not contain `action`,
  20697. * `data-action`, or `x-action` attributes.
  20698. *
  20699. * <div class="alert alert-warning">
  20700. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  20701. * `ngSubmit` handlers together. See the
  20702. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  20703. * for a detailed discussion of when `ngSubmit` may be triggered.
  20704. * </div>
  20705. *
  20706. * @element form
  20707. * @priority 0
  20708. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  20709. * ({@link guide/expression#-event- Event object is available as `$event`})
  20710. *
  20711. * @example
  20712. <example module="submitExample">
  20713. <file name="index.html">
  20714. <script>
  20715. angular.module('submitExample', [])
  20716. .controller('ExampleController', ['$scope', function($scope) {
  20717. $scope.list = [];
  20718. $scope.text = 'hello';
  20719. $scope.submit = function() {
  20720. if ($scope.text) {
  20721. $scope.list.push(this.text);
  20722. $scope.text = '';
  20723. }
  20724. };
  20725. }]);
  20726. </script>
  20727. <form ng-submit="submit()" ng-controller="ExampleController">
  20728. Enter text and hit enter:
  20729. <input type="text" ng-model="text" name="text" />
  20730. <input type="submit" id="submit" value="Submit" />
  20731. <pre>list={{list}}</pre>
  20732. </form>
  20733. </file>
  20734. <file name="protractor.js" type="protractor">
  20735. it('should check ng-submit', function() {
  20736. expect(element(by.binding('list')).getText()).toBe('list=[]');
  20737. element(by.css('#submit')).click();
  20738. expect(element(by.binding('list')).getText()).toContain('hello');
  20739. expect(element(by.model('text')).getAttribute('value')).toBe('');
  20740. });
  20741. it('should ignore empty strings', function() {
  20742. expect(element(by.binding('list')).getText()).toBe('list=[]');
  20743. element(by.css('#submit')).click();
  20744. element(by.css('#submit')).click();
  20745. expect(element(by.binding('list')).getText()).toContain('hello');
  20746. });
  20747. </file>
  20748. </example>
  20749. */
  20750. /**
  20751. * @ngdoc directive
  20752. * @name ngFocus
  20753. *
  20754. * @description
  20755. * Specify custom behavior on focus event.
  20756. *
  20757. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  20758. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  20759. * during an `$apply` to ensure a consistent state.
  20760. *
  20761. * @element window, input, select, textarea, a
  20762. * @priority 0
  20763. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  20764. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  20765. *
  20766. * @example
  20767. * See {@link ng.directive:ngClick ngClick}
  20768. */
  20769. /**
  20770. * @ngdoc directive
  20771. * @name ngBlur
  20772. *
  20773. * @description
  20774. * Specify custom behavior on blur event.
  20775. *
  20776. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  20777. * an element has lost focus.
  20778. *
  20779. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  20780. * (e.g. removing a focussed input),
  20781. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  20782. * during an `$apply` to ensure a consistent state.
  20783. *
  20784. * @element window, input, select, textarea, a
  20785. * @priority 0
  20786. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  20787. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  20788. *
  20789. * @example
  20790. * See {@link ng.directive:ngClick ngClick}
  20791. */
  20792. /**
  20793. * @ngdoc directive
  20794. * @name ngCopy
  20795. *
  20796. * @description
  20797. * Specify custom behavior on copy event.
  20798. *
  20799. * @element window, input, select, textarea, a
  20800. * @priority 0
  20801. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  20802. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  20803. *
  20804. * @example
  20805. <example>
  20806. <file name="index.html">
  20807. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  20808. copied: {{copied}}
  20809. </file>
  20810. </example>
  20811. */
  20812. /**
  20813. * @ngdoc directive
  20814. * @name ngCut
  20815. *
  20816. * @description
  20817. * Specify custom behavior on cut event.
  20818. *
  20819. * @element window, input, select, textarea, a
  20820. * @priority 0
  20821. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  20822. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  20823. *
  20824. * @example
  20825. <example>
  20826. <file name="index.html">
  20827. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  20828. cut: {{cut}}
  20829. </file>
  20830. </example>
  20831. */
  20832. /**
  20833. * @ngdoc directive
  20834. * @name ngPaste
  20835. *
  20836. * @description
  20837. * Specify custom behavior on paste event.
  20838. *
  20839. * @element window, input, select, textarea, a
  20840. * @priority 0
  20841. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  20842. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  20843. *
  20844. * @example
  20845. <example>
  20846. <file name="index.html">
  20847. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  20848. pasted: {{paste}}
  20849. </file>
  20850. </example>
  20851. */
  20852. /**
  20853. * @ngdoc directive
  20854. * @name ngIf
  20855. * @restrict A
  20856. *
  20857. * @description
  20858. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  20859. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  20860. * value then the element is removed from the DOM, otherwise a clone of the
  20861. * element is reinserted into the DOM.
  20862. *
  20863. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  20864. * element in the DOM rather than changing its visibility via the `display` css property. A common
  20865. * case when this difference is significant is when using css selectors that rely on an element's
  20866. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  20867. *
  20868. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  20869. * is created when the element is restored. The scope created within `ngIf` inherits from
  20870. * its parent scope using
  20871. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  20872. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  20873. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  20874. * variable within the child scope will override (hide) the value in the parent scope.
  20875. *
  20876. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  20877. * is if an element's class attribute is directly modified after it's compiled, using something like
  20878. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  20879. * the added class will be lost because the original compiled state is used to regenerate the element.
  20880. *
  20881. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  20882. * and `leave` effects.
  20883. *
  20884. * @animations
  20885. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  20886. * leave - happens just before the `ngIf` contents are removed from the DOM
  20887. *
  20888. * @element ANY
  20889. * @scope
  20890. * @priority 600
  20891. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  20892. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  20893. * element is added to the DOM tree.
  20894. *
  20895. * @example
  20896. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20897. <file name="index.html">
  20898. Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
  20899. Show when checked:
  20900. <span ng-if="checked" class="animate-if">
  20901. This is removed when the checkbox is unchecked.
  20902. </span>
  20903. </file>
  20904. <file name="animations.css">
  20905. .animate-if {
  20906. background:white;
  20907. border:1px solid black;
  20908. padding:10px;
  20909. }
  20910. .animate-if.ng-enter, .animate-if.ng-leave {
  20911. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20912. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20913. }
  20914. .animate-if.ng-enter,
  20915. .animate-if.ng-leave.ng-leave-active {
  20916. opacity:0;
  20917. }
  20918. .animate-if.ng-leave,
  20919. .animate-if.ng-enter.ng-enter-active {
  20920. opacity:1;
  20921. }
  20922. </file>
  20923. </example>
  20924. */
  20925. var ngIfDirective = ['$animate', function($animate) {
  20926. return {
  20927. multiElement: true,
  20928. transclude: 'element',
  20929. priority: 600,
  20930. terminal: true,
  20931. restrict: 'A',
  20932. $$tlb: true,
  20933. link: function ($scope, $element, $attr, ctrl, $transclude) {
  20934. var block, childScope, previousElements;
  20935. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  20936. if (value) {
  20937. if (!childScope) {
  20938. $transclude(function (clone, newScope) {
  20939. childScope = newScope;
  20940. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  20941. // Note: We only need the first/last node of the cloned nodes.
  20942. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  20943. // by a directive with templateUrl when its template arrives.
  20944. block = {
  20945. clone: clone
  20946. };
  20947. $animate.enter(clone, $element.parent(), $element);
  20948. });
  20949. }
  20950. } else {
  20951. if (previousElements) {
  20952. previousElements.remove();
  20953. previousElements = null;
  20954. }
  20955. if (childScope) {
  20956. childScope.$destroy();
  20957. childScope = null;
  20958. }
  20959. if (block) {
  20960. previousElements = getBlockNodes(block.clone);
  20961. $animate.leave(previousElements).then(function() {
  20962. previousElements = null;
  20963. });
  20964. block = null;
  20965. }
  20966. }
  20967. });
  20968. }
  20969. };
  20970. }];
  20971. /**
  20972. * @ngdoc directive
  20973. * @name ngInclude
  20974. * @restrict ECA
  20975. *
  20976. * @description
  20977. * Fetches, compiles and includes an external HTML fragment.
  20978. *
  20979. * By default, the template URL is restricted to the same domain and protocol as the
  20980. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  20981. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  20982. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  20983. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  20984. * ng.$sce Strict Contextual Escaping}.
  20985. *
  20986. * In addition, the browser's
  20987. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  20988. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  20989. * policy may further restrict whether the template is successfully loaded.
  20990. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  20991. * access on some browsers.
  20992. *
  20993. * @animations
  20994. * enter - animation is used to bring new content into the browser.
  20995. * leave - animation is used to animate existing content away.
  20996. *
  20997. * The enter and leave animation occur concurrently.
  20998. *
  20999. * @scope
  21000. * @priority 400
  21001. *
  21002. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  21003. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  21004. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  21005. *
  21006. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  21007. * $anchorScroll} to scroll the viewport after the content is loaded.
  21008. *
  21009. * - If the attribute is not set, disable scrolling.
  21010. * - If the attribute is set without value, enable scrolling.
  21011. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  21012. *
  21013. * @example
  21014. <example module="includeExample" deps="angular-animate.js" animations="true">
  21015. <file name="index.html">
  21016. <div ng-controller="ExampleController">
  21017. <select ng-model="template" ng-options="t.name for t in templates">
  21018. <option value="">(blank)</option>
  21019. </select>
  21020. url of the template: <tt>{{template.url}}</tt>
  21021. <hr/>
  21022. <div class="slide-animate-container">
  21023. <div class="slide-animate" ng-include="template.url"></div>
  21024. </div>
  21025. </div>
  21026. </file>
  21027. <file name="script.js">
  21028. angular.module('includeExample', ['ngAnimate'])
  21029. .controller('ExampleController', ['$scope', function($scope) {
  21030. $scope.templates =
  21031. [ { name: 'template1.html', url: 'template1.html'},
  21032. { name: 'template2.html', url: 'template2.html'} ];
  21033. $scope.template = $scope.templates[0];
  21034. }]);
  21035. </file>
  21036. <file name="template1.html">
  21037. Content of template1.html
  21038. </file>
  21039. <file name="template2.html">
  21040. Content of template2.html
  21041. </file>
  21042. <file name="animations.css">
  21043. .slide-animate-container {
  21044. position:relative;
  21045. background:white;
  21046. border:1px solid black;
  21047. height:40px;
  21048. overflow:hidden;
  21049. }
  21050. .slide-animate {
  21051. padding:10px;
  21052. }
  21053. .slide-animate.ng-enter, .slide-animate.ng-leave {
  21054. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21055. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21056. position:absolute;
  21057. top:0;
  21058. left:0;
  21059. right:0;
  21060. bottom:0;
  21061. display:block;
  21062. padding:10px;
  21063. }
  21064. .slide-animate.ng-enter {
  21065. top:-50px;
  21066. }
  21067. .slide-animate.ng-enter.ng-enter-active {
  21068. top:0;
  21069. }
  21070. .slide-animate.ng-leave {
  21071. top:0;
  21072. }
  21073. .slide-animate.ng-leave.ng-leave-active {
  21074. top:50px;
  21075. }
  21076. </file>
  21077. <file name="protractor.js" type="protractor">
  21078. var templateSelect = element(by.model('template'));
  21079. var includeElem = element(by.css('[ng-include]'));
  21080. it('should load template1.html', function() {
  21081. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  21082. });
  21083. it('should load template2.html', function() {
  21084. if (browser.params.browser == 'firefox') {
  21085. // Firefox can't handle using selects
  21086. // See https://github.com/angular/protractor/issues/480
  21087. return;
  21088. }
  21089. templateSelect.click();
  21090. templateSelect.all(by.css('option')).get(2).click();
  21091. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  21092. });
  21093. it('should change to blank', function() {
  21094. if (browser.params.browser == 'firefox') {
  21095. // Firefox can't handle using selects
  21096. return;
  21097. }
  21098. templateSelect.click();
  21099. templateSelect.all(by.css('option')).get(0).click();
  21100. expect(includeElem.isPresent()).toBe(false);
  21101. });
  21102. </file>
  21103. </example>
  21104. */
  21105. /**
  21106. * @ngdoc event
  21107. * @name ngInclude#$includeContentRequested
  21108. * @eventType emit on the scope ngInclude was declared in
  21109. * @description
  21110. * Emitted every time the ngInclude content is requested.
  21111. *
  21112. * @param {Object} angularEvent Synthetic event object.
  21113. * @param {String} src URL of content to load.
  21114. */
  21115. /**
  21116. * @ngdoc event
  21117. * @name ngInclude#$includeContentLoaded
  21118. * @eventType emit on the current ngInclude scope
  21119. * @description
  21120. * Emitted every time the ngInclude content is reloaded.
  21121. *
  21122. * @param {Object} angularEvent Synthetic event object.
  21123. * @param {String} src URL of content to load.
  21124. */
  21125. /**
  21126. * @ngdoc event
  21127. * @name ngInclude#$includeContentError
  21128. * @eventType emit on the scope ngInclude was declared in
  21129. * @description
  21130. * Emitted when a template HTTP request yields an erronous response (status < 200 || status > 299)
  21131. *
  21132. * @param {Object} angularEvent Synthetic event object.
  21133. * @param {String} src URL of content to load.
  21134. */
  21135. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate', '$sce',
  21136. function($templateRequest, $anchorScroll, $animate, $sce) {
  21137. return {
  21138. restrict: 'ECA',
  21139. priority: 400,
  21140. terminal: true,
  21141. transclude: 'element',
  21142. controller: angular.noop,
  21143. compile: function(element, attr) {
  21144. var srcExp = attr.ngInclude || attr.src,
  21145. onloadExp = attr.onload || '',
  21146. autoScrollExp = attr.autoscroll;
  21147. return function(scope, $element, $attr, ctrl, $transclude) {
  21148. var changeCounter = 0,
  21149. currentScope,
  21150. previousElement,
  21151. currentElement;
  21152. var cleanupLastIncludeContent = function() {
  21153. if(previousElement) {
  21154. previousElement.remove();
  21155. previousElement = null;
  21156. }
  21157. if(currentScope) {
  21158. currentScope.$destroy();
  21159. currentScope = null;
  21160. }
  21161. if(currentElement) {
  21162. $animate.leave(currentElement).then(function() {
  21163. previousElement = null;
  21164. });
  21165. previousElement = currentElement;
  21166. currentElement = null;
  21167. }
  21168. };
  21169. scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
  21170. var afterAnimation = function() {
  21171. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  21172. $anchorScroll();
  21173. }
  21174. };
  21175. var thisChangeId = ++changeCounter;
  21176. if (src) {
  21177. //set the 2nd param to true to ignore the template request error so that the inner
  21178. //contents and scope can be cleaned up.
  21179. $templateRequest(src, true).then(function(response) {
  21180. if (thisChangeId !== changeCounter) return;
  21181. var newScope = scope.$new();
  21182. ctrl.template = response;
  21183. // Note: This will also link all children of ng-include that were contained in the original
  21184. // html. If that content contains controllers, ... they could pollute/change the scope.
  21185. // However, using ng-include on an element with additional content does not make sense...
  21186. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  21187. // function is called before linking the content, which would apply child
  21188. // directives to non existing elements.
  21189. var clone = $transclude(newScope, function(clone) {
  21190. cleanupLastIncludeContent();
  21191. $animate.enter(clone, null, $element).then(afterAnimation);
  21192. });
  21193. currentScope = newScope;
  21194. currentElement = clone;
  21195. currentScope.$emit('$includeContentLoaded', src);
  21196. scope.$eval(onloadExp);
  21197. }, function() {
  21198. if (thisChangeId === changeCounter) {
  21199. cleanupLastIncludeContent();
  21200. scope.$emit('$includeContentError', src);
  21201. }
  21202. });
  21203. scope.$emit('$includeContentRequested', src);
  21204. } else {
  21205. cleanupLastIncludeContent();
  21206. ctrl.template = null;
  21207. }
  21208. });
  21209. };
  21210. }
  21211. };
  21212. }];
  21213. // This directive is called during the $transclude call of the first `ngInclude` directive.
  21214. // It will replace and compile the content of the element with the loaded template.
  21215. // We need this directive so that the element content is already filled when
  21216. // the link function of another directive on the same element as ngInclude
  21217. // is called.
  21218. var ngIncludeFillContentDirective = ['$compile',
  21219. function($compile) {
  21220. return {
  21221. restrict: 'ECA',
  21222. priority: -400,
  21223. require: 'ngInclude',
  21224. link: function(scope, $element, $attr, ctrl) {
  21225. if (/SVG/.test($element[0].toString())) {
  21226. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  21227. // support innerHTML, so detect this here and try to generate the contents
  21228. // specially.
  21229. $element.empty();
  21230. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  21231. function namespaceAdaptedClone(clone) {
  21232. $element.append(clone);
  21233. }, undefined, undefined, $element);
  21234. return;
  21235. }
  21236. $element.html(ctrl.template);
  21237. $compile($element.contents())(scope);
  21238. }
  21239. };
  21240. }];
  21241. /**
  21242. * @ngdoc directive
  21243. * @name ngInit
  21244. * @restrict AC
  21245. *
  21246. * @description
  21247. * The `ngInit` directive allows you to evaluate an expression in the
  21248. * current scope.
  21249. *
  21250. * <div class="alert alert-error">
  21251. * The only appropriate use of `ngInit` is for aliasing special properties of
  21252. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
  21253. * should use {@link guide/controller controllers} rather than `ngInit`
  21254. * to initialize values on a scope.
  21255. * </div>
  21256. * <div class="alert alert-warning">
  21257. * **Note**: If you have assignment in `ngInit` along with {@link ng.$filter `$filter`}, make
  21258. * sure you have parenthesis for correct precedence:
  21259. * <pre class="prettyprint">
  21260. * <div ng-init="test1 = (data | orderBy:'name')"></div>
  21261. * </pre>
  21262. * </div>
  21263. *
  21264. * @priority 450
  21265. *
  21266. * @element ANY
  21267. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  21268. *
  21269. * @example
  21270. <example module="initExample">
  21271. <file name="index.html">
  21272. <script>
  21273. angular.module('initExample', [])
  21274. .controller('ExampleController', ['$scope', function($scope) {
  21275. $scope.list = [['a', 'b'], ['c', 'd']];
  21276. }]);
  21277. </script>
  21278. <div ng-controller="ExampleController">
  21279. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  21280. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  21281. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  21282. </div>
  21283. </div>
  21284. </div>
  21285. </file>
  21286. <file name="protractor.js" type="protractor">
  21287. it('should alias index positions', function() {
  21288. var elements = element.all(by.css('.example-init'));
  21289. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  21290. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  21291. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  21292. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  21293. });
  21294. </file>
  21295. </example>
  21296. */
  21297. var ngInitDirective = ngDirective({
  21298. priority: 450,
  21299. compile: function() {
  21300. return {
  21301. pre: function(scope, element, attrs) {
  21302. scope.$eval(attrs.ngInit);
  21303. }
  21304. };
  21305. }
  21306. });
  21307. /**
  21308. * @ngdoc directive
  21309. * @name ngNonBindable
  21310. * @restrict AC
  21311. * @priority 1000
  21312. *
  21313. * @description
  21314. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  21315. * DOM element. This is useful if the element contains what appears to be Angular directives and
  21316. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  21317. * displays snippets of code, for instance.
  21318. *
  21319. * @element ANY
  21320. *
  21321. * @example
  21322. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  21323. * but the one wrapped in `ngNonBindable` is left alone.
  21324. *
  21325. * @example
  21326. <example>
  21327. <file name="index.html">
  21328. <div>Normal: {{1 + 2}}</div>
  21329. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  21330. </file>
  21331. <file name="protractor.js" type="protractor">
  21332. it('should check ng-non-bindable', function() {
  21333. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  21334. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  21335. });
  21336. </file>
  21337. </example>
  21338. */
  21339. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  21340. /**
  21341. * @ngdoc directive
  21342. * @name ngPluralize
  21343. * @restrict EA
  21344. *
  21345. * @description
  21346. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  21347. * These rules are bundled with angular.js, but can be overridden
  21348. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  21349. * by specifying the mappings between
  21350. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21351. * and the strings to be displayed.
  21352. *
  21353. * # Plural categories and explicit number rules
  21354. * There are two
  21355. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  21356. * in Angular's default en-US locale: "one" and "other".
  21357. *
  21358. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  21359. * any number that is not 1), an explicit number rule can only match one number. For example, the
  21360. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  21361. * and explicit number rules throughout the rest of this documentation.
  21362. *
  21363. * # Configuring ngPluralize
  21364. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  21365. * You can also provide an optional attribute, `offset`.
  21366. *
  21367. * The value of the `count` attribute can be either a string or an {@link guide/expression
  21368. * Angular expression}; these are evaluated on the current scope for its bound value.
  21369. *
  21370. * The `when` attribute specifies the mappings between plural categories and the actual
  21371. * string to be displayed. The value of the attribute should be a JSON object.
  21372. *
  21373. * The following example shows how to configure ngPluralize:
  21374. *
  21375. * ```html
  21376. * <ng-pluralize count="personCount"
  21377. when="{'0': 'Nobody is viewing.',
  21378. * 'one': '1 person is viewing.',
  21379. * 'other': '{} people are viewing.'}">
  21380. * </ng-pluralize>
  21381. *```
  21382. *
  21383. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  21384. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  21385. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  21386. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  21387. * show "a dozen people are viewing".
  21388. *
  21389. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  21390. * into pluralized strings. In the previous example, Angular will replace `{}` with
  21391. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  21392. * for <span ng-non-bindable>{{numberExpression}}</span>.
  21393. *
  21394. * # Configuring ngPluralize with offset
  21395. * The `offset` attribute allows further customization of pluralized text, which can result in
  21396. * a better user experience. For example, instead of the message "4 people are viewing this document",
  21397. * you might display "John, Kate and 2 others are viewing this document".
  21398. * The offset attribute allows you to offset a number by any desired value.
  21399. * Let's take a look at an example:
  21400. *
  21401. * ```html
  21402. * <ng-pluralize count="personCount" offset=2
  21403. * when="{'0': 'Nobody is viewing.',
  21404. * '1': '{{person1}} is viewing.',
  21405. * '2': '{{person1}} and {{person2}} are viewing.',
  21406. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21407. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21408. * </ng-pluralize>
  21409. * ```
  21410. *
  21411. * Notice that we are still using two plural categories(one, other), but we added
  21412. * three explicit number rules 0, 1 and 2.
  21413. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  21414. * When three people view the document, no explicit number rule is found, so
  21415. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  21416. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  21417. * is shown.
  21418. *
  21419. * Note that when you specify offsets, you must provide explicit number rules for
  21420. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  21421. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  21422. * plural categories "one" and "other".
  21423. *
  21424. * @param {string|expression} count The variable to be bound to.
  21425. * @param {string} when The mapping between plural category to its corresponding strings.
  21426. * @param {number=} offset Offset to deduct from the total number.
  21427. *
  21428. * @example
  21429. <example module="pluralizeExample">
  21430. <file name="index.html">
  21431. <script>
  21432. angular.module('pluralizeExample', [])
  21433. .controller('ExampleController', ['$scope', function($scope) {
  21434. $scope.person1 = 'Igor';
  21435. $scope.person2 = 'Misko';
  21436. $scope.personCount = 1;
  21437. }]);
  21438. </script>
  21439. <div ng-controller="ExampleController">
  21440. Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
  21441. Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
  21442. Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
  21443. <!--- Example with simple pluralization rules for en locale --->
  21444. Without Offset:
  21445. <ng-pluralize count="personCount"
  21446. when="{'0': 'Nobody is viewing.',
  21447. 'one': '1 person is viewing.',
  21448. 'other': '{} people are viewing.'}">
  21449. </ng-pluralize><br>
  21450. <!--- Example with offset --->
  21451. With Offset(2):
  21452. <ng-pluralize count="personCount" offset=2
  21453. when="{'0': 'Nobody is viewing.',
  21454. '1': '{{person1}} is viewing.',
  21455. '2': '{{person1}} and {{person2}} are viewing.',
  21456. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  21457. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  21458. </ng-pluralize>
  21459. </div>
  21460. </file>
  21461. <file name="protractor.js" type="protractor">
  21462. it('should show correct pluralized string', function() {
  21463. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  21464. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21465. var countInput = element(by.model('personCount'));
  21466. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  21467. expect(withOffset.getText()).toEqual('Igor is viewing.');
  21468. countInput.clear();
  21469. countInput.sendKeys('0');
  21470. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  21471. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  21472. countInput.clear();
  21473. countInput.sendKeys('2');
  21474. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  21475. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  21476. countInput.clear();
  21477. countInput.sendKeys('3');
  21478. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  21479. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  21480. countInput.clear();
  21481. countInput.sendKeys('4');
  21482. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  21483. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  21484. });
  21485. it('should show data-bound names', function() {
  21486. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  21487. var personCount = element(by.model('personCount'));
  21488. var person1 = element(by.model('person1'));
  21489. var person2 = element(by.model('person2'));
  21490. personCount.clear();
  21491. personCount.sendKeys('4');
  21492. person1.clear();
  21493. person1.sendKeys('Di');
  21494. person2.clear();
  21495. person2.sendKeys('Vojta');
  21496. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  21497. });
  21498. </file>
  21499. </example>
  21500. */
  21501. var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
  21502. var BRACE = /{}/g;
  21503. return {
  21504. restrict: 'EA',
  21505. link: function(scope, element, attr) {
  21506. var numberExp = attr.count,
  21507. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  21508. offset = attr.offset || 0,
  21509. whens = scope.$eval(whenExp) || {},
  21510. whensExpFns = {},
  21511. startSymbol = $interpolate.startSymbol(),
  21512. endSymbol = $interpolate.endSymbol(),
  21513. isWhen = /^when(Minus)?(.+)$/;
  21514. forEach(attr, function(expression, attributeName) {
  21515. if (isWhen.test(attributeName)) {
  21516. whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
  21517. element.attr(attr.$attr[attributeName]);
  21518. }
  21519. });
  21520. forEach(whens, function(expression, key) {
  21521. whensExpFns[key] =
  21522. $interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
  21523. offset + endSymbol));
  21524. });
  21525. scope.$watch(function ngPluralizeWatch() {
  21526. var value = parseFloat(scope.$eval(numberExp));
  21527. if (!isNaN(value)) {
  21528. //if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
  21529. //check it against pluralization rules in $locale service
  21530. if (!(value in whens)) value = $locale.pluralCat(value - offset);
  21531. return whensExpFns[value](scope);
  21532. } else {
  21533. return '';
  21534. }
  21535. }, function ngPluralizeWatchAction(newVal) {
  21536. element.text(newVal);
  21537. });
  21538. }
  21539. };
  21540. }];
  21541. /**
  21542. * @ngdoc directive
  21543. * @name ngRepeat
  21544. *
  21545. * @description
  21546. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  21547. * instance gets its own scope, where the given loop variable is set to the current collection item,
  21548. * and `$index` is set to the item index or key.
  21549. *
  21550. * Special properties are exposed on the local scope of each template instance, including:
  21551. *
  21552. * | Variable | Type | Details |
  21553. * |-----------|-----------------|-----------------------------------------------------------------------------|
  21554. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  21555. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  21556. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  21557. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  21558. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  21559. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  21560. *
  21561. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  21562. * This may be useful when, for instance, nesting ngRepeats.
  21563. *
  21564. * # Special repeat start and end points
  21565. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  21566. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  21567. * 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)
  21568. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  21569. *
  21570. * The example below makes use of this feature:
  21571. * ```html
  21572. * <header ng-repeat-start="item in items">
  21573. * Header {{ item }}
  21574. * </header>
  21575. * <div class="body">
  21576. * Body {{ item }}
  21577. * </div>
  21578. * <footer ng-repeat-end>
  21579. * Footer {{ item }}
  21580. * </footer>
  21581. * ```
  21582. *
  21583. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  21584. * ```html
  21585. * <header>
  21586. * Header A
  21587. * </header>
  21588. * <div class="body">
  21589. * Body A
  21590. * </div>
  21591. * <footer>
  21592. * Footer A
  21593. * </footer>
  21594. * <header>
  21595. * Header B
  21596. * </header>
  21597. * <div class="body">
  21598. * Body B
  21599. * </div>
  21600. * <footer>
  21601. * Footer B
  21602. * </footer>
  21603. * ```
  21604. *
  21605. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  21606. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  21607. *
  21608. * @animations
  21609. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  21610. *
  21611. * **.leave** - when an item is removed from the list or when an item is filtered out
  21612. *
  21613. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  21614. *
  21615. * @element ANY
  21616. * @scope
  21617. * @priority 1000
  21618. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  21619. * formats are currently supported:
  21620. *
  21621. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  21622. * is a scope expression giving the collection to enumerate.
  21623. *
  21624. * For example: `album in artist.albums`.
  21625. *
  21626. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  21627. * and `expression` is the scope expression giving the collection to enumerate.
  21628. *
  21629. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  21630. *
  21631. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
  21632. * which can be used to associate the objects in the collection with the DOM elements. If no tracking function
  21633. * is specified the ng-repeat associates elements by identity in the collection. It is an error to have
  21634. * more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
  21635. * mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
  21636. * before specifying a tracking expression.
  21637. *
  21638. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  21639. * will be associated by item identity in the array.
  21640. *
  21641. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  21642. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  21643. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  21644. * element in the same way in the DOM.
  21645. *
  21646. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  21647. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  21648. * property is same.
  21649. *
  21650. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  21651. * to items in conjunction with a tracking expression.
  21652. *
  21653. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  21654. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  21655. * when a filter is active on the repeater, but the filtered result set is empty.
  21656. *
  21657. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  21658. * the items have been processed through the filter.
  21659. *
  21660. * @example
  21661. * This example initializes the scope to a list of names and
  21662. * then uses `ngRepeat` to display every person:
  21663. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21664. <file name="index.html">
  21665. <div ng-init="friends = [
  21666. {name:'John', age:25, gender:'boy'},
  21667. {name:'Jessie', age:30, gender:'girl'},
  21668. {name:'Johanna', age:28, gender:'girl'},
  21669. {name:'Joy', age:15, gender:'girl'},
  21670. {name:'Mary', age:28, gender:'girl'},
  21671. {name:'Peter', age:95, gender:'boy'},
  21672. {name:'Sebastian', age:50, gender:'boy'},
  21673. {name:'Erika', age:27, gender:'girl'},
  21674. {name:'Patrick', age:40, gender:'boy'},
  21675. {name:'Samantha', age:60, gender:'girl'}
  21676. ]">
  21677. I have {{friends.length}} friends. They are:
  21678. <input type="search" ng-model="q" placeholder="filter friends..." />
  21679. <ul class="example-animate-container">
  21680. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  21681. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  21682. </li>
  21683. <li class="animate-repeat" ng-if="results.length == 0">
  21684. <strong>No results found...</strong>
  21685. </li>
  21686. </ul>
  21687. </div>
  21688. </file>
  21689. <file name="animations.css">
  21690. .example-animate-container {
  21691. background:white;
  21692. border:1px solid black;
  21693. list-style:none;
  21694. margin:0;
  21695. padding:0 10px;
  21696. }
  21697. .animate-repeat {
  21698. line-height:40px;
  21699. list-style:none;
  21700. box-sizing:border-box;
  21701. }
  21702. .animate-repeat.ng-move,
  21703. .animate-repeat.ng-enter,
  21704. .animate-repeat.ng-leave {
  21705. -webkit-transition:all linear 0.5s;
  21706. transition:all linear 0.5s;
  21707. }
  21708. .animate-repeat.ng-leave.ng-leave-active,
  21709. .animate-repeat.ng-move,
  21710. .animate-repeat.ng-enter {
  21711. opacity:0;
  21712. max-height:0;
  21713. }
  21714. .animate-repeat.ng-leave,
  21715. .animate-repeat.ng-move.ng-move-active,
  21716. .animate-repeat.ng-enter.ng-enter-active {
  21717. opacity:1;
  21718. max-height:40px;
  21719. }
  21720. </file>
  21721. <file name="protractor.js" type="protractor">
  21722. var friends = element.all(by.repeater('friend in friends'));
  21723. it('should render initial data set', function() {
  21724. expect(friends.count()).toBe(10);
  21725. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  21726. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  21727. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  21728. expect(element(by.binding('friends.length')).getText())
  21729. .toMatch("I have 10 friends. They are:");
  21730. });
  21731. it('should update repeater when filter predicate changes', function() {
  21732. expect(friends.count()).toBe(10);
  21733. element(by.model('q')).sendKeys('ma');
  21734. expect(friends.count()).toBe(2);
  21735. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  21736. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  21737. });
  21738. </file>
  21739. </example>
  21740. */
  21741. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  21742. var NG_REMOVED = '$$NG_REMOVED';
  21743. var ngRepeatMinErr = minErr('ngRepeat');
  21744. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  21745. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  21746. scope[valueIdentifier] = value;
  21747. if (keyIdentifier) scope[keyIdentifier] = key;
  21748. scope.$index = index;
  21749. scope.$first = (index === 0);
  21750. scope.$last = (index === (arrayLength - 1));
  21751. scope.$middle = !(scope.$first || scope.$last);
  21752. // jshint bitwise: false
  21753. scope.$odd = !(scope.$even = (index&1) === 0);
  21754. // jshint bitwise: true
  21755. };
  21756. var getBlockStart = function(block) {
  21757. return block.clone[0];
  21758. };
  21759. var getBlockEnd = function(block) {
  21760. return block.clone[block.clone.length - 1];
  21761. };
  21762. return {
  21763. restrict: 'A',
  21764. multiElement: true,
  21765. transclude: 'element',
  21766. priority: 1000,
  21767. terminal: true,
  21768. $$tlb: true,
  21769. compile: function ngRepeatCompile($element, $attr) {
  21770. var expression = $attr.ngRepeat;
  21771. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  21772. var match = expression.match(/^\s*([\s\S]+?)\s+in\s+([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+track\s+by\s+([\s\S]+?))?\s*$/);
  21773. if (!match) {
  21774. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  21775. expression);
  21776. }
  21777. var lhs = match[1];
  21778. var rhs = match[2];
  21779. var aliasAs = match[3];
  21780. var trackByExp = match[4];
  21781. match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
  21782. if (!match) {
  21783. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  21784. lhs);
  21785. }
  21786. var valueIdentifier = match[3] || match[1];
  21787. var keyIdentifier = match[2];
  21788. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  21789. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent)$/.test(aliasAs))) {
  21790. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  21791. aliasAs);
  21792. }
  21793. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  21794. var hashFnLocals = {$id: hashKey};
  21795. if (trackByExp) {
  21796. trackByExpGetter = $parse(trackByExp);
  21797. } else {
  21798. trackByIdArrayFn = function (key, value) {
  21799. return hashKey(value);
  21800. };
  21801. trackByIdObjFn = function (key) {
  21802. return key;
  21803. };
  21804. }
  21805. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  21806. if (trackByExpGetter) {
  21807. trackByIdExpFn = function(key, value, index) {
  21808. // assign key, value, and $index to the locals so that they can be used in hash functions
  21809. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  21810. hashFnLocals[valueIdentifier] = value;
  21811. hashFnLocals.$index = index;
  21812. return trackByExpGetter($scope, hashFnLocals);
  21813. };
  21814. }
  21815. // Store a list of elements from previous run. This is a hash where key is the item from the
  21816. // iterator, and the value is objects with following properties.
  21817. // - scope: bound scope
  21818. // - element: previous element.
  21819. // - index: position
  21820. //
  21821. // We are using no-proto object so that we don't need to guard against inherited props via
  21822. // hasOwnProperty.
  21823. var lastBlockMap = createMap();
  21824. //watch props
  21825. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  21826. var index, length,
  21827. previousNode = $element[0], // node that cloned nodes should be inserted after
  21828. // initialized to the comment node anchor
  21829. nextNode,
  21830. // Same as lastBlockMap but it has the current state. It will become the
  21831. // lastBlockMap on the next iteration.
  21832. nextBlockMap = createMap(),
  21833. collectionLength,
  21834. key, value, // key/value of iteration
  21835. trackById,
  21836. trackByIdFn,
  21837. collectionKeys,
  21838. block, // last object information {scope, element, id}
  21839. nextBlockOrder,
  21840. elementsToRemove;
  21841. if (aliasAs) {
  21842. $scope[aliasAs] = collection;
  21843. }
  21844. if (isArrayLike(collection)) {
  21845. collectionKeys = collection;
  21846. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  21847. } else {
  21848. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  21849. // if object, extract keys, sort them and use to determine order of iteration over obj props
  21850. collectionKeys = [];
  21851. for (var itemKey in collection) {
  21852. if (collection.hasOwnProperty(itemKey) && itemKey.charAt(0) != '$') {
  21853. collectionKeys.push(itemKey);
  21854. }
  21855. }
  21856. collectionKeys.sort();
  21857. }
  21858. collectionLength = collectionKeys.length;
  21859. nextBlockOrder = new Array(collectionLength);
  21860. // locate existing items
  21861. for (index = 0; index < collectionLength; index++) {
  21862. key = (collection === collectionKeys) ? index : collectionKeys[index];
  21863. value = collection[key];
  21864. trackById = trackByIdFn(key, value, index);
  21865. if (lastBlockMap[trackById]) {
  21866. // found previously seen block
  21867. block = lastBlockMap[trackById];
  21868. delete lastBlockMap[trackById];
  21869. nextBlockMap[trackById] = block;
  21870. nextBlockOrder[index] = block;
  21871. } else if (nextBlockMap[trackById]) {
  21872. // if collision detected. restore lastBlockMap and throw an error
  21873. forEach(nextBlockOrder, function (block) {
  21874. if (block && block.scope) lastBlockMap[block.id] = block;
  21875. });
  21876. throw ngRepeatMinErr('dupes',
  21877. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  21878. expression, trackById, toJson(value));
  21879. } else {
  21880. // new never before seen block
  21881. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  21882. nextBlockMap[trackById] = true;
  21883. }
  21884. }
  21885. // remove leftover items
  21886. for (var blockKey in lastBlockMap) {
  21887. block = lastBlockMap[blockKey];
  21888. elementsToRemove = getBlockNodes(block.clone);
  21889. $animate.leave(elementsToRemove);
  21890. if (elementsToRemove[0].parentNode) {
  21891. // if the element was not removed yet because of pending animation, mark it as deleted
  21892. // so that we can ignore it later
  21893. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  21894. elementsToRemove[index][NG_REMOVED] = true;
  21895. }
  21896. }
  21897. block.scope.$destroy();
  21898. }
  21899. // we are not using forEach for perf reasons (trying to avoid #call)
  21900. for (index = 0; index < collectionLength; index++) {
  21901. key = (collection === collectionKeys) ? index : collectionKeys[index];
  21902. value = collection[key];
  21903. block = nextBlockOrder[index];
  21904. if (block.scope) {
  21905. // if we have already seen this object, then we need to reuse the
  21906. // associated scope/element
  21907. nextNode = previousNode;
  21908. // skip nodes that are already pending removal via leave animation
  21909. do {
  21910. nextNode = nextNode.nextSibling;
  21911. } while (nextNode && nextNode[NG_REMOVED]);
  21912. if (getBlockStart(block) != nextNode) {
  21913. // existing item which got moved
  21914. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  21915. }
  21916. previousNode = getBlockEnd(block);
  21917. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  21918. } else {
  21919. // new item which we don't know about
  21920. $transclude(function ngRepeatTransclude(clone, scope) {
  21921. block.scope = scope;
  21922. // http://jsperf.com/clone-vs-createcomment
  21923. var endNode = ngRepeatEndComment.cloneNode(false);
  21924. clone[clone.length++] = endNode;
  21925. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  21926. $animate.enter(clone, null, jqLite(previousNode));
  21927. previousNode = endNode;
  21928. // Note: We only need the first/last node of the cloned nodes.
  21929. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  21930. // by a directive with templateUrl when its template arrives.
  21931. block.clone = clone;
  21932. nextBlockMap[block.id] = block;
  21933. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  21934. });
  21935. }
  21936. }
  21937. lastBlockMap = nextBlockMap;
  21938. });
  21939. };
  21940. }
  21941. };
  21942. }];
  21943. var NG_HIDE_CLASS = 'ng-hide';
  21944. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  21945. /**
  21946. * @ngdoc directive
  21947. * @name ngShow
  21948. *
  21949. * @description
  21950. * The `ngShow` directive shows or hides the given HTML element based on the expression
  21951. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  21952. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  21953. * in AngularJS and sets the display style to none (using an !important flag).
  21954. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  21955. *
  21956. * ```html
  21957. * <!-- when $scope.myValue is truthy (element is visible) -->
  21958. * <div ng-show="myValue"></div>
  21959. *
  21960. * <!-- when $scope.myValue is falsy (element is hidden) -->
  21961. * <div ng-show="myValue" class="ng-hide"></div>
  21962. * ```
  21963. *
  21964. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  21965. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  21966. * from the element causing the element not to appear hidden.
  21967. *
  21968. * ## Why is !important used?
  21969. *
  21970. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  21971. * can be easily overridden by heavier selectors. For example, something as simple
  21972. * as changing the display style on a HTML list item would make hidden elements appear visible.
  21973. * This also becomes a bigger issue when dealing with CSS frameworks.
  21974. *
  21975. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  21976. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  21977. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  21978. *
  21979. * ### Overriding `.ng-hide`
  21980. *
  21981. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  21982. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  21983. * class in CSS:
  21984. *
  21985. * ```css
  21986. * .ng-hide {
  21987. * /&#42; this is just another form of hiding an element &#42;/
  21988. * display:block!important;
  21989. * position:absolute;
  21990. * top:-9999px;
  21991. * left:-9999px;
  21992. * }
  21993. * ```
  21994. *
  21995. * By default you don't need to override in CSS anything and the animations will work around the display style.
  21996. *
  21997. * ## A note about animations with `ngShow`
  21998. *
  21999. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22000. * is true and false. This system works like the animation system present with ngClass except that
  22001. * you must also include the !important flag to override the display property
  22002. * so that you can perform an animation when the element is hidden during the time of the animation.
  22003. *
  22004. * ```css
  22005. * //
  22006. * //a working example can be found at the bottom of this page
  22007. * //
  22008. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22009. * /&#42; this is required as of 1.3x to properly
  22010. * apply all styling in a show/hide animation &#42;/
  22011. * transition:0s linear all;
  22012. * }
  22013. *
  22014. * .my-element.ng-hide-add-active,
  22015. * .my-element.ng-hide-remove-active {
  22016. * /&#42; the transition is defined in the active class &#42;/
  22017. * transition:1s linear all;
  22018. * }
  22019. *
  22020. * .my-element.ng-hide-add { ... }
  22021. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22022. * .my-element.ng-hide-remove { ... }
  22023. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22024. * ```
  22025. *
  22026. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22027. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22028. *
  22029. * @animations
  22030. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  22031. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  22032. *
  22033. * @element ANY
  22034. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  22035. * then the element is shown or hidden respectively.
  22036. *
  22037. * @example
  22038. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22039. <file name="index.html">
  22040. Click me: <input type="checkbox" ng-model="checked"><br/>
  22041. <div>
  22042. Show:
  22043. <div class="check-element animate-show" ng-show="checked">
  22044. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22045. </div>
  22046. </div>
  22047. <div>
  22048. Hide:
  22049. <div class="check-element animate-show" ng-hide="checked">
  22050. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22051. </div>
  22052. </div>
  22053. </file>
  22054. <file name="glyphicons.css">
  22055. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  22056. </file>
  22057. <file name="animations.css">
  22058. .animate-show {
  22059. line-height:20px;
  22060. opacity:1;
  22061. padding:10px;
  22062. border:1px solid black;
  22063. background:white;
  22064. }
  22065. .animate-show.ng-hide-add.ng-hide-add-active,
  22066. .animate-show.ng-hide-remove.ng-hide-remove-active {
  22067. -webkit-transition:all linear 0.5s;
  22068. transition:all linear 0.5s;
  22069. }
  22070. .animate-show.ng-hide {
  22071. line-height:0;
  22072. opacity:0;
  22073. padding:0 10px;
  22074. }
  22075. .check-element {
  22076. padding:10px;
  22077. border:1px solid black;
  22078. background:white;
  22079. }
  22080. </file>
  22081. <file name="protractor.js" type="protractor">
  22082. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22083. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22084. it('should check ng-show / ng-hide', function() {
  22085. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22086. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22087. element(by.model('checked')).click();
  22088. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22089. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22090. });
  22091. </file>
  22092. </example>
  22093. */
  22094. var ngShowDirective = ['$animate', function($animate) {
  22095. return {
  22096. restrict: 'A',
  22097. multiElement: true,
  22098. link: function(scope, element, attr) {
  22099. scope.$watch(attr.ngShow, function ngShowWatchAction(value){
  22100. // we're adding a temporary, animation-specific class for ng-hide since this way
  22101. // we can control when the element is actually displayed on screen without having
  22102. // to have a global/greedy CSS selector that breaks when other animations are run.
  22103. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  22104. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  22105. tempClasses : NG_HIDE_IN_PROGRESS_CLASS
  22106. });
  22107. });
  22108. }
  22109. };
  22110. }];
  22111. /**
  22112. * @ngdoc directive
  22113. * @name ngHide
  22114. *
  22115. * @description
  22116. * The `ngHide` directive shows or hides the given HTML element based on the expression
  22117. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  22118. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  22119. * in AngularJS and sets the display style to none (using an !important flag).
  22120. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  22121. *
  22122. * ```html
  22123. * <!-- when $scope.myValue is truthy (element is hidden) -->
  22124. * <div ng-hide="myValue" class="ng-hide"></div>
  22125. *
  22126. * <!-- when $scope.myValue is falsy (element is visible) -->
  22127. * <div ng-hide="myValue"></div>
  22128. * ```
  22129. *
  22130. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  22131. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  22132. * from the element causing the element not to appear hidden.
  22133. *
  22134. * ## Why is !important used?
  22135. *
  22136. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  22137. * can be easily overridden by heavier selectors. For example, something as simple
  22138. * as changing the display style on a HTML list item would make hidden elements appear visible.
  22139. * This also becomes a bigger issue when dealing with CSS frameworks.
  22140. *
  22141. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  22142. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  22143. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  22144. *
  22145. * ### Overriding `.ng-hide`
  22146. *
  22147. * By default, the `.ng-hide` class will style the element with `display:none!important`. If you wish to change
  22148. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  22149. * class in CSS:
  22150. *
  22151. * ```css
  22152. * .ng-hide {
  22153. * /&#42; this is just another form of hiding an element &#42;/
  22154. * display:block!important;
  22155. * position:absolute;
  22156. * top:-9999px;
  22157. * left:-9999px;
  22158. * }
  22159. * ```
  22160. *
  22161. * By default you don't need to override in CSS anything and the animations will work around the display style.
  22162. *
  22163. * ## A note about animations with `ngHide`
  22164. *
  22165. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  22166. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  22167. * CSS class is added and removed for you instead of your own CSS class.
  22168. *
  22169. * ```css
  22170. * //
  22171. * //a working example can be found at the bottom of this page
  22172. * //
  22173. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  22174. * transition:0.5s linear all;
  22175. * }
  22176. *
  22177. * .my-element.ng-hide-add { ... }
  22178. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  22179. * .my-element.ng-hide-remove { ... }
  22180. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  22181. * ```
  22182. *
  22183. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  22184. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  22185. *
  22186. * @animations
  22187. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  22188. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  22189. *
  22190. * @element ANY
  22191. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  22192. * the element is shown or hidden respectively.
  22193. *
  22194. * @example
  22195. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  22196. <file name="index.html">
  22197. Click me: <input type="checkbox" ng-model="checked"><br/>
  22198. <div>
  22199. Show:
  22200. <div class="check-element animate-hide" ng-show="checked">
  22201. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  22202. </div>
  22203. </div>
  22204. <div>
  22205. Hide:
  22206. <div class="check-element animate-hide" ng-hide="checked">
  22207. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  22208. </div>
  22209. </div>
  22210. </file>
  22211. <file name="glyphicons.css">
  22212. @import url(//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css);
  22213. </file>
  22214. <file name="animations.css">
  22215. .animate-hide {
  22216. -webkit-transition:all linear 0.5s;
  22217. transition:all linear 0.5s;
  22218. line-height:20px;
  22219. opacity:1;
  22220. padding:10px;
  22221. border:1px solid black;
  22222. background:white;
  22223. }
  22224. .animate-hide.ng-hide {
  22225. line-height:0;
  22226. opacity:0;
  22227. padding:0 10px;
  22228. }
  22229. .check-element {
  22230. padding:10px;
  22231. border:1px solid black;
  22232. background:white;
  22233. }
  22234. </file>
  22235. <file name="protractor.js" type="protractor">
  22236. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  22237. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  22238. it('should check ng-show / ng-hide', function() {
  22239. expect(thumbsUp.isDisplayed()).toBeFalsy();
  22240. expect(thumbsDown.isDisplayed()).toBeTruthy();
  22241. element(by.model('checked')).click();
  22242. expect(thumbsUp.isDisplayed()).toBeTruthy();
  22243. expect(thumbsDown.isDisplayed()).toBeFalsy();
  22244. });
  22245. </file>
  22246. </example>
  22247. */
  22248. var ngHideDirective = ['$animate', function($animate) {
  22249. return {
  22250. restrict: 'A',
  22251. multiElement: true,
  22252. link: function(scope, element, attr) {
  22253. scope.$watch(attr.ngHide, function ngHideWatchAction(value){
  22254. // The comment inside of the ngShowDirective explains why we add and
  22255. // remove a temporary class for the show/hide animation
  22256. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  22257. tempClasses : NG_HIDE_IN_PROGRESS_CLASS
  22258. });
  22259. });
  22260. }
  22261. };
  22262. }];
  22263. /**
  22264. * @ngdoc directive
  22265. * @name ngStyle
  22266. * @restrict AC
  22267. *
  22268. * @description
  22269. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  22270. *
  22271. * @element ANY
  22272. * @param {expression} ngStyle
  22273. *
  22274. * {@link guide/expression Expression} which evals to an
  22275. * object whose keys are CSS style names and values are corresponding values for those CSS
  22276. * keys.
  22277. *
  22278. * Since some CSS style names are not valid keys for an object, they must be quoted.
  22279. * See the 'background-color' style in the example below.
  22280. *
  22281. * @example
  22282. <example>
  22283. <file name="index.html">
  22284. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  22285. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  22286. <input type="button" value="clear" ng-click="myStyle={}">
  22287. <br/>
  22288. <span ng-style="myStyle">Sample Text</span>
  22289. <pre>myStyle={{myStyle}}</pre>
  22290. </file>
  22291. <file name="style.css">
  22292. span {
  22293. color: black;
  22294. }
  22295. </file>
  22296. <file name="protractor.js" type="protractor">
  22297. var colorSpan = element(by.css('span'));
  22298. it('should check ng-style', function() {
  22299. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22300. element(by.css('input[value=\'set color\']')).click();
  22301. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  22302. element(by.css('input[value=clear]')).click();
  22303. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  22304. });
  22305. </file>
  22306. </example>
  22307. */
  22308. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  22309. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  22310. if (oldStyles && (newStyles !== oldStyles)) {
  22311. forEach(oldStyles, function(val, style) { element.css(style, '');});
  22312. }
  22313. if (newStyles) element.css(newStyles);
  22314. }, true);
  22315. });
  22316. /**
  22317. * @ngdoc directive
  22318. * @name ngSwitch
  22319. * @restrict EA
  22320. *
  22321. * @description
  22322. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  22323. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  22324. * as specified in the template.
  22325. *
  22326. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  22327. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  22328. * matches the value obtained from the evaluated expression. In other words, you define a container element
  22329. * (where you place the directive), place an expression on the **`on="..."` attribute**
  22330. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  22331. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  22332. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  22333. * attribute is displayed.
  22334. *
  22335. * <div class="alert alert-info">
  22336. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  22337. * as literal string values to match against.
  22338. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  22339. * value of the expression `$scope.someVal`.
  22340. * </div>
  22341. * @animations
  22342. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  22343. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  22344. *
  22345. * @usage
  22346. *
  22347. * ```
  22348. * <ANY ng-switch="expression">
  22349. * <ANY ng-switch-when="matchValue1">...</ANY>
  22350. * <ANY ng-switch-when="matchValue2">...</ANY>
  22351. * <ANY ng-switch-default>...</ANY>
  22352. * </ANY>
  22353. * ```
  22354. *
  22355. *
  22356. * @scope
  22357. * @priority 1200
  22358. * @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
  22359. * On child elements add:
  22360. *
  22361. * * `ngSwitchWhen`: the case statement to match against. If match then this
  22362. * case will be displayed. If the same match appears multiple times, all the
  22363. * elements will be displayed.
  22364. * * `ngSwitchDefault`: the default case when no other case match. If there
  22365. * are multiple default cases, all of them will be displayed when no other
  22366. * case match.
  22367. *
  22368. *
  22369. * @example
  22370. <example module="switchExample" deps="angular-animate.js" animations="true">
  22371. <file name="index.html">
  22372. <div ng-controller="ExampleController">
  22373. <select ng-model="selection" ng-options="item for item in items">
  22374. </select>
  22375. <tt>selection={{selection}}</tt>
  22376. <hr/>
  22377. <div class="animate-switch-container"
  22378. ng-switch on="selection">
  22379. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  22380. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  22381. <div class="animate-switch" ng-switch-default>default</div>
  22382. </div>
  22383. </div>
  22384. </file>
  22385. <file name="script.js">
  22386. angular.module('switchExample', ['ngAnimate'])
  22387. .controller('ExampleController', ['$scope', function($scope) {
  22388. $scope.items = ['settings', 'home', 'other'];
  22389. $scope.selection = $scope.items[0];
  22390. }]);
  22391. </file>
  22392. <file name="animations.css">
  22393. .animate-switch-container {
  22394. position:relative;
  22395. background:white;
  22396. border:1px solid black;
  22397. height:40px;
  22398. overflow:hidden;
  22399. }
  22400. .animate-switch {
  22401. padding:10px;
  22402. }
  22403. .animate-switch.ng-animate {
  22404. -webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22405. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22406. position:absolute;
  22407. top:0;
  22408. left:0;
  22409. right:0;
  22410. bottom:0;
  22411. }
  22412. .animate-switch.ng-leave.ng-leave-active,
  22413. .animate-switch.ng-enter {
  22414. top:-50px;
  22415. }
  22416. .animate-switch.ng-leave,
  22417. .animate-switch.ng-enter.ng-enter-active {
  22418. top:0;
  22419. }
  22420. </file>
  22421. <file name="protractor.js" type="protractor">
  22422. var switchElem = element(by.css('[ng-switch]'));
  22423. var select = element(by.model('selection'));
  22424. it('should start in settings', function() {
  22425. expect(switchElem.getText()).toMatch(/Settings Div/);
  22426. });
  22427. it('should change to home', function() {
  22428. select.all(by.css('option')).get(1).click();
  22429. expect(switchElem.getText()).toMatch(/Home Span/);
  22430. });
  22431. it('should select default', function() {
  22432. select.all(by.css('option')).get(2).click();
  22433. expect(switchElem.getText()).toMatch(/default/);
  22434. });
  22435. </file>
  22436. </example>
  22437. */
  22438. var ngSwitchDirective = ['$animate', function($animate) {
  22439. return {
  22440. restrict: 'EA',
  22441. require: 'ngSwitch',
  22442. // asks for $scope to fool the BC controller module
  22443. controller: ['$scope', function ngSwitchController() {
  22444. this.cases = {};
  22445. }],
  22446. link: function(scope, element, attr, ngSwitchController) {
  22447. var watchExpr = attr.ngSwitch || attr.on,
  22448. selectedTranscludes = [],
  22449. selectedElements = [],
  22450. previousLeaveAnimations = [],
  22451. selectedScopes = [];
  22452. var spliceFactory = function(array, index) {
  22453. return function() { array.splice(index, 1); };
  22454. };
  22455. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  22456. var i, ii;
  22457. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  22458. $animate.cancel(previousLeaveAnimations[i]);
  22459. }
  22460. previousLeaveAnimations.length = 0;
  22461. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  22462. var selected = getBlockNodes(selectedElements[i].clone);
  22463. selectedScopes[i].$destroy();
  22464. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  22465. promise.then(spliceFactory(previousLeaveAnimations, i));
  22466. }
  22467. selectedElements.length = 0;
  22468. selectedScopes.length = 0;
  22469. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  22470. forEach(selectedTranscludes, function(selectedTransclude) {
  22471. selectedTransclude.transclude(function(caseElement, selectedScope) {
  22472. selectedScopes.push(selectedScope);
  22473. var anchor = selectedTransclude.element;
  22474. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  22475. var block = { clone: caseElement };
  22476. selectedElements.push(block);
  22477. $animate.enter(caseElement, anchor.parent(), anchor);
  22478. });
  22479. });
  22480. }
  22481. });
  22482. }
  22483. };
  22484. }];
  22485. var ngSwitchWhenDirective = ngDirective({
  22486. transclude: 'element',
  22487. priority: 1200,
  22488. require: '^ngSwitch',
  22489. multiElement: true,
  22490. link: function(scope, element, attrs, ctrl, $transclude) {
  22491. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  22492. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  22493. }
  22494. });
  22495. var ngSwitchDefaultDirective = ngDirective({
  22496. transclude: 'element',
  22497. priority: 1200,
  22498. require: '^ngSwitch',
  22499. multiElement: true,
  22500. link: function(scope, element, attr, ctrl, $transclude) {
  22501. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  22502. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  22503. }
  22504. });
  22505. /**
  22506. * @ngdoc directive
  22507. * @name ngTransclude
  22508. * @restrict EAC
  22509. *
  22510. * @description
  22511. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  22512. *
  22513. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  22514. *
  22515. * @element ANY
  22516. *
  22517. * @example
  22518. <example module="transcludeExample">
  22519. <file name="index.html">
  22520. <script>
  22521. angular.module('transcludeExample', [])
  22522. .directive('pane', function(){
  22523. return {
  22524. restrict: 'E',
  22525. transclude: true,
  22526. scope: { title:'@' },
  22527. template: '<div style="border: 1px solid black;">' +
  22528. '<div style="background-color: gray">{{title}}</div>' +
  22529. '<ng-transclude></ng-transclude>' +
  22530. '</div>'
  22531. };
  22532. })
  22533. .controller('ExampleController', ['$scope', function($scope) {
  22534. $scope.title = 'Lorem Ipsum';
  22535. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  22536. }]);
  22537. </script>
  22538. <div ng-controller="ExampleController">
  22539. <input ng-model="title"><br>
  22540. <textarea ng-model="text"></textarea> <br/>
  22541. <pane title="{{title}}">{{text}}</pane>
  22542. </div>
  22543. </file>
  22544. <file name="protractor.js" type="protractor">
  22545. it('should have transcluded', function() {
  22546. var titleElement = element(by.model('title'));
  22547. titleElement.clear();
  22548. titleElement.sendKeys('TITLE');
  22549. var textElement = element(by.model('text'));
  22550. textElement.clear();
  22551. textElement.sendKeys('TEXT');
  22552. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  22553. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  22554. });
  22555. </file>
  22556. </example>
  22557. *
  22558. */
  22559. var ngTranscludeDirective = ngDirective({
  22560. restrict: 'EAC',
  22561. link: function($scope, $element, $attrs, controller, $transclude) {
  22562. if (!$transclude) {
  22563. throw minErr('ngTransclude')('orphan',
  22564. 'Illegal use of ngTransclude directive in the template! ' +
  22565. 'No parent directive that requires a transclusion found. ' +
  22566. 'Element: {0}',
  22567. startingTag($element));
  22568. }
  22569. $transclude(function(clone) {
  22570. $element.empty();
  22571. $element.append(clone);
  22572. });
  22573. }
  22574. });
  22575. /**
  22576. * @ngdoc directive
  22577. * @name script
  22578. * @restrict E
  22579. *
  22580. * @description
  22581. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  22582. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  22583. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  22584. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  22585. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  22586. *
  22587. * @param {string} type Must be set to `'text/ng-template'`.
  22588. * @param {string} id Cache name of the template.
  22589. *
  22590. * @example
  22591. <example>
  22592. <file name="index.html">
  22593. <script type="text/ng-template" id="/tpl.html">
  22594. Content of the template.
  22595. </script>
  22596. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  22597. <div id="tpl-content" ng-include src="currentTpl"></div>
  22598. </file>
  22599. <file name="protractor.js" type="protractor">
  22600. it('should load template defined inside script tag', function() {
  22601. element(by.css('#tpl-link')).click();
  22602. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  22603. });
  22604. </file>
  22605. </example>
  22606. */
  22607. var scriptDirective = ['$templateCache', function($templateCache) {
  22608. return {
  22609. restrict: 'E',
  22610. terminal: true,
  22611. compile: function(element, attr) {
  22612. if (attr.type == 'text/ng-template') {
  22613. var templateUrl = attr.id,
  22614. // IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
  22615. text = element[0].text;
  22616. $templateCache.put(templateUrl, text);
  22617. }
  22618. }
  22619. };
  22620. }];
  22621. var ngOptionsMinErr = minErr('ngOptions');
  22622. /**
  22623. * @ngdoc directive
  22624. * @name select
  22625. * @restrict E
  22626. *
  22627. * @description
  22628. * HTML `SELECT` element with angular data-binding.
  22629. *
  22630. * # `ngOptions`
  22631. *
  22632. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  22633. * elements for the `<select>` element using the array or object obtained by evaluating the
  22634. * `ngOptions` comprehension_expression.
  22635. *
  22636. * When an item in the `<select>` menu is selected, the array element or object property
  22637. * represented by the selected option will be bound to the model identified by the `ngModel`
  22638. * directive.
  22639. *
  22640. * <div class="alert alert-warning">
  22641. * **Note:** `ngModel` compares by reference, not value. This is important when binding to an
  22642. * array of objects. See an example [in this jsfiddle](http://jsfiddle.net/qWzTb/).
  22643. * </div>
  22644. *
  22645. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  22646. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  22647. * option. See example below for demonstration.
  22648. *
  22649. * <div class="alert alert-warning">
  22650. * **Note:** `ngOptions` provides an iterator facility for the `<option>` element which should be used instead
  22651. * of {@link ng.directive:ngRepeat ngRepeat} when you want the
  22652. * `select` model to be bound to a non-string value. This is because an option element can only
  22653. * be bound to string values at present.
  22654. * </div>
  22655. *
  22656. * <div class="alert alert-info">
  22657. * **Note:** Using `select as` will bind the result of the `select as` expression to the model, but
  22658. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  22659. * or property name (for object data sources) of the value within the collection.
  22660. * </div>
  22661. *
  22662. * **Note:** Using `select as` together with `trackexpr` is not recommended.
  22663. * Reasoning:
  22664. * - Example: &lt;select ng-options="item.subItem as item.label for item in values track by item.id" ng-model="selected"&gt;
  22665. * values: [{id: 1, label: 'aLabel', subItem: {name: 'aSubItem'}}, {id: 2, label: 'bLabel', subItem: {name: 'bSubItem'}}],
  22666. * $scope.selected = {name: 'aSubItem'};
  22667. * - track by is always applied to `value`, with the purpose of preserving the selection,
  22668. * (to `item` in this case)
  22669. * - to calculate whether an item is selected we do the following:
  22670. * 1. apply `track by` to the values in the array, e.g.
  22671. * In the example: [1,2]
  22672. * 2. apply `track by` to the already selected value in `ngModel`:
  22673. * In the example: this is not possible, as `track by` refers to `item.id`, but the selected
  22674. * value from `ngModel` is `{name: aSubItem}`.
  22675. *
  22676. * @param {string} ngModel Assignable angular expression to data-bind to.
  22677. * @param {string=} name Property name of the form under which the control is published.
  22678. * @param {string=} required The control is considered valid only if value is entered.
  22679. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  22680. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  22681. * `required` when you want to data-bind to the `required` attribute.
  22682. * @param {comprehension_expression=} ngOptions in one of the following forms:
  22683. *
  22684. * * for array data sources:
  22685. * * `label` **`for`** `value` **`in`** `array`
  22686. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  22687. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  22688. * * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  22689. * * for object data sources:
  22690. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  22691. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  22692. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  22693. * * `select` **`as`** `label` **`group by`** `group`
  22694. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  22695. *
  22696. * Where:
  22697. *
  22698. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  22699. * * `value`: local variable which will refer to each item in the `array` or each property value
  22700. * of `object` during iteration.
  22701. * * `key`: local variable which will refer to a property name in `object` during iteration.
  22702. * * `label`: The result of this expression will be the label for `<option>` element. The
  22703. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  22704. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  22705. * element. If not specified, `select` expression will default to `value`.
  22706. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  22707. * DOM element.
  22708. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  22709. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  22710. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  22711. * even when the options are recreated (e.g. reloaded from the server).
  22712. *
  22713. * @example
  22714. <example module="selectExample">
  22715. <file name="index.html">
  22716. <script>
  22717. angular.module('selectExample', [])
  22718. .controller('ExampleController', ['$scope', function($scope) {
  22719. $scope.colors = [
  22720. {name:'black', shade:'dark'},
  22721. {name:'white', shade:'light'},
  22722. {name:'red', shade:'dark'},
  22723. {name:'blue', shade:'dark'},
  22724. {name:'yellow', shade:'light'}
  22725. ];
  22726. $scope.myColor = $scope.colors[2]; // red
  22727. }]);
  22728. </script>
  22729. <div ng-controller="ExampleController">
  22730. <ul>
  22731. <li ng-repeat="color in colors">
  22732. Name: <input ng-model="color.name">
  22733. [<a href ng-click="colors.splice($index, 1)">X</a>]
  22734. </li>
  22735. <li>
  22736. [<a href ng-click="colors.push({})">add</a>]
  22737. </li>
  22738. </ul>
  22739. <hr/>
  22740. Color (null not allowed):
  22741. <select ng-model="myColor" ng-options="color.name for color in colors"></select><br>
  22742. Color (null allowed):
  22743. <span class="nullable">
  22744. <select ng-model="myColor" ng-options="color.name for color in colors">
  22745. <option value="">-- choose color --</option>
  22746. </select>
  22747. </span><br/>
  22748. Color grouped by shade:
  22749. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  22750. </select><br/>
  22751. Select <a href ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</a>.<br>
  22752. <hr/>
  22753. Currently selected: {{ {selected_color:myColor} }}
  22754. <div style="border:solid 1px black; height:20px"
  22755. ng-style="{'background-color':myColor.name}">
  22756. </div>
  22757. </div>
  22758. </file>
  22759. <file name="protractor.js" type="protractor">
  22760. it('should check ng-options', function() {
  22761. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  22762. element.all(by.model('myColor')).first().click();
  22763. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  22764. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  22765. element(by.css('.nullable select[ng-model="myColor"]')).click();
  22766. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  22767. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  22768. });
  22769. </file>
  22770. </example>
  22771. */
  22772. var ngOptionsDirective = valueFn({
  22773. restrict: 'A',
  22774. terminal: true
  22775. });
  22776. // jshint maxlen: false
  22777. var selectDirective = ['$compile', '$parse', function($compile, $parse) {
  22778. //000011111111110000000000022222222220000000000000000000003333333333000000000000004444444444444440000000005555555555555550000000666666666666666000000000000000777777777700000000000000000008888888888
  22779. 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]+?))?$/,
  22780. nullModelCtrl = {$setViewValue: noop};
  22781. // jshint maxlen: 100
  22782. return {
  22783. restrict: 'E',
  22784. require: ['select', '?ngModel'],
  22785. controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  22786. var self = this,
  22787. optionsMap = {},
  22788. ngModelCtrl = nullModelCtrl,
  22789. nullOption,
  22790. unknownOption;
  22791. self.databound = $attrs.ngModel;
  22792. self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
  22793. ngModelCtrl = ngModelCtrl_;
  22794. nullOption = nullOption_;
  22795. unknownOption = unknownOption_;
  22796. };
  22797. self.addOption = function(value, element) {
  22798. assertNotHasOwnProperty(value, '"option value"');
  22799. optionsMap[value] = true;
  22800. if (ngModelCtrl.$viewValue == value) {
  22801. $element.val(value);
  22802. if (unknownOption.parent()) unknownOption.remove();
  22803. }
  22804. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  22805. // Adding an <option selected="selected"> element to a <select required="required"> should
  22806. // automatically select the new element
  22807. if (element && element[0].hasAttribute('selected')) {
  22808. element[0].selected = true;
  22809. }
  22810. };
  22811. self.removeOption = function(value) {
  22812. if (this.hasOption(value)) {
  22813. delete optionsMap[value];
  22814. if (ngModelCtrl.$viewValue == value) {
  22815. this.renderUnknownOption(value);
  22816. }
  22817. }
  22818. };
  22819. self.renderUnknownOption = function(val) {
  22820. var unknownVal = '? ' + hashKey(val) + ' ?';
  22821. unknownOption.val(unknownVal);
  22822. $element.prepend(unknownOption);
  22823. $element.val(unknownVal);
  22824. unknownOption.prop('selected', true); // needed for IE
  22825. };
  22826. self.hasOption = function(value) {
  22827. return optionsMap.hasOwnProperty(value);
  22828. };
  22829. $scope.$on('$destroy', function() {
  22830. // disable unknown option so that we don't do work when the whole select is being destroyed
  22831. self.renderUnknownOption = noop;
  22832. });
  22833. }],
  22834. link: function(scope, element, attr, ctrls) {
  22835. // if ngModel is not defined, we don't need to do anything
  22836. if (!ctrls[1]) return;
  22837. var selectCtrl = ctrls[0],
  22838. ngModelCtrl = ctrls[1],
  22839. multiple = attr.multiple,
  22840. optionsExp = attr.ngOptions,
  22841. nullOption = false, // if false, user will not be able to select it (used by ngOptions)
  22842. emptyOption,
  22843. renderScheduled = false,
  22844. // we can't just jqLite('<option>') since jqLite is not smart enough
  22845. // to create it in <select> and IE barfs otherwise.
  22846. optionTemplate = jqLite(document.createElement('option')),
  22847. optGroupTemplate =jqLite(document.createElement('optgroup')),
  22848. unknownOption = optionTemplate.clone();
  22849. // find "null" option
  22850. for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
  22851. if (children[i].value === '') {
  22852. emptyOption = nullOption = children.eq(i);
  22853. break;
  22854. }
  22855. }
  22856. selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
  22857. // required validator
  22858. if (multiple) {
  22859. ngModelCtrl.$isEmpty = function(value) {
  22860. return !value || value.length === 0;
  22861. };
  22862. }
  22863. if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
  22864. else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
  22865. else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
  22866. ////////////////////////////
  22867. function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
  22868. ngModelCtrl.$render = function() {
  22869. var viewValue = ngModelCtrl.$viewValue;
  22870. if (selectCtrl.hasOption(viewValue)) {
  22871. if (unknownOption.parent()) unknownOption.remove();
  22872. selectElement.val(viewValue);
  22873. if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
  22874. } else {
  22875. if (isUndefined(viewValue) && emptyOption) {
  22876. selectElement.val('');
  22877. } else {
  22878. selectCtrl.renderUnknownOption(viewValue);
  22879. }
  22880. }
  22881. };
  22882. selectElement.on('change', function() {
  22883. scope.$apply(function() {
  22884. if (unknownOption.parent()) unknownOption.remove();
  22885. ngModelCtrl.$setViewValue(selectElement.val());
  22886. });
  22887. });
  22888. }
  22889. function setupAsMultiple(scope, selectElement, ctrl) {
  22890. var lastView;
  22891. ctrl.$render = function() {
  22892. var items = new HashMap(ctrl.$viewValue);
  22893. forEach(selectElement.find('option'), function(option) {
  22894. option.selected = isDefined(items.get(option.value));
  22895. });
  22896. };
  22897. // we have to do it on each watch since ngModel watches reference, but
  22898. // we need to work of an array, so we need to see if anything was inserted/removed
  22899. scope.$watch(function selectMultipleWatch() {
  22900. if (!equals(lastView, ctrl.$viewValue)) {
  22901. lastView = shallowCopy(ctrl.$viewValue);
  22902. ctrl.$render();
  22903. }
  22904. });
  22905. selectElement.on('change', function() {
  22906. scope.$apply(function() {
  22907. var array = [];
  22908. forEach(selectElement.find('option'), function(option) {
  22909. if (option.selected) {
  22910. array.push(option.value);
  22911. }
  22912. });
  22913. ctrl.$setViewValue(array);
  22914. });
  22915. });
  22916. }
  22917. function setupAsOptions(scope, selectElement, ctrl) {
  22918. var match;
  22919. if (!(match = optionsExp.match(NG_OPTIONS_REGEXP))) {
  22920. throw ngOptionsMinErr('iexp',
  22921. "Expected expression in form of " +
  22922. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  22923. " but got '{0}'. Element: {1}",
  22924. optionsExp, startingTag(selectElement));
  22925. }
  22926. var displayFn = $parse(match[2] || match[1]),
  22927. valueName = match[4] || match[6],
  22928. selectAs = / as /.test(match[0]) && match[1],
  22929. selectAsFn = selectAs ? $parse(selectAs) : null,
  22930. keyName = match[5],
  22931. groupByFn = $parse(match[3] || ''),
  22932. valueFn = $parse(match[2] ? match[1] : valueName),
  22933. valuesFn = $parse(match[7]),
  22934. track = match[8],
  22935. trackFn = track ? $parse(match[8]) : null,
  22936. // This is an array of array of existing option groups in DOM.
  22937. // We try to reuse these if possible
  22938. // - optionGroupsCache[0] is the options with no option group
  22939. // - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
  22940. optionGroupsCache = [[{element: selectElement, label:''}]],
  22941. //re-usable object to represent option's locals
  22942. locals = {};
  22943. if (nullOption) {
  22944. // compile the element since there might be bindings in it
  22945. $compile(nullOption)(scope);
  22946. // remove the class, which is added automatically because we recompile the element and it
  22947. // becomes the compilation root
  22948. nullOption.removeClass('ng-scope');
  22949. // we need to remove it before calling selectElement.empty() because otherwise IE will
  22950. // remove the label from the element. wtf?
  22951. nullOption.remove();
  22952. }
  22953. // clear contents, we'll add what's needed based on the model
  22954. selectElement.empty();
  22955. selectElement.on('change', selectionChanged);
  22956. ctrl.$render = render;
  22957. scope.$watchCollection(valuesFn, scheduleRendering);
  22958. scope.$watchCollection(getLabels, scheduleRendering);
  22959. if (multiple) {
  22960. scope.$watchCollection(function() { return ctrl.$modelValue; }, scheduleRendering);
  22961. }
  22962. // ------------------------------------------------------------------ //
  22963. function callExpression(exprFn, key, value) {
  22964. locals[valueName] = value;
  22965. if (keyName) locals[keyName] = key;
  22966. return exprFn(scope, locals);
  22967. }
  22968. function selectionChanged() {
  22969. scope.$apply(function() {
  22970. var optionGroup,
  22971. collection = valuesFn(scope) || [],
  22972. key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
  22973. var viewValue;
  22974. if (multiple) {
  22975. viewValue = [];
  22976. forEach(selectElement.val(), function(selectedKey) {
  22977. viewValue.push(getViewValue(selectedKey, collection[selectedKey]));
  22978. });
  22979. } else {
  22980. var selectedKey = selectElement.val();
  22981. viewValue = getViewValue(selectedKey, collection[selectedKey]);
  22982. }
  22983. ctrl.$setViewValue(viewValue);
  22984. render();
  22985. });
  22986. }
  22987. function getViewValue(key, value) {
  22988. if (key === '?') {
  22989. return undefined;
  22990. } else if (key === '') {
  22991. return null;
  22992. } else {
  22993. var viewValueFn = selectAsFn ? selectAsFn : valueFn;
  22994. return callExpression(viewValueFn, key, value);
  22995. }
  22996. }
  22997. function getLabels() {
  22998. var values = valuesFn(scope);
  22999. var toDisplay;
  23000. if (values && isArray(values)) {
  23001. toDisplay = new Array(values.length);
  23002. for (var i = 0, ii = values.length; i < ii; i++) {
  23003. toDisplay[i] = callExpression(displayFn, i, values[i]);
  23004. }
  23005. return toDisplay;
  23006. } else if (values) {
  23007. // TODO: Add a test for this case
  23008. toDisplay = {};
  23009. for (var prop in values) {
  23010. if (values.hasOwnProperty(prop)) {
  23011. toDisplay[prop] = callExpression(displayFn, prop, values[prop]);
  23012. }
  23013. }
  23014. }
  23015. return toDisplay;
  23016. }
  23017. function createIsSelectedFn(viewValue) {
  23018. var selectedSet;
  23019. if (multiple) {
  23020. if (trackFn && isArray(viewValue)) {
  23021. selectedSet = new HashMap([]);
  23022. for (var trackIndex = 0; trackIndex < viewValue.length; trackIndex++) {
  23023. // tracking by key
  23024. selectedSet.put(callExpression(trackFn, null, viewValue[trackIndex]), true);
  23025. }
  23026. } else {
  23027. selectedSet = new HashMap(viewValue);
  23028. }
  23029. } else if (trackFn) {
  23030. viewValue = callExpression(trackFn, null, viewValue);
  23031. }
  23032. return function isSelected(key, value) {
  23033. var compareValueFn;
  23034. if (trackFn) {
  23035. compareValueFn = trackFn;
  23036. } else if (selectAsFn) {
  23037. compareValueFn = selectAsFn;
  23038. } else {
  23039. compareValueFn = valueFn;
  23040. }
  23041. if (multiple) {
  23042. return isDefined(selectedSet.remove(callExpression(compareValueFn, key, value)));
  23043. } else {
  23044. return viewValue == callExpression(compareValueFn, key, value);
  23045. }
  23046. };
  23047. }
  23048. function scheduleRendering() {
  23049. if (!renderScheduled) {
  23050. scope.$$postDigest(render);
  23051. renderScheduled = true;
  23052. }
  23053. }
  23054. /**
  23055. * A new labelMap is created with each render.
  23056. * This function is called for each existing option with added=false,
  23057. * and each new option with added=true.
  23058. * - Labels that are passed to this method twice,
  23059. * (once with added=true and once with added=false) will end up with a value of 0, and
  23060. * will cause no change to happen to the corresponding option.
  23061. * - Labels that are passed to this method only once with added=false will end up with a
  23062. * value of -1 and will eventually be passed to selectCtrl.removeOption()
  23063. * - Labels that are passed to this method only once with added=true will end up with a
  23064. * value of 1 and will eventually be passed to selectCtrl.addOption()
  23065. */
  23066. function updateLabelMap(labelMap, label, added) {
  23067. labelMap[label] = labelMap[label] || 0;
  23068. labelMap[label] += (added ? 1 : -1);
  23069. }
  23070. function render() {
  23071. renderScheduled = false;
  23072. // Temporary location for the option groups before we render them
  23073. var optionGroups = {'':[]},
  23074. optionGroupNames = [''],
  23075. optionGroupName,
  23076. optionGroup,
  23077. option,
  23078. existingParent, existingOptions, existingOption,
  23079. viewValue = ctrl.$viewValue,
  23080. values = valuesFn(scope) || [],
  23081. keys = keyName ? sortedKeys(values) : values,
  23082. key,
  23083. value,
  23084. groupLength, length,
  23085. groupIndex, index,
  23086. labelMap = {},
  23087. selected,
  23088. isSelected = createIsSelectedFn(viewValue),
  23089. anySelected = false,
  23090. lastElement,
  23091. element,
  23092. label;
  23093. // We now build up the list of options we need (we merge later)
  23094. for (index = 0; length = keys.length, index < length; index++) {
  23095. key = index;
  23096. if (keyName) {
  23097. key = keys[index];
  23098. if ( key.charAt(0) === '$' ) continue;
  23099. }
  23100. value = values[key];
  23101. optionGroupName = callExpression(groupByFn, key, value) || '';
  23102. if (!(optionGroup = optionGroups[optionGroupName])) {
  23103. optionGroup = optionGroups[optionGroupName] = [];
  23104. optionGroupNames.push(optionGroupName);
  23105. }
  23106. selected = isSelected(key, value);
  23107. anySelected = anySelected || selected;
  23108. label = callExpression(displayFn, key, value); // what will be seen by the user
  23109. // doing displayFn(scope, locals) || '' overwrites zero values
  23110. label = isDefined(label) ? label : '';
  23111. optionGroup.push({
  23112. // either the index into array or key from object
  23113. id: (keyName ? keys[index] : index),
  23114. label: label,
  23115. selected: selected // determine if we should be selected
  23116. });
  23117. }
  23118. if (!multiple) {
  23119. if (nullOption || viewValue === null) {
  23120. // insert null option if we have a placeholder, or the model is null
  23121. optionGroups[''].unshift({id:'', label:'', selected:!anySelected});
  23122. } else if (!anySelected) {
  23123. // option could not be found, we have to insert the undefined item
  23124. optionGroups[''].unshift({id:'?', label:'', selected:true});
  23125. }
  23126. }
  23127. // Now we need to update the list of DOM nodes to match the optionGroups we computed above
  23128. for (groupIndex = 0, groupLength = optionGroupNames.length;
  23129. groupIndex < groupLength;
  23130. groupIndex++) {
  23131. // current option group name or '' if no group
  23132. optionGroupName = optionGroupNames[groupIndex];
  23133. // list of options for that group. (first item has the parent)
  23134. optionGroup = optionGroups[optionGroupName];
  23135. if (optionGroupsCache.length <= groupIndex) {
  23136. // we need to grow the optionGroups
  23137. existingParent = {
  23138. element: optGroupTemplate.clone().attr('label', optionGroupName),
  23139. label: optionGroup.label
  23140. };
  23141. existingOptions = [existingParent];
  23142. optionGroupsCache.push(existingOptions);
  23143. selectElement.append(existingParent.element);
  23144. } else {
  23145. existingOptions = optionGroupsCache[groupIndex];
  23146. existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
  23147. // update the OPTGROUP label if not the same.
  23148. if (existingParent.label != optionGroupName) {
  23149. existingParent.element.attr('label', existingParent.label = optionGroupName);
  23150. }
  23151. }
  23152. lastElement = null; // start at the beginning
  23153. for(index = 0, length = optionGroup.length; index < length; index++) {
  23154. option = optionGroup[index];
  23155. if ((existingOption = existingOptions[index+1])) {
  23156. // reuse elements
  23157. lastElement = existingOption.element;
  23158. if (existingOption.label !== option.label) {
  23159. updateLabelMap(labelMap, existingOption.label, false);
  23160. updateLabelMap(labelMap, option.label, true);
  23161. lastElement.text(existingOption.label = option.label);
  23162. }
  23163. if (existingOption.id !== option.id) {
  23164. lastElement.val(existingOption.id = option.id);
  23165. }
  23166. // lastElement.prop('selected') provided by jQuery has side-effects
  23167. if (lastElement[0].selected !== option.selected) {
  23168. lastElement.prop('selected', (existingOption.selected = option.selected));
  23169. if (msie) {
  23170. // See #7692
  23171. // The selected item wouldn't visually update on IE without this.
  23172. // Tested on Win7: IE9, IE10 and IE11. Future IEs should be tested as well
  23173. lastElement.prop('selected', existingOption.selected);
  23174. }
  23175. }
  23176. } else {
  23177. // grow elements
  23178. // if it's a null option
  23179. if (option.id === '' && nullOption) {
  23180. // put back the pre-compiled element
  23181. element = nullOption;
  23182. } else {
  23183. // jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
  23184. // in this version of jQuery on some browser the .text() returns a string
  23185. // rather then the element.
  23186. (element = optionTemplate.clone())
  23187. .val(option.id)
  23188. .prop('selected', option.selected)
  23189. .attr('selected', option.selected)
  23190. .text(option.label);
  23191. }
  23192. existingOptions.push(existingOption = {
  23193. element: element,
  23194. label: option.label,
  23195. id: option.id,
  23196. selected: option.selected
  23197. });
  23198. updateLabelMap(labelMap, option.label, true);
  23199. if (lastElement) {
  23200. lastElement.after(element);
  23201. } else {
  23202. existingParent.element.append(element);
  23203. }
  23204. lastElement = element;
  23205. }
  23206. }
  23207. // remove any excessive OPTIONs in a group
  23208. index++; // increment since the existingOptions[0] is parent element not OPTION
  23209. while(existingOptions.length > index) {
  23210. option = existingOptions.pop();
  23211. updateLabelMap(labelMap, option.label, false);
  23212. option.element.remove();
  23213. }
  23214. forEach(labelMap, function (count, label) {
  23215. if (count > 0) {
  23216. selectCtrl.addOption(label);
  23217. } else if (count < 0) {
  23218. selectCtrl.removeOption(label);
  23219. }
  23220. });
  23221. }
  23222. // remove any excessive OPTGROUPs from select
  23223. while(optionGroupsCache.length > groupIndex) {
  23224. optionGroupsCache.pop()[0].element.remove();
  23225. }
  23226. }
  23227. }
  23228. }
  23229. };
  23230. }];
  23231. var optionDirective = ['$interpolate', function($interpolate) {
  23232. var nullSelectCtrl = {
  23233. addOption: noop,
  23234. removeOption: noop
  23235. };
  23236. return {
  23237. restrict: 'E',
  23238. priority: 100,
  23239. compile: function(element, attr) {
  23240. if (isUndefined(attr.value)) {
  23241. var interpolateFn = $interpolate(element.text(), true);
  23242. if (!interpolateFn) {
  23243. attr.$set('value', element.text());
  23244. }
  23245. }
  23246. return function (scope, element, attr) {
  23247. var selectCtrlName = '$selectController',
  23248. parent = element.parent(),
  23249. selectCtrl = parent.data(selectCtrlName) ||
  23250. parent.parent().data(selectCtrlName); // in case we are in optgroup
  23251. if (!selectCtrl || !selectCtrl.databound) {
  23252. selectCtrl = nullSelectCtrl;
  23253. }
  23254. if (interpolateFn) {
  23255. scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
  23256. attr.$set('value', newVal);
  23257. if (oldVal !== newVal) {
  23258. selectCtrl.removeOption(oldVal);
  23259. }
  23260. selectCtrl.addOption(newVal, element);
  23261. });
  23262. } else {
  23263. selectCtrl.addOption(attr.value, element);
  23264. }
  23265. element.on('$destroy', function() {
  23266. selectCtrl.removeOption(attr.value);
  23267. });
  23268. };
  23269. }
  23270. };
  23271. }];
  23272. var styleDirective = valueFn({
  23273. restrict: 'E',
  23274. terminal: false
  23275. });
  23276. if (window.angular.bootstrap) {
  23277. //AngularJS is already loaded, so we can return here...
  23278. console.log('WARNING: Tried to load angular more than once.');
  23279. return;
  23280. }
  23281. //try to bind to jquery now so that one can write jqLite(document).ready()
  23282. //but we will rebind on bootstrap again.
  23283. bindJQuery();
  23284. publishExternalAPI(angular);
  23285. jqLite(document).ready(function() {
  23286. angularInit(document, bootstrap);
  23287. });
  23288. })(window, document);
  23289. !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:not(.ng-hide-animate){display:none !important;}ng\\:form{display:block;}</style>');