angular.js 1.0MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018
  1. /**
  2. * @license AngularJS v1.4.8
  3. * (c) 2010-2015 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 SKIP_INDEXES = 2;
  40. var templateArgs = arguments,
  41. code = templateArgs[0],
  42. message = '[' + (module ? module + ':' : '') + code + '] ',
  43. template = templateArgs[1],
  44. paramPrefix, i;
  45. message += template.replace(/\{\d+\}/g, function(match) {
  46. var index = +match.slice(1, -1),
  47. shiftedIndex = index + SKIP_INDEXES;
  48. if (shiftedIndex < templateArgs.length) {
  49. return toDebugString(templateArgs[shiftedIndex]);
  50. }
  51. return match;
  52. });
  53. message += '\nhttp://errors.angularjs.org/1.4.8/' +
  54. (module ? module + '/' : '') + code;
  55. for (i = SKIP_INDEXES, paramPrefix = '?'; i < templateArgs.length; i++, paramPrefix = '&') {
  56. message += paramPrefix + 'p' + (i - SKIP_INDEXES) + '=' +
  57. encodeURIComponent(toDebugString(templateArgs[i]));
  58. }
  59. return new ErrorConstructor(message);
  60. };
  61. }
  62. /* We need to tell jshint what variables are being exported */
  63. /* global angular: true,
  64. msie: true,
  65. jqLite: true,
  66. jQuery: true,
  67. slice: true,
  68. splice: true,
  69. push: true,
  70. toString: true,
  71. ngMinErr: true,
  72. angularModule: true,
  73. uid: true,
  74. REGEX_STRING_REGEXP: true,
  75. VALIDITY_STATE_PROPERTY: true,
  76. lowercase: true,
  77. uppercase: true,
  78. manualLowercase: true,
  79. manualUppercase: true,
  80. nodeName_: true,
  81. isArrayLike: true,
  82. forEach: true,
  83. forEachSorted: true,
  84. reverseParams: true,
  85. nextUid: true,
  86. setHashKey: true,
  87. extend: true,
  88. toInt: true,
  89. inherit: true,
  90. merge: true,
  91. noop: true,
  92. identity: true,
  93. valueFn: true,
  94. isUndefined: true,
  95. isDefined: true,
  96. isObject: true,
  97. isBlankObject: true,
  98. isString: true,
  99. isNumber: true,
  100. isDate: true,
  101. isArray: true,
  102. isFunction: true,
  103. isRegExp: true,
  104. isWindow: true,
  105. isScope: true,
  106. isFile: true,
  107. isFormData: true,
  108. isBlob: true,
  109. isBoolean: true,
  110. isPromiseLike: true,
  111. trim: true,
  112. escapeForRegexp: true,
  113. isElement: true,
  114. makeMap: true,
  115. includes: true,
  116. arrayRemove: true,
  117. copy: true,
  118. shallowCopy: true,
  119. equals: true,
  120. csp: true,
  121. jq: true,
  122. concat: true,
  123. sliceArgs: true,
  124. bind: true,
  125. toJsonReplacer: true,
  126. toJson: true,
  127. fromJson: true,
  128. convertTimezoneToLocal: true,
  129. timezoneToOffset: true,
  130. startingTag: true,
  131. tryDecodeURIComponent: true,
  132. parseKeyValue: true,
  133. toKeyValue: true,
  134. encodeUriSegment: true,
  135. encodeUriQuery: true,
  136. angularInit: true,
  137. bootstrap: true,
  138. getTestability: true,
  139. snake_case: true,
  140. bindJQuery: true,
  141. assertArg: true,
  142. assertArgFn: true,
  143. assertNotHasOwnProperty: true,
  144. getter: true,
  145. getBlockNodes: true,
  146. hasOwnProperty: true,
  147. createMap: true,
  148. NODE_TYPE_ELEMENT: true,
  149. NODE_TYPE_ATTRIBUTE: true,
  150. NODE_TYPE_TEXT: true,
  151. NODE_TYPE_COMMENT: true,
  152. NODE_TYPE_DOCUMENT: true,
  153. NODE_TYPE_DOCUMENT_FRAGMENT: true,
  154. */
  155. ////////////////////////////////////
  156. /**
  157. * @ngdoc module
  158. * @name ng
  159. * @module ng
  160. * @description
  161. *
  162. * # ng (core module)
  163. * The ng module is loaded by default when an AngularJS application is started. The module itself
  164. * contains the essential components for an AngularJS application to function. The table below
  165. * lists a high level breakdown of each of the services/factories, filters, directives and testing
  166. * components available within this core module.
  167. *
  168. * <div doc-module-components="ng"></div>
  169. */
  170. var REGEX_STRING_REGEXP = /^\/(.+)\/([a-z]*)$/;
  171. // The name of a form control's ValidityState property.
  172. // This is used so that it's possible for internal tests to create mock ValidityStates.
  173. var VALIDITY_STATE_PROPERTY = 'validity';
  174. /**
  175. * @ngdoc function
  176. * @name angular.lowercase
  177. * @module ng
  178. * @kind function
  179. *
  180. * @description Converts the specified string to lowercase.
  181. * @param {string} string String to be converted to lowercase.
  182. * @returns {string} Lowercased string.
  183. */
  184. var lowercase = function(string) {return isString(string) ? string.toLowerCase() : string;};
  185. var hasOwnProperty = Object.prototype.hasOwnProperty;
  186. /**
  187. * @ngdoc function
  188. * @name angular.uppercase
  189. * @module ng
  190. * @kind function
  191. *
  192. * @description Converts the specified string to uppercase.
  193. * @param {string} string String to be converted to uppercase.
  194. * @returns {string} Uppercased string.
  195. */
  196. var uppercase = function(string) {return isString(string) ? string.toUpperCase() : string;};
  197. var manualLowercase = function(s) {
  198. /* jshint bitwise: false */
  199. return isString(s)
  200. ? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
  201. : s;
  202. };
  203. var manualUppercase = function(s) {
  204. /* jshint bitwise: false */
  205. return isString(s)
  206. ? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
  207. : s;
  208. };
  209. // String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
  210. // locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
  211. // with correct but slower alternatives.
  212. if ('i' !== 'I'.toLowerCase()) {
  213. lowercase = manualLowercase;
  214. uppercase = manualUppercase;
  215. }
  216. var
  217. msie, // holds major version number for IE, or NaN if UA is not IE.
  218. jqLite, // delay binding since jQuery could be loaded after us.
  219. jQuery, // delay binding
  220. slice = [].slice,
  221. splice = [].splice,
  222. push = [].push,
  223. toString = Object.prototype.toString,
  224. getPrototypeOf = Object.getPrototypeOf,
  225. ngMinErr = minErr('ng'),
  226. /** @name angular */
  227. angular = window.angular || (window.angular = {}),
  228. angularModule,
  229. uid = 0;
  230. /**
  231. * documentMode is an IE-only property
  232. * http://msdn.microsoft.com/en-us/library/ie/cc196988(v=vs.85).aspx
  233. */
  234. msie = document.documentMode;
  235. /**
  236. * @private
  237. * @param {*} obj
  238. * @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
  239. * String ...)
  240. */
  241. function isArrayLike(obj) {
  242. // `null`, `undefined` and `window` are not array-like
  243. if (obj == null || isWindow(obj)) return false;
  244. // arrays, strings and jQuery/jqLite objects are array like
  245. // * jqLite is either the jQuery or jqLite constructor function
  246. // * we have to check the existance of jqLite first as this method is called
  247. // via the forEach method when constructing the jqLite object in the first place
  248. if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
  249. // Support: iOS 8.2 (not reproducible in simulator)
  250. // "length" in obj used to prevent JIT error (gh-11508)
  251. var length = "length" in Object(obj) && obj.length;
  252. // NodeList objects (with `item` method) and
  253. // other objects with suitable length characteristics are array-like
  254. return isNumber(length) &&
  255. (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
  256. }
  257. /**
  258. * @ngdoc function
  259. * @name angular.forEach
  260. * @module ng
  261. * @kind function
  262. *
  263. * @description
  264. * Invokes the `iterator` function once for each item in `obj` collection, which can be either an
  265. * object or an array. The `iterator` function is invoked with `iterator(value, key, obj)`, where `value`
  266. * is the value of an object property or an array element, `key` is the object property key or
  267. * array element index and obj is the `obj` itself. Specifying a `context` for the function is optional.
  268. *
  269. * It is worth noting that `.forEach` does not iterate over inherited properties because it filters
  270. * using the `hasOwnProperty` method.
  271. *
  272. * Unlike ES262's
  273. * [Array.prototype.forEach](http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18),
  274. * Providing 'undefined' or 'null' values for `obj` will not throw a TypeError, but rather just
  275. * return the value provided.
  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 if (isBlankObject(obj)) {
  312. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  313. for (key in obj) {
  314. iterator.call(context, obj[key], key, obj);
  315. }
  316. } else if (typeof obj.hasOwnProperty === 'function') {
  317. // Slow path for objects inheriting Object.prototype, hasOwnProperty check needed
  318. for (key in obj) {
  319. if (obj.hasOwnProperty(key)) {
  320. iterator.call(context, obj[key], key, obj);
  321. }
  322. }
  323. } else {
  324. // Slow path for objects which do not have a method `hasOwnProperty`
  325. for (key in obj) {
  326. if (hasOwnProperty.call(obj, key)) {
  327. iterator.call(context, obj[key], key, obj);
  328. }
  329. }
  330. }
  331. }
  332. return obj;
  333. }
  334. function forEachSorted(obj, iterator, context) {
  335. var keys = Object.keys(obj).sort();
  336. for (var i = 0; i < keys.length; i++) {
  337. iterator.call(context, obj[keys[i]], keys[i]);
  338. }
  339. return keys;
  340. }
  341. /**
  342. * when using forEach the params are value, key, but it is often useful to have key, value.
  343. * @param {function(string, *)} iteratorFn
  344. * @returns {function(*, string)}
  345. */
  346. function reverseParams(iteratorFn) {
  347. return function(value, key) { iteratorFn(key, value); };
  348. }
  349. /**
  350. * A consistent way of creating unique IDs in angular.
  351. *
  352. * Using simple numbers allows us to generate 28.6 million unique ids per second for 10 years before
  353. * we hit number precision issues in JavaScript.
  354. *
  355. * Math.pow(2,53) / 60 / 60 / 24 / 365 / 10 = 28.6M
  356. *
  357. * @returns {number} an unique alpha-numeric string
  358. */
  359. function nextUid() {
  360. return ++uid;
  361. }
  362. /**
  363. * Set or clear the hashkey for an object.
  364. * @param obj object
  365. * @param h the hashkey (!truthy to delete the hashkey)
  366. */
  367. function setHashKey(obj, h) {
  368. if (h) {
  369. obj.$$hashKey = h;
  370. } else {
  371. delete obj.$$hashKey;
  372. }
  373. }
  374. function baseExtend(dst, objs, deep) {
  375. var h = dst.$$hashKey;
  376. for (var i = 0, ii = objs.length; i < ii; ++i) {
  377. var obj = objs[i];
  378. if (!isObject(obj) && !isFunction(obj)) continue;
  379. var keys = Object.keys(obj);
  380. for (var j = 0, jj = keys.length; j < jj; j++) {
  381. var key = keys[j];
  382. var src = obj[key];
  383. if (deep && isObject(src)) {
  384. if (isDate(src)) {
  385. dst[key] = new Date(src.valueOf());
  386. } else if (isRegExp(src)) {
  387. dst[key] = new RegExp(src);
  388. } else if (src.nodeName) {
  389. dst[key] = src.cloneNode(true);
  390. } else if (isElement(src)) {
  391. dst[key] = src.clone();
  392. } else {
  393. if (!isObject(dst[key])) dst[key] = isArray(src) ? [] : {};
  394. baseExtend(dst[key], [src], true);
  395. }
  396. } else {
  397. dst[key] = src;
  398. }
  399. }
  400. }
  401. setHashKey(dst, h);
  402. return dst;
  403. }
  404. /**
  405. * @ngdoc function
  406. * @name angular.extend
  407. * @module ng
  408. * @kind function
  409. *
  410. * @description
  411. * Extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  412. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  413. * by passing an empty object as the target: `var object = angular.extend({}, object1, object2)`.
  414. *
  415. * **Note:** Keep in mind that `angular.extend` does not support recursive merge (deep copy). Use
  416. * {@link angular.merge} for this.
  417. *
  418. * @param {Object} dst Destination object.
  419. * @param {...Object} src Source object(s).
  420. * @returns {Object} Reference to `dst`.
  421. */
  422. function extend(dst) {
  423. return baseExtend(dst, slice.call(arguments, 1), false);
  424. }
  425. /**
  426. * @ngdoc function
  427. * @name angular.merge
  428. * @module ng
  429. * @kind function
  430. *
  431. * @description
  432. * Deeply extends the destination object `dst` by copying own enumerable properties from the `src` object(s)
  433. * to `dst`. You can specify multiple `src` objects. If you want to preserve original objects, you can do so
  434. * by passing an empty object as the target: `var object = angular.merge({}, object1, object2)`.
  435. *
  436. * Unlike {@link angular.extend extend()}, `merge()` recursively descends into object properties of source
  437. * objects, performing a deep copy.
  438. *
  439. * @param {Object} dst Destination object.
  440. * @param {...Object} src Source object(s).
  441. * @returns {Object} Reference to `dst`.
  442. */
  443. function merge(dst) {
  444. return baseExtend(dst, slice.call(arguments, 1), true);
  445. }
  446. function toInt(str) {
  447. return parseInt(str, 10);
  448. }
  449. function inherit(parent, extra) {
  450. return extend(Object.create(parent), extra);
  451. }
  452. /**
  453. * @ngdoc function
  454. * @name angular.noop
  455. * @module ng
  456. * @kind function
  457. *
  458. * @description
  459. * A function that performs no operations. This function can be useful when writing code in the
  460. * functional style.
  461. ```js
  462. function foo(callback) {
  463. var result = calculateResult();
  464. (callback || angular.noop)(result);
  465. }
  466. ```
  467. */
  468. function noop() {}
  469. noop.$inject = [];
  470. /**
  471. * @ngdoc function
  472. * @name angular.identity
  473. * @module ng
  474. * @kind function
  475. *
  476. * @description
  477. * A function that returns its first argument. This function is useful when writing code in the
  478. * functional style.
  479. *
  480. ```js
  481. function transformer(transformationFn, value) {
  482. return (transformationFn || angular.identity)(value);
  483. };
  484. ```
  485. * @param {*} value to be returned.
  486. * @returns {*} the value passed in.
  487. */
  488. function identity($) {return $;}
  489. identity.$inject = [];
  490. function valueFn(value) {return function() {return value;};}
  491. function hasCustomToString(obj) {
  492. return isFunction(obj.toString) && obj.toString !== toString;
  493. }
  494. /**
  495. * @ngdoc function
  496. * @name angular.isUndefined
  497. * @module ng
  498. * @kind function
  499. *
  500. * @description
  501. * Determines if a reference is undefined.
  502. *
  503. * @param {*} value Reference to check.
  504. * @returns {boolean} True if `value` is undefined.
  505. */
  506. function isUndefined(value) {return typeof value === 'undefined';}
  507. /**
  508. * @ngdoc function
  509. * @name angular.isDefined
  510. * @module ng
  511. * @kind function
  512. *
  513. * @description
  514. * Determines if a reference is defined.
  515. *
  516. * @param {*} value Reference to check.
  517. * @returns {boolean} True if `value` is defined.
  518. */
  519. function isDefined(value) {return typeof value !== 'undefined';}
  520. /**
  521. * @ngdoc function
  522. * @name angular.isObject
  523. * @module ng
  524. * @kind function
  525. *
  526. * @description
  527. * Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
  528. * considered to be objects. Note that JavaScript arrays are objects.
  529. *
  530. * @param {*} value Reference to check.
  531. * @returns {boolean} True if `value` is an `Object` but not `null`.
  532. */
  533. function isObject(value) {
  534. // http://jsperf.com/isobject4
  535. return value !== null && typeof value === 'object';
  536. }
  537. /**
  538. * Determine if a value is an object with a null prototype
  539. *
  540. * @returns {boolean} True if `value` is an `Object` with a null prototype
  541. */
  542. function isBlankObject(value) {
  543. return value !== null && typeof value === 'object' && !getPrototypeOf(value);
  544. }
  545. /**
  546. * @ngdoc function
  547. * @name angular.isString
  548. * @module ng
  549. * @kind function
  550. *
  551. * @description
  552. * Determines if a reference is a `String`.
  553. *
  554. * @param {*} value Reference to check.
  555. * @returns {boolean} True if `value` is a `String`.
  556. */
  557. function isString(value) {return typeof value === 'string';}
  558. /**
  559. * @ngdoc function
  560. * @name angular.isNumber
  561. * @module ng
  562. * @kind function
  563. *
  564. * @description
  565. * Determines if a reference is a `Number`.
  566. *
  567. * This includes the "special" numbers `NaN`, `+Infinity` and `-Infinity`.
  568. *
  569. * If you wish to exclude these then you can use the native
  570. * [`isFinite'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isFinite)
  571. * method.
  572. *
  573. * @param {*} value Reference to check.
  574. * @returns {boolean} True if `value` is a `Number`.
  575. */
  576. function isNumber(value) {return typeof value === 'number';}
  577. /**
  578. * @ngdoc function
  579. * @name angular.isDate
  580. * @module ng
  581. * @kind function
  582. *
  583. * @description
  584. * Determines if a value is a date.
  585. *
  586. * @param {*} value Reference to check.
  587. * @returns {boolean} True if `value` is a `Date`.
  588. */
  589. function isDate(value) {
  590. return toString.call(value) === '[object Date]';
  591. }
  592. /**
  593. * @ngdoc function
  594. * @name angular.isArray
  595. * @module ng
  596. * @kind function
  597. *
  598. * @description
  599. * Determines if a reference is an `Array`.
  600. *
  601. * @param {*} value Reference to check.
  602. * @returns {boolean} True if `value` is an `Array`.
  603. */
  604. var isArray = Array.isArray;
  605. /**
  606. * @ngdoc function
  607. * @name angular.isFunction
  608. * @module ng
  609. * @kind function
  610. *
  611. * @description
  612. * Determines if a reference is a `Function`.
  613. *
  614. * @param {*} value Reference to check.
  615. * @returns {boolean} True if `value` is a `Function`.
  616. */
  617. function isFunction(value) {return typeof value === 'function';}
  618. /**
  619. * Determines if a value is a regular expression object.
  620. *
  621. * @private
  622. * @param {*} value Reference to check.
  623. * @returns {boolean} True if `value` is a `RegExp`.
  624. */
  625. function isRegExp(value) {
  626. return toString.call(value) === '[object RegExp]';
  627. }
  628. /**
  629. * Checks if `obj` is a window object.
  630. *
  631. * @private
  632. * @param {*} obj Object to check
  633. * @returns {boolean} True if `obj` is a window obj.
  634. */
  635. function isWindow(obj) {
  636. return obj && obj.window === obj;
  637. }
  638. function isScope(obj) {
  639. return obj && obj.$evalAsync && obj.$watch;
  640. }
  641. function isFile(obj) {
  642. return toString.call(obj) === '[object File]';
  643. }
  644. function isFormData(obj) {
  645. return toString.call(obj) === '[object FormData]';
  646. }
  647. function isBlob(obj) {
  648. return toString.call(obj) === '[object Blob]';
  649. }
  650. function isBoolean(value) {
  651. return typeof value === 'boolean';
  652. }
  653. function isPromiseLike(obj) {
  654. return obj && isFunction(obj.then);
  655. }
  656. var TYPED_ARRAY_REGEXP = /^\[object (?:Uint8|Uint8Clamped|Uint16|Uint32|Int8|Int16|Int32|Float32|Float64)Array\]$/;
  657. function isTypedArray(value) {
  658. return value && isNumber(value.length) && TYPED_ARRAY_REGEXP.test(toString.call(value));
  659. }
  660. var trim = function(value) {
  661. return isString(value) ? value.trim() : value;
  662. };
  663. // Copied from:
  664. // http://docs.closure-library.googlecode.com/git/local_closure_goog_string_string.js.source.html#line1021
  665. // Prereq: s is a string.
  666. var escapeForRegexp = function(s) {
  667. return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
  668. replace(/\x08/g, '\\x08');
  669. };
  670. /**
  671. * @ngdoc function
  672. * @name angular.isElement
  673. * @module ng
  674. * @kind function
  675. *
  676. * @description
  677. * Determines if a reference is a DOM element (or wrapped jQuery element).
  678. *
  679. * @param {*} value Reference to check.
  680. * @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
  681. */
  682. function isElement(node) {
  683. return !!(node &&
  684. (node.nodeName // we are a direct element
  685. || (node.prop && node.attr && node.find))); // we have an on and find method part of jQuery API
  686. }
  687. /**
  688. * @param str 'key1,key2,...'
  689. * @returns {object} in the form of {key1:true, key2:true, ...}
  690. */
  691. function makeMap(str) {
  692. var obj = {}, items = str.split(","), i;
  693. for (i = 0; i < items.length; i++) {
  694. obj[items[i]] = true;
  695. }
  696. return obj;
  697. }
  698. function nodeName_(element) {
  699. return lowercase(element.nodeName || (element[0] && element[0].nodeName));
  700. }
  701. function includes(array, obj) {
  702. return Array.prototype.indexOf.call(array, obj) != -1;
  703. }
  704. function arrayRemove(array, value) {
  705. var index = array.indexOf(value);
  706. if (index >= 0) {
  707. array.splice(index, 1);
  708. }
  709. return index;
  710. }
  711. /**
  712. * @ngdoc function
  713. * @name angular.copy
  714. * @module ng
  715. * @kind function
  716. *
  717. * @description
  718. * Creates a deep copy of `source`, which should be an object or an array.
  719. *
  720. * * If no destination is supplied, a copy of the object or array is created.
  721. * * If a destination is provided, all of its elements (for arrays) or properties (for objects)
  722. * are deleted and then all elements/properties from the source are copied to it.
  723. * * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
  724. * * If `source` is identical to 'destination' an exception will be thrown.
  725. *
  726. * @param {*} source The source that will be used to make a copy.
  727. * Can be any type, including primitives, `null`, and `undefined`.
  728. * @param {(Object|Array)=} destination Destination into which the source is copied. If
  729. * provided, must be of the same type as `source`.
  730. * @returns {*} The copy or updated `destination`, if `destination` was specified.
  731. *
  732. * @example
  733. <example module="copyExample">
  734. <file name="index.html">
  735. <div ng-controller="ExampleController">
  736. <form novalidate class="simple-form">
  737. Name: <input type="text" ng-model="user.name" /><br />
  738. E-mail: <input type="email" ng-model="user.email" /><br />
  739. Gender: <input type="radio" ng-model="user.gender" value="male" />male
  740. <input type="radio" ng-model="user.gender" value="female" />female<br />
  741. <button ng-click="reset()">RESET</button>
  742. <button ng-click="update(user)">SAVE</button>
  743. </form>
  744. <pre>form = {{user | json}}</pre>
  745. <pre>master = {{master | json}}</pre>
  746. </div>
  747. <script>
  748. angular.module('copyExample', [])
  749. .controller('ExampleController', ['$scope', function($scope) {
  750. $scope.master= {};
  751. $scope.update = function(user) {
  752. // Example with 1 argument
  753. $scope.master= angular.copy(user);
  754. };
  755. $scope.reset = function() {
  756. // Example with 2 arguments
  757. angular.copy($scope.master, $scope.user);
  758. };
  759. $scope.reset();
  760. }]);
  761. </script>
  762. </file>
  763. </example>
  764. */
  765. function copy(source, destination) {
  766. var stackSource = [];
  767. var stackDest = [];
  768. if (destination) {
  769. if (isTypedArray(destination)) {
  770. throw ngMinErr('cpta', "Can't copy! TypedArray destination cannot be mutated.");
  771. }
  772. if (source === destination) {
  773. throw ngMinErr('cpi', "Can't copy! Source and destination are identical.");
  774. }
  775. // Empty the destination object
  776. if (isArray(destination)) {
  777. destination.length = 0;
  778. } else {
  779. forEach(destination, function(value, key) {
  780. if (key !== '$$hashKey') {
  781. delete destination[key];
  782. }
  783. });
  784. }
  785. stackSource.push(source);
  786. stackDest.push(destination);
  787. return copyRecurse(source, destination);
  788. }
  789. return copyElement(source);
  790. function copyRecurse(source, destination) {
  791. var h = destination.$$hashKey;
  792. var result, key;
  793. if (isArray(source)) {
  794. for (var i = 0, ii = source.length; i < ii; i++) {
  795. destination.push(copyElement(source[i]));
  796. }
  797. } else if (isBlankObject(source)) {
  798. // createMap() fast path --- Safe to avoid hasOwnProperty check because prototype chain is empty
  799. for (key in source) {
  800. destination[key] = copyElement(source[key]);
  801. }
  802. } else if (source && typeof source.hasOwnProperty === 'function') {
  803. // Slow path, which must rely on hasOwnProperty
  804. for (key in source) {
  805. if (source.hasOwnProperty(key)) {
  806. destination[key] = copyElement(source[key]);
  807. }
  808. }
  809. } else {
  810. // Slowest path --- hasOwnProperty can't be called as a method
  811. for (key in source) {
  812. if (hasOwnProperty.call(source, key)) {
  813. destination[key] = copyElement(source[key]);
  814. }
  815. }
  816. }
  817. setHashKey(destination, h);
  818. return destination;
  819. }
  820. function copyElement(source) {
  821. // Simple values
  822. if (!isObject(source)) {
  823. return source;
  824. }
  825. // Already copied values
  826. var index = stackSource.indexOf(source);
  827. if (index !== -1) {
  828. return stackDest[index];
  829. }
  830. if (isWindow(source) || isScope(source)) {
  831. throw ngMinErr('cpws',
  832. "Can't copy! Making copies of Window or Scope instances is not supported.");
  833. }
  834. var needsRecurse = false;
  835. var destination;
  836. if (isArray(source)) {
  837. destination = [];
  838. needsRecurse = true;
  839. } else if (isTypedArray(source)) {
  840. destination = new source.constructor(source);
  841. } else if (isDate(source)) {
  842. destination = new Date(source.getTime());
  843. } else if (isRegExp(source)) {
  844. destination = new RegExp(source.source, source.toString().match(/[^\/]*$/)[0]);
  845. destination.lastIndex = source.lastIndex;
  846. } else if (isFunction(source.cloneNode)) {
  847. destination = source.cloneNode(true);
  848. } else {
  849. destination = Object.create(getPrototypeOf(source));
  850. needsRecurse = true;
  851. }
  852. stackSource.push(source);
  853. stackDest.push(destination);
  854. return needsRecurse
  855. ? copyRecurse(source, destination)
  856. : destination;
  857. }
  858. }
  859. /**
  860. * Creates a shallow copy of an object, an array or a primitive.
  861. *
  862. * Assumes that there are no proto properties for objects.
  863. */
  864. function shallowCopy(src, dst) {
  865. if (isArray(src)) {
  866. dst = dst || [];
  867. for (var i = 0, ii = src.length; i < ii; i++) {
  868. dst[i] = src[i];
  869. }
  870. } else if (isObject(src)) {
  871. dst = dst || {};
  872. for (var key in src) {
  873. if (!(key.charAt(0) === '$' && key.charAt(1) === '$')) {
  874. dst[key] = src[key];
  875. }
  876. }
  877. }
  878. return dst || src;
  879. }
  880. /**
  881. * @ngdoc function
  882. * @name angular.equals
  883. * @module ng
  884. * @kind function
  885. *
  886. * @description
  887. * Determines if two objects or two values are equivalent. Supports value types, regular
  888. * expressions, arrays and objects.
  889. *
  890. * Two objects or values are considered equivalent if at least one of the following is true:
  891. *
  892. * * Both objects or values pass `===` comparison.
  893. * * Both objects or values are of the same type and all of their properties are equal by
  894. * comparing them with `angular.equals`.
  895. * * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
  896. * * Both values represent the same regular expression (In JavaScript,
  897. * /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
  898. * representation matches).
  899. *
  900. * During a property comparison, properties of `function` type and properties with names
  901. * that begin with `$` are ignored.
  902. *
  903. * Scope and DOMWindow objects are being compared only by identify (`===`).
  904. *
  905. * @param {*} o1 Object or value to compare.
  906. * @param {*} o2 Object or value to compare.
  907. * @returns {boolean} True if arguments are equal.
  908. */
  909. function equals(o1, o2) {
  910. if (o1 === o2) return true;
  911. if (o1 === null || o2 === null) return false;
  912. if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
  913. var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
  914. if (t1 == t2) {
  915. if (t1 == 'object') {
  916. if (isArray(o1)) {
  917. if (!isArray(o2)) return false;
  918. if ((length = o1.length) == o2.length) {
  919. for (key = 0; key < length; key++) {
  920. if (!equals(o1[key], o2[key])) return false;
  921. }
  922. return true;
  923. }
  924. } else if (isDate(o1)) {
  925. if (!isDate(o2)) return false;
  926. return equals(o1.getTime(), o2.getTime());
  927. } else if (isRegExp(o1)) {
  928. return isRegExp(o2) ? o1.toString() == o2.toString() : false;
  929. } else {
  930. if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) ||
  931. isArray(o2) || isDate(o2) || isRegExp(o2)) return false;
  932. keySet = createMap();
  933. for (key in o1) {
  934. if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
  935. if (!equals(o1[key], o2[key])) return false;
  936. keySet[key] = true;
  937. }
  938. for (key in o2) {
  939. if (!(key in keySet) &&
  940. key.charAt(0) !== '$' &&
  941. isDefined(o2[key]) &&
  942. !isFunction(o2[key])) return false;
  943. }
  944. return true;
  945. }
  946. }
  947. }
  948. return false;
  949. }
  950. var csp = function() {
  951. if (!isDefined(csp.rules)) {
  952. var ngCspElement = (document.querySelector('[ng-csp]') ||
  953. document.querySelector('[data-ng-csp]'));
  954. if (ngCspElement) {
  955. var ngCspAttribute = ngCspElement.getAttribute('ng-csp') ||
  956. ngCspElement.getAttribute('data-ng-csp');
  957. csp.rules = {
  958. noUnsafeEval: !ngCspAttribute || (ngCspAttribute.indexOf('no-unsafe-eval') !== -1),
  959. noInlineStyle: !ngCspAttribute || (ngCspAttribute.indexOf('no-inline-style') !== -1)
  960. };
  961. } else {
  962. csp.rules = {
  963. noUnsafeEval: noUnsafeEval(),
  964. noInlineStyle: false
  965. };
  966. }
  967. }
  968. return csp.rules;
  969. function noUnsafeEval() {
  970. try {
  971. /* jshint -W031, -W054 */
  972. new Function('');
  973. /* jshint +W031, +W054 */
  974. return false;
  975. } catch (e) {
  976. return true;
  977. }
  978. }
  979. };
  980. /**
  981. * @ngdoc directive
  982. * @module ng
  983. * @name ngJq
  984. *
  985. * @element ANY
  986. * @param {string=} ngJq the name of the library available under `window`
  987. * to be used for angular.element
  988. * @description
  989. * Use this directive to force the angular.element library. This should be
  990. * used to force either jqLite by leaving ng-jq blank or setting the name of
  991. * the jquery variable under window (eg. jQuery).
  992. *
  993. * Since angular looks for this directive when it is loaded (doesn't wait for the
  994. * DOMContentLoaded event), it must be placed on an element that comes before the script
  995. * which loads angular. Also, only the first instance of `ng-jq` will be used and all
  996. * others ignored.
  997. *
  998. * @example
  999. * This example shows how to force jqLite using the `ngJq` directive to the `html` tag.
  1000. ```html
  1001. <!doctype html>
  1002. <html ng-app ng-jq>
  1003. ...
  1004. ...
  1005. </html>
  1006. ```
  1007. * @example
  1008. * This example shows how to use a jQuery based library of a different name.
  1009. * The library name must be available at the top most 'window'.
  1010. ```html
  1011. <!doctype html>
  1012. <html ng-app ng-jq="jQueryLib">
  1013. ...
  1014. ...
  1015. </html>
  1016. ```
  1017. */
  1018. var jq = function() {
  1019. if (isDefined(jq.name_)) return jq.name_;
  1020. var el;
  1021. var i, ii = ngAttrPrefixes.length, prefix, name;
  1022. for (i = 0; i < ii; ++i) {
  1023. prefix = ngAttrPrefixes[i];
  1024. if (el = document.querySelector('[' + prefix.replace(':', '\\:') + 'jq]')) {
  1025. name = el.getAttribute(prefix + 'jq');
  1026. break;
  1027. }
  1028. }
  1029. return (jq.name_ = name);
  1030. };
  1031. function concat(array1, array2, index) {
  1032. return array1.concat(slice.call(array2, index));
  1033. }
  1034. function sliceArgs(args, startIndex) {
  1035. return slice.call(args, startIndex || 0);
  1036. }
  1037. /* jshint -W101 */
  1038. /**
  1039. * @ngdoc function
  1040. * @name angular.bind
  1041. * @module ng
  1042. * @kind function
  1043. *
  1044. * @description
  1045. * Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
  1046. * `fn`). You can supply optional `args` that are prebound to the function. This feature is also
  1047. * known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
  1048. * distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
  1049. *
  1050. * @param {Object} self Context which `fn` should be evaluated in.
  1051. * @param {function()} fn Function to be bound.
  1052. * @param {...*} args Optional arguments to be prebound to the `fn` function call.
  1053. * @returns {function()} Function that wraps the `fn` with all the specified bindings.
  1054. */
  1055. /* jshint +W101 */
  1056. function bind(self, fn) {
  1057. var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
  1058. if (isFunction(fn) && !(fn instanceof RegExp)) {
  1059. return curryArgs.length
  1060. ? function() {
  1061. return arguments.length
  1062. ? fn.apply(self, concat(curryArgs, arguments, 0))
  1063. : fn.apply(self, curryArgs);
  1064. }
  1065. : function() {
  1066. return arguments.length
  1067. ? fn.apply(self, arguments)
  1068. : fn.call(self);
  1069. };
  1070. } else {
  1071. // in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
  1072. return fn;
  1073. }
  1074. }
  1075. function toJsonReplacer(key, value) {
  1076. var val = value;
  1077. if (typeof key === 'string' && key.charAt(0) === '$' && key.charAt(1) === '$') {
  1078. val = undefined;
  1079. } else if (isWindow(value)) {
  1080. val = '$WINDOW';
  1081. } else if (value && document === value) {
  1082. val = '$DOCUMENT';
  1083. } else if (isScope(value)) {
  1084. val = '$SCOPE';
  1085. }
  1086. return val;
  1087. }
  1088. /**
  1089. * @ngdoc function
  1090. * @name angular.toJson
  1091. * @module ng
  1092. * @kind function
  1093. *
  1094. * @description
  1095. * Serializes input into a JSON-formatted string. Properties with leading $$ characters will be
  1096. * stripped since angular uses this notation internally.
  1097. *
  1098. * @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
  1099. * @param {boolean|number} [pretty=2] If set to true, the JSON output will contain newlines and whitespace.
  1100. * If set to an integer, the JSON output will contain that many spaces per indentation.
  1101. * @returns {string|undefined} JSON-ified string representing `obj`.
  1102. */
  1103. function toJson(obj, pretty) {
  1104. if (typeof obj === 'undefined') return undefined;
  1105. if (!isNumber(pretty)) {
  1106. pretty = pretty ? 2 : null;
  1107. }
  1108. return JSON.stringify(obj, toJsonReplacer, pretty);
  1109. }
  1110. /**
  1111. * @ngdoc function
  1112. * @name angular.fromJson
  1113. * @module ng
  1114. * @kind function
  1115. *
  1116. * @description
  1117. * Deserializes a JSON string.
  1118. *
  1119. * @param {string} json JSON string to deserialize.
  1120. * @returns {Object|Array|string|number} Deserialized JSON string.
  1121. */
  1122. function fromJson(json) {
  1123. return isString(json)
  1124. ? JSON.parse(json)
  1125. : json;
  1126. }
  1127. function timezoneToOffset(timezone, fallback) {
  1128. var requestedTimezoneOffset = Date.parse('Jan 01, 1970 00:00:00 ' + timezone) / 60000;
  1129. return isNaN(requestedTimezoneOffset) ? fallback : requestedTimezoneOffset;
  1130. }
  1131. function addDateMinutes(date, minutes) {
  1132. date = new Date(date.getTime());
  1133. date.setMinutes(date.getMinutes() + minutes);
  1134. return date;
  1135. }
  1136. function convertTimezoneToLocal(date, timezone, reverse) {
  1137. reverse = reverse ? -1 : 1;
  1138. var timezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  1139. return addDateMinutes(date, reverse * (timezoneOffset - date.getTimezoneOffset()));
  1140. }
  1141. /**
  1142. * @returns {string} Returns the string representation of the element.
  1143. */
  1144. function startingTag(element) {
  1145. element = jqLite(element).clone();
  1146. try {
  1147. // turns out IE does not let you set .html() on elements which
  1148. // are not allowed to have children. So we just ignore it.
  1149. element.empty();
  1150. } catch (e) {}
  1151. var elemHtml = jqLite('<div>').append(element).html();
  1152. try {
  1153. return element[0].nodeType === NODE_TYPE_TEXT ? lowercase(elemHtml) :
  1154. elemHtml.
  1155. match(/^(<[^>]+>)/)[1].
  1156. replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
  1157. } catch (e) {
  1158. return lowercase(elemHtml);
  1159. }
  1160. }
  1161. /////////////////////////////////////////////////
  1162. /**
  1163. * Tries to decode the URI component without throwing an exception.
  1164. *
  1165. * @private
  1166. * @param str value potential URI component to check.
  1167. * @returns {boolean} True if `value` can be decoded
  1168. * with the decodeURIComponent function.
  1169. */
  1170. function tryDecodeURIComponent(value) {
  1171. try {
  1172. return decodeURIComponent(value);
  1173. } catch (e) {
  1174. // Ignore any invalid uri component
  1175. }
  1176. }
  1177. /**
  1178. * Parses an escaped url query string into key-value pairs.
  1179. * @returns {Object.<string,boolean|Array>}
  1180. */
  1181. function parseKeyValue(/**string*/keyValue) {
  1182. var obj = {};
  1183. forEach((keyValue || "").split('&'), function(keyValue) {
  1184. var splitPoint, key, val;
  1185. if (keyValue) {
  1186. key = keyValue = keyValue.replace(/\+/g,'%20');
  1187. splitPoint = keyValue.indexOf('=');
  1188. if (splitPoint !== -1) {
  1189. key = keyValue.substring(0, splitPoint);
  1190. val = keyValue.substring(splitPoint + 1);
  1191. }
  1192. key = tryDecodeURIComponent(key);
  1193. if (isDefined(key)) {
  1194. val = isDefined(val) ? tryDecodeURIComponent(val) : true;
  1195. if (!hasOwnProperty.call(obj, key)) {
  1196. obj[key] = val;
  1197. } else if (isArray(obj[key])) {
  1198. obj[key].push(val);
  1199. } else {
  1200. obj[key] = [obj[key],val];
  1201. }
  1202. }
  1203. }
  1204. });
  1205. return obj;
  1206. }
  1207. function toKeyValue(obj) {
  1208. var parts = [];
  1209. forEach(obj, function(value, key) {
  1210. if (isArray(value)) {
  1211. forEach(value, function(arrayValue) {
  1212. parts.push(encodeUriQuery(key, true) +
  1213. (arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
  1214. });
  1215. } else {
  1216. parts.push(encodeUriQuery(key, true) +
  1217. (value === true ? '' : '=' + encodeUriQuery(value, true)));
  1218. }
  1219. });
  1220. return parts.length ? parts.join('&') : '';
  1221. }
  1222. /**
  1223. * We need our custom method because encodeURIComponent is too aggressive and doesn't follow
  1224. * http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
  1225. * segments:
  1226. * segment = *pchar
  1227. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1228. * pct-encoded = "%" HEXDIG HEXDIG
  1229. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1230. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1231. * / "*" / "+" / "," / ";" / "="
  1232. */
  1233. function encodeUriSegment(val) {
  1234. return encodeUriQuery(val, true).
  1235. replace(/%26/gi, '&').
  1236. replace(/%3D/gi, '=').
  1237. replace(/%2B/gi, '+');
  1238. }
  1239. /**
  1240. * This method is intended for encoding *key* or *value* parts of query component. We need a custom
  1241. * method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
  1242. * encoded per http://tools.ietf.org/html/rfc3986:
  1243. * query = *( pchar / "/" / "?" )
  1244. * pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
  1245. * unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
  1246. * pct-encoded = "%" HEXDIG HEXDIG
  1247. * sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
  1248. * / "*" / "+" / "," / ";" / "="
  1249. */
  1250. function encodeUriQuery(val, pctEncodeSpaces) {
  1251. return encodeURIComponent(val).
  1252. replace(/%40/gi, '@').
  1253. replace(/%3A/gi, ':').
  1254. replace(/%24/g, '$').
  1255. replace(/%2C/gi, ',').
  1256. replace(/%3B/gi, ';').
  1257. replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
  1258. }
  1259. var ngAttrPrefixes = ['ng-', 'data-ng-', 'ng:', 'x-ng-'];
  1260. function getNgAttribute(element, ngAttr) {
  1261. var attr, i, ii = ngAttrPrefixes.length;
  1262. for (i = 0; i < ii; ++i) {
  1263. attr = ngAttrPrefixes[i] + ngAttr;
  1264. if (isString(attr = element.getAttribute(attr))) {
  1265. return attr;
  1266. }
  1267. }
  1268. return null;
  1269. }
  1270. /**
  1271. * @ngdoc directive
  1272. * @name ngApp
  1273. * @module ng
  1274. *
  1275. * @element ANY
  1276. * @param {angular.Module} ngApp an optional application
  1277. * {@link angular.module module} name to load.
  1278. * @param {boolean=} ngStrictDi if this attribute is present on the app element, the injector will be
  1279. * created in "strict-di" mode. This means that the application will fail to invoke functions which
  1280. * do not use explicit function annotation (and are thus unsuitable for minification), as described
  1281. * in {@link guide/di the Dependency Injection guide}, and useful debugging info will assist in
  1282. * tracking down the root of these bugs.
  1283. *
  1284. * @description
  1285. *
  1286. * Use this directive to **auto-bootstrap** an AngularJS application. The `ngApp` directive
  1287. * designates the **root element** of the application and is typically placed near the root element
  1288. * of the page - e.g. on the `<body>` or `<html>` tags.
  1289. *
  1290. * Only one AngularJS application can be auto-bootstrapped per HTML document. The first `ngApp`
  1291. * found in the document will be used to define the root element to auto-bootstrap as an
  1292. * application. To run multiple applications in an HTML document you must manually bootstrap them using
  1293. * {@link angular.bootstrap} instead. AngularJS applications cannot be nested within each other.
  1294. *
  1295. * You can specify an **AngularJS module** to be used as the root module for the application. This
  1296. * module will be loaded into the {@link auto.$injector} when the application is bootstrapped. It
  1297. * should contain the application code needed or have dependencies on other modules that will
  1298. * contain the code. See {@link angular.module} for more information.
  1299. *
  1300. * In the example below if the `ngApp` directive were not placed on the `html` element then the
  1301. * document would not be compiled, the `AppController` would not be instantiated and the `{{ a+b }}`
  1302. * would not be resolved to `3`.
  1303. *
  1304. * `ngApp` is the easiest, and most common way to bootstrap an application.
  1305. *
  1306. <example module="ngAppDemo">
  1307. <file name="index.html">
  1308. <div ng-controller="ngAppDemoController">
  1309. I can add: {{a}} + {{b}} = {{ a+b }}
  1310. </div>
  1311. </file>
  1312. <file name="script.js">
  1313. angular.module('ngAppDemo', []).controller('ngAppDemoController', function($scope) {
  1314. $scope.a = 1;
  1315. $scope.b = 2;
  1316. });
  1317. </file>
  1318. </example>
  1319. *
  1320. * Using `ngStrictDi`, you would see something like this:
  1321. *
  1322. <example ng-app-included="true">
  1323. <file name="index.html">
  1324. <div ng-app="ngAppStrictDemo" ng-strict-di>
  1325. <div ng-controller="GoodController1">
  1326. I can add: {{a}} + {{b}} = {{ a+b }}
  1327. <p>This renders because the controller does not fail to
  1328. instantiate, by using explicit annotation style (see
  1329. script.js for details)
  1330. </p>
  1331. </div>
  1332. <div ng-controller="GoodController2">
  1333. Name: <input ng-model="name"><br />
  1334. Hello, {{name}}!
  1335. <p>This renders because the controller does not fail to
  1336. instantiate, by using explicit annotation style
  1337. (see script.js for details)
  1338. </p>
  1339. </div>
  1340. <div ng-controller="BadController">
  1341. I can add: {{a}} + {{b}} = {{ a+b }}
  1342. <p>The controller could not be instantiated, due to relying
  1343. on automatic function annotations (which are disabled in
  1344. strict mode). As such, the content of this section is not
  1345. interpolated, and there should be an error in your web console.
  1346. </p>
  1347. </div>
  1348. </div>
  1349. </file>
  1350. <file name="script.js">
  1351. angular.module('ngAppStrictDemo', [])
  1352. // BadController will fail to instantiate, due to relying on automatic function annotation,
  1353. // rather than an explicit annotation
  1354. .controller('BadController', function($scope) {
  1355. $scope.a = 1;
  1356. $scope.b = 2;
  1357. })
  1358. // Unlike BadController, GoodController1 and GoodController2 will not fail to be instantiated,
  1359. // due to using explicit annotations using the array style and $inject property, respectively.
  1360. .controller('GoodController1', ['$scope', function($scope) {
  1361. $scope.a = 1;
  1362. $scope.b = 2;
  1363. }])
  1364. .controller('GoodController2', GoodController2);
  1365. function GoodController2($scope) {
  1366. $scope.name = "World";
  1367. }
  1368. GoodController2.$inject = ['$scope'];
  1369. </file>
  1370. <file name="style.css">
  1371. div[ng-controller] {
  1372. margin-bottom: 1em;
  1373. -webkit-border-radius: 4px;
  1374. border-radius: 4px;
  1375. border: 1px solid;
  1376. padding: .5em;
  1377. }
  1378. div[ng-controller^=Good] {
  1379. border-color: #d6e9c6;
  1380. background-color: #dff0d8;
  1381. color: #3c763d;
  1382. }
  1383. div[ng-controller^=Bad] {
  1384. border-color: #ebccd1;
  1385. background-color: #f2dede;
  1386. color: #a94442;
  1387. margin-bottom: 0;
  1388. }
  1389. </file>
  1390. </example>
  1391. */
  1392. function angularInit(element, bootstrap) {
  1393. var appElement,
  1394. module,
  1395. config = {};
  1396. // The element `element` has priority over any other element
  1397. forEach(ngAttrPrefixes, function(prefix) {
  1398. var name = prefix + 'app';
  1399. if (!appElement && element.hasAttribute && element.hasAttribute(name)) {
  1400. appElement = element;
  1401. module = element.getAttribute(name);
  1402. }
  1403. });
  1404. forEach(ngAttrPrefixes, function(prefix) {
  1405. var name = prefix + 'app';
  1406. var candidate;
  1407. if (!appElement && (candidate = element.querySelector('[' + name.replace(':', '\\:') + ']'))) {
  1408. appElement = candidate;
  1409. module = candidate.getAttribute(name);
  1410. }
  1411. });
  1412. if (appElement) {
  1413. config.strictDi = getNgAttribute(appElement, "strict-di") !== null;
  1414. bootstrap(appElement, module ? [module] : [], config);
  1415. }
  1416. }
  1417. /**
  1418. * @ngdoc function
  1419. * @name angular.bootstrap
  1420. * @module ng
  1421. * @description
  1422. * Use this function to manually start up angular application.
  1423. *
  1424. * See: {@link guide/bootstrap Bootstrap}
  1425. *
  1426. * Note that Protractor based end-to-end tests cannot use this function to bootstrap manually.
  1427. * They must use {@link ng.directive:ngApp ngApp}.
  1428. *
  1429. * Angular will detect if it has been loaded into the browser more than once and only allow the
  1430. * first loaded script to be bootstrapped and will report a warning to the browser console for
  1431. * each of the subsequent scripts. This prevents strange results in applications, where otherwise
  1432. * multiple instances of Angular try to work on the DOM.
  1433. *
  1434. * ```html
  1435. * <!doctype html>
  1436. * <html>
  1437. * <body>
  1438. * <div ng-controller="WelcomeController">
  1439. * {{greeting}}
  1440. * </div>
  1441. *
  1442. * <script src="angular.js"></script>
  1443. * <script>
  1444. * var app = angular.module('demo', [])
  1445. * .controller('WelcomeController', function($scope) {
  1446. * $scope.greeting = 'Welcome!';
  1447. * });
  1448. * angular.bootstrap(document, ['demo']);
  1449. * </script>
  1450. * </body>
  1451. * </html>
  1452. * ```
  1453. *
  1454. * @param {DOMElement} element DOM element which is the root of angular application.
  1455. * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
  1456. * Each item in the array should be the name of a predefined module or a (DI annotated)
  1457. * function that will be invoked by the injector as a `config` block.
  1458. * See: {@link angular.module modules}
  1459. * @param {Object=} config an object for defining configuration options for the application. The
  1460. * following keys are supported:
  1461. *
  1462. * * `strictDi` - disable automatic function annotation for the application. This is meant to
  1463. * assist in finding bugs which break minified code. Defaults to `false`.
  1464. *
  1465. * @returns {auto.$injector} Returns the newly created injector for this app.
  1466. */
  1467. function bootstrap(element, modules, config) {
  1468. if (!isObject(config)) config = {};
  1469. var defaultConfig = {
  1470. strictDi: false
  1471. };
  1472. config = extend(defaultConfig, config);
  1473. var doBootstrap = function() {
  1474. element = jqLite(element);
  1475. if (element.injector()) {
  1476. var tag = (element[0] === document) ? 'document' : startingTag(element);
  1477. //Encode angle brackets to prevent input from being sanitized to empty string #8683
  1478. throw ngMinErr(
  1479. 'btstrpd',
  1480. "App Already Bootstrapped with this Element '{0}'",
  1481. tag.replace(/</,'&lt;').replace(/>/,'&gt;'));
  1482. }
  1483. modules = modules || [];
  1484. modules.unshift(['$provide', function($provide) {
  1485. $provide.value('$rootElement', element);
  1486. }]);
  1487. if (config.debugInfoEnabled) {
  1488. // Pushing so that this overrides `debugInfoEnabled` setting defined in user's `modules`.
  1489. modules.push(['$compileProvider', function($compileProvider) {
  1490. $compileProvider.debugInfoEnabled(true);
  1491. }]);
  1492. }
  1493. modules.unshift('ng');
  1494. var injector = createInjector(modules, config.strictDi);
  1495. injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector',
  1496. function bootstrapApply(scope, element, compile, injector) {
  1497. scope.$apply(function() {
  1498. element.data('$injector', injector);
  1499. compile(element)(scope);
  1500. });
  1501. }]
  1502. );
  1503. return injector;
  1504. };
  1505. var NG_ENABLE_DEBUG_INFO = /^NG_ENABLE_DEBUG_INFO!/;
  1506. var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
  1507. if (window && NG_ENABLE_DEBUG_INFO.test(window.name)) {
  1508. config.debugInfoEnabled = true;
  1509. window.name = window.name.replace(NG_ENABLE_DEBUG_INFO, '');
  1510. }
  1511. if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
  1512. return doBootstrap();
  1513. }
  1514. window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
  1515. angular.resumeBootstrap = function(extraModules) {
  1516. forEach(extraModules, function(module) {
  1517. modules.push(module);
  1518. });
  1519. return doBootstrap();
  1520. };
  1521. if (isFunction(angular.resumeDeferredBootstrap)) {
  1522. angular.resumeDeferredBootstrap();
  1523. }
  1524. }
  1525. /**
  1526. * @ngdoc function
  1527. * @name angular.reloadWithDebugInfo
  1528. * @module ng
  1529. * @description
  1530. * Use this function to reload the current application with debug information turned on.
  1531. * This takes precedence over a call to `$compileProvider.debugInfoEnabled(false)`.
  1532. *
  1533. * See {@link ng.$compileProvider#debugInfoEnabled} for more.
  1534. */
  1535. function reloadWithDebugInfo() {
  1536. window.name = 'NG_ENABLE_DEBUG_INFO!' + window.name;
  1537. window.location.reload();
  1538. }
  1539. /**
  1540. * @name angular.getTestability
  1541. * @module ng
  1542. * @description
  1543. * Get the testability service for the instance of Angular on the given
  1544. * element.
  1545. * @param {DOMElement} element DOM element which is the root of angular application.
  1546. */
  1547. function getTestability(rootElement) {
  1548. var injector = angular.element(rootElement).injector();
  1549. if (!injector) {
  1550. throw ngMinErr('test',
  1551. 'no injector found for element argument to getTestability');
  1552. }
  1553. return injector.get('$$testability');
  1554. }
  1555. var SNAKE_CASE_REGEXP = /[A-Z]/g;
  1556. function snake_case(name, separator) {
  1557. separator = separator || '_';
  1558. return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
  1559. return (pos ? separator : '') + letter.toLowerCase();
  1560. });
  1561. }
  1562. var bindJQueryFired = false;
  1563. var skipDestroyOnNextJQueryCleanData;
  1564. function bindJQuery() {
  1565. var originalCleanData;
  1566. if (bindJQueryFired) {
  1567. return;
  1568. }
  1569. // bind to jQuery if present;
  1570. var jqName = jq();
  1571. jQuery = isUndefined(jqName) ? window.jQuery : // use jQuery (if present)
  1572. !jqName ? undefined : // use jqLite
  1573. window[jqName]; // use jQuery specified by `ngJq`
  1574. // Use jQuery if it exists with proper functionality, otherwise default to us.
  1575. // Angular 1.2+ requires jQuery 1.7+ for on()/off() support.
  1576. // Angular 1.3+ technically requires at least jQuery 2.1+ but it may work with older
  1577. // versions. It will not work for sure with jQuery <1.7, though.
  1578. if (jQuery && jQuery.fn.on) {
  1579. jqLite = jQuery;
  1580. extend(jQuery.fn, {
  1581. scope: JQLitePrototype.scope,
  1582. isolateScope: JQLitePrototype.isolateScope,
  1583. controller: JQLitePrototype.controller,
  1584. injector: JQLitePrototype.injector,
  1585. inheritedData: JQLitePrototype.inheritedData
  1586. });
  1587. // All nodes removed from the DOM via various jQuery APIs like .remove()
  1588. // are passed through jQuery.cleanData. Monkey-patch this method to fire
  1589. // the $destroy event on all removed nodes.
  1590. originalCleanData = jQuery.cleanData;
  1591. jQuery.cleanData = function(elems) {
  1592. var events;
  1593. if (!skipDestroyOnNextJQueryCleanData) {
  1594. for (var i = 0, elem; (elem = elems[i]) != null; i++) {
  1595. events = jQuery._data(elem, "events");
  1596. if (events && events.$destroy) {
  1597. jQuery(elem).triggerHandler('$destroy');
  1598. }
  1599. }
  1600. } else {
  1601. skipDestroyOnNextJQueryCleanData = false;
  1602. }
  1603. originalCleanData(elems);
  1604. };
  1605. } else {
  1606. jqLite = JQLite;
  1607. }
  1608. angular.element = jqLite;
  1609. // Prevent double-proxying.
  1610. bindJQueryFired = true;
  1611. }
  1612. /**
  1613. * throw error if the argument is falsy.
  1614. */
  1615. function assertArg(arg, name, reason) {
  1616. if (!arg) {
  1617. throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
  1618. }
  1619. return arg;
  1620. }
  1621. function assertArgFn(arg, name, acceptArrayAnnotation) {
  1622. if (acceptArrayAnnotation && isArray(arg)) {
  1623. arg = arg[arg.length - 1];
  1624. }
  1625. assertArg(isFunction(arg), name, 'not a function, got ' +
  1626. (arg && typeof arg === 'object' ? arg.constructor.name || 'Object' : typeof arg));
  1627. return arg;
  1628. }
  1629. /**
  1630. * throw error if the name given is hasOwnProperty
  1631. * @param {String} name the name to test
  1632. * @param {String} context the context in which the name is used, such as module or directive
  1633. */
  1634. function assertNotHasOwnProperty(name, context) {
  1635. if (name === 'hasOwnProperty') {
  1636. throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
  1637. }
  1638. }
  1639. /**
  1640. * Return the value accessible from the object by path. Any undefined traversals are ignored
  1641. * @param {Object} obj starting object
  1642. * @param {String} path path to traverse
  1643. * @param {boolean} [bindFnToScope=true]
  1644. * @returns {Object} value as accessible by path
  1645. */
  1646. //TODO(misko): this function needs to be removed
  1647. function getter(obj, path, bindFnToScope) {
  1648. if (!path) return obj;
  1649. var keys = path.split('.');
  1650. var key;
  1651. var lastInstance = obj;
  1652. var len = keys.length;
  1653. for (var i = 0; i < len; i++) {
  1654. key = keys[i];
  1655. if (obj) {
  1656. obj = (lastInstance = obj)[key];
  1657. }
  1658. }
  1659. if (!bindFnToScope && isFunction(obj)) {
  1660. return bind(lastInstance, obj);
  1661. }
  1662. return obj;
  1663. }
  1664. /**
  1665. * Return the DOM siblings between the first and last node in the given array.
  1666. * @param {Array} array like object
  1667. * @returns {Array} the inputted object or a jqLite collection containing the nodes
  1668. */
  1669. function getBlockNodes(nodes) {
  1670. // TODO(perf): update `nodes` instead of creating a new object?
  1671. var node = nodes[0];
  1672. var endNode = nodes[nodes.length - 1];
  1673. var blockNodes;
  1674. for (var i = 1; node !== endNode && (node = node.nextSibling); i++) {
  1675. if (blockNodes || nodes[i] !== node) {
  1676. if (!blockNodes) {
  1677. blockNodes = jqLite(slice.call(nodes, 0, i));
  1678. }
  1679. blockNodes.push(node);
  1680. }
  1681. }
  1682. return blockNodes || nodes;
  1683. }
  1684. /**
  1685. * Creates a new object without a prototype. This object is useful for lookup without having to
  1686. * guard against prototypically inherited properties via hasOwnProperty.
  1687. *
  1688. * Related micro-benchmarks:
  1689. * - http://jsperf.com/object-create2
  1690. * - http://jsperf.com/proto-map-lookup/2
  1691. * - http://jsperf.com/for-in-vs-object-keys2
  1692. *
  1693. * @returns {Object}
  1694. */
  1695. function createMap() {
  1696. return Object.create(null);
  1697. }
  1698. var NODE_TYPE_ELEMENT = 1;
  1699. var NODE_TYPE_ATTRIBUTE = 2;
  1700. var NODE_TYPE_TEXT = 3;
  1701. var NODE_TYPE_COMMENT = 8;
  1702. var NODE_TYPE_DOCUMENT = 9;
  1703. var NODE_TYPE_DOCUMENT_FRAGMENT = 11;
  1704. /**
  1705. * @ngdoc type
  1706. * @name angular.Module
  1707. * @module ng
  1708. * @description
  1709. *
  1710. * Interface for configuring angular {@link angular.module modules}.
  1711. */
  1712. function setupModuleLoader(window) {
  1713. var $injectorMinErr = minErr('$injector');
  1714. var ngMinErr = minErr('ng');
  1715. function ensure(obj, name, factory) {
  1716. return obj[name] || (obj[name] = factory());
  1717. }
  1718. var angular = ensure(window, 'angular', Object);
  1719. // We need to expose `angular.$$minErr` to modules such as `ngResource` that reference it during bootstrap
  1720. angular.$$minErr = angular.$$minErr || minErr;
  1721. return ensure(angular, 'module', function() {
  1722. /** @type {Object.<string, angular.Module>} */
  1723. var modules = {};
  1724. /**
  1725. * @ngdoc function
  1726. * @name angular.module
  1727. * @module ng
  1728. * @description
  1729. *
  1730. * The `angular.module` is a global place for creating, registering and retrieving Angular
  1731. * modules.
  1732. * All modules (angular core or 3rd party) that should be available to an application must be
  1733. * registered using this mechanism.
  1734. *
  1735. * Passing one argument retrieves an existing {@link angular.Module},
  1736. * whereas passing more than one argument creates a new {@link angular.Module}
  1737. *
  1738. *
  1739. * # Module
  1740. *
  1741. * A module is a collection of services, directives, controllers, filters, and configuration information.
  1742. * `angular.module` is used to configure the {@link auto.$injector $injector}.
  1743. *
  1744. * ```js
  1745. * // Create a new module
  1746. * var myModule = angular.module('myModule', []);
  1747. *
  1748. * // register a new service
  1749. * myModule.value('appName', 'MyCoolApp');
  1750. *
  1751. * // configure existing services inside initialization blocks.
  1752. * myModule.config(['$locationProvider', function($locationProvider) {
  1753. * // Configure existing providers
  1754. * $locationProvider.hashPrefix('!');
  1755. * }]);
  1756. * ```
  1757. *
  1758. * Then you can create an injector and load your modules like this:
  1759. *
  1760. * ```js
  1761. * var injector = angular.injector(['ng', 'myModule'])
  1762. * ```
  1763. *
  1764. * However it's more likely that you'll just use
  1765. * {@link ng.directive:ngApp ngApp} or
  1766. * {@link angular.bootstrap} to simplify this process for you.
  1767. *
  1768. * @param {!string} name The name of the module to create or retrieve.
  1769. * @param {!Array.<string>=} requires If specified then new module is being created. If
  1770. * unspecified then the module is being retrieved for further configuration.
  1771. * @param {Function=} configFn Optional configuration function for the module. Same as
  1772. * {@link angular.Module#config Module#config()}.
  1773. * @returns {module} new module with the {@link angular.Module} api.
  1774. */
  1775. return function module(name, requires, configFn) {
  1776. var assertNotHasOwnProperty = function(name, context) {
  1777. if (name === 'hasOwnProperty') {
  1778. throw ngMinErr('badname', 'hasOwnProperty is not a valid {0} name', context);
  1779. }
  1780. };
  1781. assertNotHasOwnProperty(name, 'module');
  1782. if (requires && modules.hasOwnProperty(name)) {
  1783. modules[name] = null;
  1784. }
  1785. return ensure(modules, name, function() {
  1786. if (!requires) {
  1787. throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
  1788. "the module name or forgot to load it. If registering a module ensure that you " +
  1789. "specify the dependencies as the second argument.", name);
  1790. }
  1791. /** @type {!Array.<Array.<*>>} */
  1792. var invokeQueue = [];
  1793. /** @type {!Array.<Function>} */
  1794. var configBlocks = [];
  1795. /** @type {!Array.<Function>} */
  1796. var runBlocks = [];
  1797. var config = invokeLater('$injector', 'invoke', 'push', configBlocks);
  1798. /** @type {angular.Module} */
  1799. var moduleInstance = {
  1800. // Private state
  1801. _invokeQueue: invokeQueue,
  1802. _configBlocks: configBlocks,
  1803. _runBlocks: runBlocks,
  1804. /**
  1805. * @ngdoc property
  1806. * @name angular.Module#requires
  1807. * @module ng
  1808. *
  1809. * @description
  1810. * Holds the list of modules which the injector will load before the current module is
  1811. * loaded.
  1812. */
  1813. requires: requires,
  1814. /**
  1815. * @ngdoc property
  1816. * @name angular.Module#name
  1817. * @module ng
  1818. *
  1819. * @description
  1820. * Name of the module.
  1821. */
  1822. name: name,
  1823. /**
  1824. * @ngdoc method
  1825. * @name angular.Module#provider
  1826. * @module ng
  1827. * @param {string} name service name
  1828. * @param {Function} providerType Construction function for creating new instance of the
  1829. * service.
  1830. * @description
  1831. * See {@link auto.$provide#provider $provide.provider()}.
  1832. */
  1833. provider: invokeLaterAndSetModuleName('$provide', 'provider'),
  1834. /**
  1835. * @ngdoc method
  1836. * @name angular.Module#factory
  1837. * @module ng
  1838. * @param {string} name service name
  1839. * @param {Function} providerFunction Function for creating new instance of the service.
  1840. * @description
  1841. * See {@link auto.$provide#factory $provide.factory()}.
  1842. */
  1843. factory: invokeLaterAndSetModuleName('$provide', 'factory'),
  1844. /**
  1845. * @ngdoc method
  1846. * @name angular.Module#service
  1847. * @module ng
  1848. * @param {string} name service name
  1849. * @param {Function} constructor A constructor function that will be instantiated.
  1850. * @description
  1851. * See {@link auto.$provide#service $provide.service()}.
  1852. */
  1853. service: invokeLaterAndSetModuleName('$provide', 'service'),
  1854. /**
  1855. * @ngdoc method
  1856. * @name angular.Module#value
  1857. * @module ng
  1858. * @param {string} name service name
  1859. * @param {*} object Service instance object.
  1860. * @description
  1861. * See {@link auto.$provide#value $provide.value()}.
  1862. */
  1863. value: invokeLater('$provide', 'value'),
  1864. /**
  1865. * @ngdoc method
  1866. * @name angular.Module#constant
  1867. * @module ng
  1868. * @param {string} name constant name
  1869. * @param {*} object Constant value.
  1870. * @description
  1871. * Because the constants are fixed, they get applied before other provide methods.
  1872. * See {@link auto.$provide#constant $provide.constant()}.
  1873. */
  1874. constant: invokeLater('$provide', 'constant', 'unshift'),
  1875. /**
  1876. * @ngdoc method
  1877. * @name angular.Module#decorator
  1878. * @module ng
  1879. * @param {string} The name of the service to decorate.
  1880. * @param {Function} This function will be invoked when the service needs to be
  1881. * instantiated and should return the decorated service instance.
  1882. * @description
  1883. * See {@link auto.$provide#decorator $provide.decorator()}.
  1884. */
  1885. decorator: invokeLaterAndSetModuleName('$provide', 'decorator'),
  1886. /**
  1887. * @ngdoc method
  1888. * @name angular.Module#animation
  1889. * @module ng
  1890. * @param {string} name animation name
  1891. * @param {Function} animationFactory Factory function for creating new instance of an
  1892. * animation.
  1893. * @description
  1894. *
  1895. * **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
  1896. *
  1897. *
  1898. * Defines an animation hook that can be later used with
  1899. * {@link $animate $animate} service and directives that use this service.
  1900. *
  1901. * ```js
  1902. * module.animation('.animation-name', function($inject1, $inject2) {
  1903. * return {
  1904. * eventName : function(element, done) {
  1905. * //code to run the animation
  1906. * //once complete, then run done()
  1907. * return function cancellationFunction(element) {
  1908. * //code to cancel the animation
  1909. * }
  1910. * }
  1911. * }
  1912. * })
  1913. * ```
  1914. *
  1915. * See {@link ng.$animateProvider#register $animateProvider.register()} and
  1916. * {@link ngAnimate ngAnimate module} for more information.
  1917. */
  1918. animation: invokeLaterAndSetModuleName('$animateProvider', 'register'),
  1919. /**
  1920. * @ngdoc method
  1921. * @name angular.Module#filter
  1922. * @module ng
  1923. * @param {string} name Filter name - this must be a valid angular expression identifier
  1924. * @param {Function} filterFactory Factory function for creating new instance of filter.
  1925. * @description
  1926. * See {@link ng.$filterProvider#register $filterProvider.register()}.
  1927. *
  1928. * <div class="alert alert-warning">
  1929. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  1930. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  1931. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  1932. * (`myapp_subsection_filterx`).
  1933. * </div>
  1934. */
  1935. filter: invokeLaterAndSetModuleName('$filterProvider', 'register'),
  1936. /**
  1937. * @ngdoc method
  1938. * @name angular.Module#controller
  1939. * @module ng
  1940. * @param {string|Object} name Controller name, or an object map of controllers where the
  1941. * keys are the names and the values are the constructors.
  1942. * @param {Function} constructor Controller constructor function.
  1943. * @description
  1944. * See {@link ng.$controllerProvider#register $controllerProvider.register()}.
  1945. */
  1946. controller: invokeLaterAndSetModuleName('$controllerProvider', 'register'),
  1947. /**
  1948. * @ngdoc method
  1949. * @name angular.Module#directive
  1950. * @module ng
  1951. * @param {string|Object} name Directive name, or an object map of directives where the
  1952. * keys are the names and the values are the factories.
  1953. * @param {Function} directiveFactory Factory function for creating new instance of
  1954. * directives.
  1955. * @description
  1956. * See {@link ng.$compileProvider#directive $compileProvider.directive()}.
  1957. */
  1958. directive: invokeLaterAndSetModuleName('$compileProvider', 'directive'),
  1959. /**
  1960. * @ngdoc method
  1961. * @name angular.Module#config
  1962. * @module ng
  1963. * @param {Function} configFn Execute this function on module load. Useful for service
  1964. * configuration.
  1965. * @description
  1966. * Use this method to register work which needs to be performed on module loading.
  1967. * For more about how to configure services, see
  1968. * {@link providers#provider-recipe Provider Recipe}.
  1969. */
  1970. config: config,
  1971. /**
  1972. * @ngdoc method
  1973. * @name angular.Module#run
  1974. * @module ng
  1975. * @param {Function} initializationFn Execute this function after injector creation.
  1976. * Useful for application initialization.
  1977. * @description
  1978. * Use this method to register work which should be performed when the injector is done
  1979. * loading all modules.
  1980. */
  1981. run: function(block) {
  1982. runBlocks.push(block);
  1983. return this;
  1984. }
  1985. };
  1986. if (configFn) {
  1987. config(configFn);
  1988. }
  1989. return moduleInstance;
  1990. /**
  1991. * @param {string} provider
  1992. * @param {string} method
  1993. * @param {String=} insertMethod
  1994. * @returns {angular.Module}
  1995. */
  1996. function invokeLater(provider, method, insertMethod, queue) {
  1997. if (!queue) queue = invokeQueue;
  1998. return function() {
  1999. queue[insertMethod || 'push']([provider, method, arguments]);
  2000. return moduleInstance;
  2001. };
  2002. }
  2003. /**
  2004. * @param {string} provider
  2005. * @param {string} method
  2006. * @returns {angular.Module}
  2007. */
  2008. function invokeLaterAndSetModuleName(provider, method) {
  2009. return function(recipeName, factoryFunction) {
  2010. if (factoryFunction && isFunction(factoryFunction)) factoryFunction.$$moduleName = name;
  2011. invokeQueue.push([provider, method, arguments]);
  2012. return moduleInstance;
  2013. };
  2014. }
  2015. });
  2016. };
  2017. });
  2018. }
  2019. /* global: toDebugString: true */
  2020. function serializeObject(obj) {
  2021. var seen = [];
  2022. return JSON.stringify(obj, function(key, val) {
  2023. val = toJsonReplacer(key, val);
  2024. if (isObject(val)) {
  2025. if (seen.indexOf(val) >= 0) return '...';
  2026. seen.push(val);
  2027. }
  2028. return val;
  2029. });
  2030. }
  2031. function toDebugString(obj) {
  2032. if (typeof obj === 'function') {
  2033. return obj.toString().replace(/ \{[\s\S]*$/, '');
  2034. } else if (isUndefined(obj)) {
  2035. return 'undefined';
  2036. } else if (typeof obj !== 'string') {
  2037. return serializeObject(obj);
  2038. }
  2039. return obj;
  2040. }
  2041. /* global angularModule: true,
  2042. version: true,
  2043. $CompileProvider,
  2044. htmlAnchorDirective,
  2045. inputDirective,
  2046. inputDirective,
  2047. formDirective,
  2048. scriptDirective,
  2049. selectDirective,
  2050. styleDirective,
  2051. optionDirective,
  2052. ngBindDirective,
  2053. ngBindHtmlDirective,
  2054. ngBindTemplateDirective,
  2055. ngClassDirective,
  2056. ngClassEvenDirective,
  2057. ngClassOddDirective,
  2058. ngCloakDirective,
  2059. ngControllerDirective,
  2060. ngFormDirective,
  2061. ngHideDirective,
  2062. ngIfDirective,
  2063. ngIncludeDirective,
  2064. ngIncludeFillContentDirective,
  2065. ngInitDirective,
  2066. ngNonBindableDirective,
  2067. ngPluralizeDirective,
  2068. ngRepeatDirective,
  2069. ngShowDirective,
  2070. ngStyleDirective,
  2071. ngSwitchDirective,
  2072. ngSwitchWhenDirective,
  2073. ngSwitchDefaultDirective,
  2074. ngOptionsDirective,
  2075. ngTranscludeDirective,
  2076. ngModelDirective,
  2077. ngListDirective,
  2078. ngChangeDirective,
  2079. patternDirective,
  2080. patternDirective,
  2081. requiredDirective,
  2082. requiredDirective,
  2083. minlengthDirective,
  2084. minlengthDirective,
  2085. maxlengthDirective,
  2086. maxlengthDirective,
  2087. ngValueDirective,
  2088. ngModelOptionsDirective,
  2089. ngAttributeAliasDirectives,
  2090. ngEventDirectives,
  2091. $AnchorScrollProvider,
  2092. $AnimateProvider,
  2093. $CoreAnimateCssProvider,
  2094. $$CoreAnimateQueueProvider,
  2095. $$CoreAnimateRunnerProvider,
  2096. $BrowserProvider,
  2097. $CacheFactoryProvider,
  2098. $ControllerProvider,
  2099. $DocumentProvider,
  2100. $ExceptionHandlerProvider,
  2101. $FilterProvider,
  2102. $$ForceReflowProvider,
  2103. $InterpolateProvider,
  2104. $IntervalProvider,
  2105. $$HashMapProvider,
  2106. $HttpProvider,
  2107. $HttpParamSerializerProvider,
  2108. $HttpParamSerializerJQLikeProvider,
  2109. $HttpBackendProvider,
  2110. $xhrFactoryProvider,
  2111. $LocationProvider,
  2112. $LogProvider,
  2113. $ParseProvider,
  2114. $RootScopeProvider,
  2115. $QProvider,
  2116. $$QProvider,
  2117. $$SanitizeUriProvider,
  2118. $SceProvider,
  2119. $SceDelegateProvider,
  2120. $SnifferProvider,
  2121. $TemplateCacheProvider,
  2122. $TemplateRequestProvider,
  2123. $$TestabilityProvider,
  2124. $TimeoutProvider,
  2125. $$RAFProvider,
  2126. $WindowProvider,
  2127. $$jqLiteProvider,
  2128. $$CookieReaderProvider
  2129. */
  2130. /**
  2131. * @ngdoc object
  2132. * @name angular.version
  2133. * @module ng
  2134. * @description
  2135. * An object that contains information about the current AngularJS version.
  2136. *
  2137. * This object has the following properties:
  2138. *
  2139. * - `full` – `{string}` – Full version string, such as "0.9.18".
  2140. * - `major` – `{number}` – Major version number, such as "0".
  2141. * - `minor` – `{number}` – Minor version number, such as "9".
  2142. * - `dot` – `{number}` – Dot version number, such as "18".
  2143. * - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
  2144. */
  2145. var version = {
  2146. full: '1.4.8', // all of these placeholder strings will be replaced by grunt's
  2147. major: 1, // package task
  2148. minor: 4,
  2149. dot: 8,
  2150. codeName: 'ice-manipulation'
  2151. };
  2152. function publishExternalAPI(angular) {
  2153. extend(angular, {
  2154. 'bootstrap': bootstrap,
  2155. 'copy': copy,
  2156. 'extend': extend,
  2157. 'merge': merge,
  2158. 'equals': equals,
  2159. 'element': jqLite,
  2160. 'forEach': forEach,
  2161. 'injector': createInjector,
  2162. 'noop': noop,
  2163. 'bind': bind,
  2164. 'toJson': toJson,
  2165. 'fromJson': fromJson,
  2166. 'identity': identity,
  2167. 'isUndefined': isUndefined,
  2168. 'isDefined': isDefined,
  2169. 'isString': isString,
  2170. 'isFunction': isFunction,
  2171. 'isObject': isObject,
  2172. 'isNumber': isNumber,
  2173. 'isElement': isElement,
  2174. 'isArray': isArray,
  2175. 'version': version,
  2176. 'isDate': isDate,
  2177. 'lowercase': lowercase,
  2178. 'uppercase': uppercase,
  2179. 'callbacks': {counter: 0},
  2180. 'getTestability': getTestability,
  2181. '$$minErr': minErr,
  2182. '$$csp': csp,
  2183. 'reloadWithDebugInfo': reloadWithDebugInfo
  2184. });
  2185. angularModule = setupModuleLoader(window);
  2186. angularModule('ng', ['ngLocale'], ['$provide',
  2187. function ngModule($provide) {
  2188. // $$sanitizeUriProvider needs to be before $compileProvider as it is used by it.
  2189. $provide.provider({
  2190. $$sanitizeUri: $$SanitizeUriProvider
  2191. });
  2192. $provide.provider('$compile', $CompileProvider).
  2193. directive({
  2194. a: htmlAnchorDirective,
  2195. input: inputDirective,
  2196. textarea: inputDirective,
  2197. form: formDirective,
  2198. script: scriptDirective,
  2199. select: selectDirective,
  2200. style: styleDirective,
  2201. option: optionDirective,
  2202. ngBind: ngBindDirective,
  2203. ngBindHtml: ngBindHtmlDirective,
  2204. ngBindTemplate: ngBindTemplateDirective,
  2205. ngClass: ngClassDirective,
  2206. ngClassEven: ngClassEvenDirective,
  2207. ngClassOdd: ngClassOddDirective,
  2208. ngCloak: ngCloakDirective,
  2209. ngController: ngControllerDirective,
  2210. ngForm: ngFormDirective,
  2211. ngHide: ngHideDirective,
  2212. ngIf: ngIfDirective,
  2213. ngInclude: ngIncludeDirective,
  2214. ngInit: ngInitDirective,
  2215. ngNonBindable: ngNonBindableDirective,
  2216. ngPluralize: ngPluralizeDirective,
  2217. ngRepeat: ngRepeatDirective,
  2218. ngShow: ngShowDirective,
  2219. ngStyle: ngStyleDirective,
  2220. ngSwitch: ngSwitchDirective,
  2221. ngSwitchWhen: ngSwitchWhenDirective,
  2222. ngSwitchDefault: ngSwitchDefaultDirective,
  2223. ngOptions: ngOptionsDirective,
  2224. ngTransclude: ngTranscludeDirective,
  2225. ngModel: ngModelDirective,
  2226. ngList: ngListDirective,
  2227. ngChange: ngChangeDirective,
  2228. pattern: patternDirective,
  2229. ngPattern: patternDirective,
  2230. required: requiredDirective,
  2231. ngRequired: requiredDirective,
  2232. minlength: minlengthDirective,
  2233. ngMinlength: minlengthDirective,
  2234. maxlength: maxlengthDirective,
  2235. ngMaxlength: maxlengthDirective,
  2236. ngValue: ngValueDirective,
  2237. ngModelOptions: ngModelOptionsDirective
  2238. }).
  2239. directive({
  2240. ngInclude: ngIncludeFillContentDirective
  2241. }).
  2242. directive(ngAttributeAliasDirectives).
  2243. directive(ngEventDirectives);
  2244. $provide.provider({
  2245. $anchorScroll: $AnchorScrollProvider,
  2246. $animate: $AnimateProvider,
  2247. $animateCss: $CoreAnimateCssProvider,
  2248. $$animateQueue: $$CoreAnimateQueueProvider,
  2249. $$AnimateRunner: $$CoreAnimateRunnerProvider,
  2250. $browser: $BrowserProvider,
  2251. $cacheFactory: $CacheFactoryProvider,
  2252. $controller: $ControllerProvider,
  2253. $document: $DocumentProvider,
  2254. $exceptionHandler: $ExceptionHandlerProvider,
  2255. $filter: $FilterProvider,
  2256. $$forceReflow: $$ForceReflowProvider,
  2257. $interpolate: $InterpolateProvider,
  2258. $interval: $IntervalProvider,
  2259. $http: $HttpProvider,
  2260. $httpParamSerializer: $HttpParamSerializerProvider,
  2261. $httpParamSerializerJQLike: $HttpParamSerializerJQLikeProvider,
  2262. $httpBackend: $HttpBackendProvider,
  2263. $xhrFactory: $xhrFactoryProvider,
  2264. $location: $LocationProvider,
  2265. $log: $LogProvider,
  2266. $parse: $ParseProvider,
  2267. $rootScope: $RootScopeProvider,
  2268. $q: $QProvider,
  2269. $$q: $$QProvider,
  2270. $sce: $SceProvider,
  2271. $sceDelegate: $SceDelegateProvider,
  2272. $sniffer: $SnifferProvider,
  2273. $templateCache: $TemplateCacheProvider,
  2274. $templateRequest: $TemplateRequestProvider,
  2275. $$testability: $$TestabilityProvider,
  2276. $timeout: $TimeoutProvider,
  2277. $window: $WindowProvider,
  2278. $$rAF: $$RAFProvider,
  2279. $$jqLite: $$jqLiteProvider,
  2280. $$HashMap: $$HashMapProvider,
  2281. $$cookieReader: $$CookieReaderProvider
  2282. });
  2283. }
  2284. ]);
  2285. }
  2286. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  2287. * Any commits to this file should be reviewed with security in mind. *
  2288. * Changes to this file can potentially create security vulnerabilities. *
  2289. * An approval from 2 Core members with history of modifying *
  2290. * this file is required. *
  2291. * *
  2292. * Does the change somehow allow for arbitrary javascript to be executed? *
  2293. * Or allows for someone to change the prototype of built-in objects? *
  2294. * Or gives undesired access to variables likes document or window? *
  2295. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  2296. /* global JQLitePrototype: true,
  2297. addEventListenerFn: true,
  2298. removeEventListenerFn: true,
  2299. BOOLEAN_ATTR: true,
  2300. ALIASED_ATTR: true,
  2301. */
  2302. //////////////////////////////////
  2303. //JQLite
  2304. //////////////////////////////////
  2305. /**
  2306. * @ngdoc function
  2307. * @name angular.element
  2308. * @module ng
  2309. * @kind function
  2310. *
  2311. * @description
  2312. * Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
  2313. *
  2314. * If jQuery is available, `angular.element` is an alias for the
  2315. * [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
  2316. * delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
  2317. *
  2318. * <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
  2319. * Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
  2320. * commonly needed functionality with the goal of having a very small footprint.</div>
  2321. *
  2322. * To use `jQuery`, simply ensure it is loaded before the `angular.js` file.
  2323. *
  2324. * <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
  2325. * jqLite; they are never raw DOM references.</div>
  2326. *
  2327. * ## Angular's jqLite
  2328. * jqLite provides only the following jQuery methods:
  2329. *
  2330. * - [`addClass()`](http://api.jquery.com/addClass/)
  2331. * - [`after()`](http://api.jquery.com/after/)
  2332. * - [`append()`](http://api.jquery.com/append/)
  2333. * - [`attr()`](http://api.jquery.com/attr/) - Does not support functions as parameters
  2334. * - [`bind()`](http://api.jquery.com/bind/) - Does not support namespaces, selectors or eventData
  2335. * - [`children()`](http://api.jquery.com/children/) - Does not support selectors
  2336. * - [`clone()`](http://api.jquery.com/clone/)
  2337. * - [`contents()`](http://api.jquery.com/contents/)
  2338. * - [`css()`](http://api.jquery.com/css/) - Only retrieves inline-styles, does not call `getComputedStyle()`. As a setter, does not convert numbers to strings or append 'px'.
  2339. * - [`data()`](http://api.jquery.com/data/)
  2340. * - [`detach()`](http://api.jquery.com/detach/)
  2341. * - [`empty()`](http://api.jquery.com/empty/)
  2342. * - [`eq()`](http://api.jquery.com/eq/)
  2343. * - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
  2344. * - [`hasClass()`](http://api.jquery.com/hasClass/)
  2345. * - [`html()`](http://api.jquery.com/html/)
  2346. * - [`next()`](http://api.jquery.com/next/) - Does not support selectors
  2347. * - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
  2348. * - [`off()`](http://api.jquery.com/off/) - Does not support namespaces, selectors or event object as parameter
  2349. * - [`one()`](http://api.jquery.com/one/) - Does not support namespaces or selectors
  2350. * - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
  2351. * - [`prepend()`](http://api.jquery.com/prepend/)
  2352. * - [`prop()`](http://api.jquery.com/prop/)
  2353. * - [`ready()`](http://api.jquery.com/ready/)
  2354. * - [`remove()`](http://api.jquery.com/remove/)
  2355. * - [`removeAttr()`](http://api.jquery.com/removeAttr/)
  2356. * - [`removeClass()`](http://api.jquery.com/removeClass/)
  2357. * - [`removeData()`](http://api.jquery.com/removeData/)
  2358. * - [`replaceWith()`](http://api.jquery.com/replaceWith/)
  2359. * - [`text()`](http://api.jquery.com/text/)
  2360. * - [`toggleClass()`](http://api.jquery.com/toggleClass/)
  2361. * - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
  2362. * - [`unbind()`](http://api.jquery.com/unbind/) - Does not support namespaces or event object as parameter
  2363. * - [`val()`](http://api.jquery.com/val/)
  2364. * - [`wrap()`](http://api.jquery.com/wrap/)
  2365. *
  2366. * ## jQuery/jqLite Extras
  2367. * Angular also provides the following additional methods and events to both jQuery and jqLite:
  2368. *
  2369. * ### Events
  2370. * - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
  2371. * on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
  2372. * element before it is removed.
  2373. *
  2374. * ### Methods
  2375. * - `controller(name)` - retrieves the controller of the current element or its parent. By default
  2376. * retrieves controller associated with the `ngController` directive. If `name` is provided as
  2377. * camelCase directive name, then the controller for this directive will be retrieved (e.g.
  2378. * `'ngModel'`).
  2379. * - `injector()` - retrieves the injector of the current element or its parent.
  2380. * - `scope()` - retrieves the {@link ng.$rootScope.Scope scope} of the current
  2381. * element or its parent. Requires {@link guide/production#disabling-debug-data Debug Data} to
  2382. * be enabled.
  2383. * - `isolateScope()` - retrieves an isolate {@link ng.$rootScope.Scope scope} if one is attached directly to the
  2384. * current element. This getter should be used only on elements that contain a directive which starts a new isolate
  2385. * scope. Calling `scope()` on this element always returns the original non-isolate scope.
  2386. * Requires {@link guide/production#disabling-debug-data Debug Data} to be enabled.
  2387. * - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
  2388. * parent element is reached.
  2389. *
  2390. * @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
  2391. * @returns {Object} jQuery object.
  2392. */
  2393. JQLite.expando = 'ng339';
  2394. var jqCache = JQLite.cache = {},
  2395. jqId = 1,
  2396. addEventListenerFn = function(element, type, fn) {
  2397. element.addEventListener(type, fn, false);
  2398. },
  2399. removeEventListenerFn = function(element, type, fn) {
  2400. element.removeEventListener(type, fn, false);
  2401. };
  2402. /*
  2403. * !!! This is an undocumented "private" function !!!
  2404. */
  2405. JQLite._data = function(node) {
  2406. //jQuery always returns an object on cache miss
  2407. return this.cache[node[this.expando]] || {};
  2408. };
  2409. function jqNextId() { return ++jqId; }
  2410. var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
  2411. var MOZ_HACK_REGEXP = /^moz([A-Z])/;
  2412. var MOUSE_EVENT_MAP= { mouseleave: "mouseout", mouseenter: "mouseover"};
  2413. var jqLiteMinErr = minErr('jqLite');
  2414. /**
  2415. * Converts snake_case to camelCase.
  2416. * Also there is special case for Moz prefix starting with upper case letter.
  2417. * @param name Name to normalize
  2418. */
  2419. function camelCase(name) {
  2420. return name.
  2421. replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
  2422. return offset ? letter.toUpperCase() : letter;
  2423. }).
  2424. replace(MOZ_HACK_REGEXP, 'Moz$1');
  2425. }
  2426. var SINGLE_TAG_REGEXP = /^<([\w-]+)\s*\/?>(?:<\/\1>|)$/;
  2427. var HTML_REGEXP = /<|&#?\w+;/;
  2428. var TAG_NAME_REGEXP = /<([\w:-]+)/;
  2429. var XHTML_TAG_REGEXP = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:-]+)[^>]*)\/>/gi;
  2430. var wrapMap = {
  2431. 'option': [1, '<select multiple="multiple">', '</select>'],
  2432. 'thead': [1, '<table>', '</table>'],
  2433. 'col': [2, '<table><colgroup>', '</colgroup></table>'],
  2434. 'tr': [2, '<table><tbody>', '</tbody></table>'],
  2435. 'td': [3, '<table><tbody><tr>', '</tr></tbody></table>'],
  2436. '_default': [0, "", ""]
  2437. };
  2438. wrapMap.optgroup = wrapMap.option;
  2439. wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
  2440. wrapMap.th = wrapMap.td;
  2441. function jqLiteIsTextNode(html) {
  2442. return !HTML_REGEXP.test(html);
  2443. }
  2444. function jqLiteAcceptsData(node) {
  2445. // The window object can accept data but has no nodeType
  2446. // Otherwise we are only interested in elements (1) and documents (9)
  2447. var nodeType = node.nodeType;
  2448. return nodeType === NODE_TYPE_ELEMENT || !nodeType || nodeType === NODE_TYPE_DOCUMENT;
  2449. }
  2450. function jqLiteHasData(node) {
  2451. for (var key in jqCache[node.ng339]) {
  2452. return true;
  2453. }
  2454. return false;
  2455. }
  2456. function jqLiteBuildFragment(html, context) {
  2457. var tmp, tag, wrap,
  2458. fragment = context.createDocumentFragment(),
  2459. nodes = [], i;
  2460. if (jqLiteIsTextNode(html)) {
  2461. // Convert non-html into a text node
  2462. nodes.push(context.createTextNode(html));
  2463. } else {
  2464. // Convert html into DOM nodes
  2465. tmp = tmp || fragment.appendChild(context.createElement("div"));
  2466. tag = (TAG_NAME_REGEXP.exec(html) || ["", ""])[1].toLowerCase();
  2467. wrap = wrapMap[tag] || wrapMap._default;
  2468. tmp.innerHTML = wrap[1] + html.replace(XHTML_TAG_REGEXP, "<$1></$2>") + wrap[2];
  2469. // Descend through wrappers to the right content
  2470. i = wrap[0];
  2471. while (i--) {
  2472. tmp = tmp.lastChild;
  2473. }
  2474. nodes = concat(nodes, tmp.childNodes);
  2475. tmp = fragment.firstChild;
  2476. tmp.textContent = "";
  2477. }
  2478. // Remove wrapper from fragment
  2479. fragment.textContent = "";
  2480. fragment.innerHTML = ""; // Clear inner HTML
  2481. forEach(nodes, function(node) {
  2482. fragment.appendChild(node);
  2483. });
  2484. return fragment;
  2485. }
  2486. function jqLiteParseHTML(html, context) {
  2487. context = context || document;
  2488. var parsed;
  2489. if ((parsed = SINGLE_TAG_REGEXP.exec(html))) {
  2490. return [context.createElement(parsed[1])];
  2491. }
  2492. if ((parsed = jqLiteBuildFragment(html, context))) {
  2493. return parsed.childNodes;
  2494. }
  2495. return [];
  2496. }
  2497. // IE9-11 has no method "contains" in SVG element and in Node.prototype. Bug #10259.
  2498. var jqLiteContains = Node.prototype.contains || function(arg) {
  2499. // jshint bitwise: false
  2500. return !!(this.compareDocumentPosition(arg) & 16);
  2501. // jshint bitwise: true
  2502. };
  2503. /////////////////////////////////////////////
  2504. function JQLite(element) {
  2505. if (element instanceof JQLite) {
  2506. return element;
  2507. }
  2508. var argIsString;
  2509. if (isString(element)) {
  2510. element = trim(element);
  2511. argIsString = true;
  2512. }
  2513. if (!(this instanceof JQLite)) {
  2514. if (argIsString && element.charAt(0) != '<') {
  2515. throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
  2516. }
  2517. return new JQLite(element);
  2518. }
  2519. if (argIsString) {
  2520. jqLiteAddNodes(this, jqLiteParseHTML(element));
  2521. } else {
  2522. jqLiteAddNodes(this, element);
  2523. }
  2524. }
  2525. function jqLiteClone(element) {
  2526. return element.cloneNode(true);
  2527. }
  2528. function jqLiteDealoc(element, onlyDescendants) {
  2529. if (!onlyDescendants) jqLiteRemoveData(element);
  2530. if (element.querySelectorAll) {
  2531. var descendants = element.querySelectorAll('*');
  2532. for (var i = 0, l = descendants.length; i < l; i++) {
  2533. jqLiteRemoveData(descendants[i]);
  2534. }
  2535. }
  2536. }
  2537. function jqLiteOff(element, type, fn, unsupported) {
  2538. if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
  2539. var expandoStore = jqLiteExpandoStore(element);
  2540. var events = expandoStore && expandoStore.events;
  2541. var handle = expandoStore && expandoStore.handle;
  2542. if (!handle) return; //no listeners registered
  2543. if (!type) {
  2544. for (type in events) {
  2545. if (type !== '$destroy') {
  2546. removeEventListenerFn(element, type, handle);
  2547. }
  2548. delete events[type];
  2549. }
  2550. } else {
  2551. var removeHandler = function(type) {
  2552. var listenerFns = events[type];
  2553. if (isDefined(fn)) {
  2554. arrayRemove(listenerFns || [], fn);
  2555. }
  2556. if (!(isDefined(fn) && listenerFns && listenerFns.length > 0)) {
  2557. removeEventListenerFn(element, type, handle);
  2558. delete events[type];
  2559. }
  2560. };
  2561. forEach(type.split(' '), function(type) {
  2562. removeHandler(type);
  2563. if (MOUSE_EVENT_MAP[type]) {
  2564. removeHandler(MOUSE_EVENT_MAP[type]);
  2565. }
  2566. });
  2567. }
  2568. }
  2569. function jqLiteRemoveData(element, name) {
  2570. var expandoId = element.ng339;
  2571. var expandoStore = expandoId && jqCache[expandoId];
  2572. if (expandoStore) {
  2573. if (name) {
  2574. delete expandoStore.data[name];
  2575. return;
  2576. }
  2577. if (expandoStore.handle) {
  2578. if (expandoStore.events.$destroy) {
  2579. expandoStore.handle({}, '$destroy');
  2580. }
  2581. jqLiteOff(element);
  2582. }
  2583. delete jqCache[expandoId];
  2584. element.ng339 = undefined; // don't delete DOM expandos. IE and Chrome don't like it
  2585. }
  2586. }
  2587. function jqLiteExpandoStore(element, createIfNecessary) {
  2588. var expandoId = element.ng339,
  2589. expandoStore = expandoId && jqCache[expandoId];
  2590. if (createIfNecessary && !expandoStore) {
  2591. element.ng339 = expandoId = jqNextId();
  2592. expandoStore = jqCache[expandoId] = {events: {}, data: {}, handle: undefined};
  2593. }
  2594. return expandoStore;
  2595. }
  2596. function jqLiteData(element, key, value) {
  2597. if (jqLiteAcceptsData(element)) {
  2598. var isSimpleSetter = isDefined(value);
  2599. var isSimpleGetter = !isSimpleSetter && key && !isObject(key);
  2600. var massGetter = !key;
  2601. var expandoStore = jqLiteExpandoStore(element, !isSimpleGetter);
  2602. var data = expandoStore && expandoStore.data;
  2603. if (isSimpleSetter) { // data('key', value)
  2604. data[key] = value;
  2605. } else {
  2606. if (massGetter) { // data()
  2607. return data;
  2608. } else {
  2609. if (isSimpleGetter) { // data('key')
  2610. // don't force creation of expandoStore if it doesn't exist yet
  2611. return data && data[key];
  2612. } else { // mass-setter: data({key1: val1, key2: val2})
  2613. extend(data, key);
  2614. }
  2615. }
  2616. }
  2617. }
  2618. }
  2619. function jqLiteHasClass(element, selector) {
  2620. if (!element.getAttribute) return false;
  2621. return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
  2622. indexOf(" " + selector + " ") > -1);
  2623. }
  2624. function jqLiteRemoveClass(element, cssClasses) {
  2625. if (cssClasses && element.setAttribute) {
  2626. forEach(cssClasses.split(' '), function(cssClass) {
  2627. element.setAttribute('class', trim(
  2628. (" " + (element.getAttribute('class') || '') + " ")
  2629. .replace(/[\n\t]/g, " ")
  2630. .replace(" " + trim(cssClass) + " ", " "))
  2631. );
  2632. });
  2633. }
  2634. }
  2635. function jqLiteAddClass(element, cssClasses) {
  2636. if (cssClasses && element.setAttribute) {
  2637. var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
  2638. .replace(/[\n\t]/g, " ");
  2639. forEach(cssClasses.split(' '), function(cssClass) {
  2640. cssClass = trim(cssClass);
  2641. if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
  2642. existingClasses += cssClass + ' ';
  2643. }
  2644. });
  2645. element.setAttribute('class', trim(existingClasses));
  2646. }
  2647. }
  2648. function jqLiteAddNodes(root, elements) {
  2649. // THIS CODE IS VERY HOT. Don't make changes without benchmarking.
  2650. if (elements) {
  2651. // if a Node (the most common case)
  2652. if (elements.nodeType) {
  2653. root[root.length++] = elements;
  2654. } else {
  2655. var length = elements.length;
  2656. // if an Array or NodeList and not a Window
  2657. if (typeof length === 'number' && elements.window !== elements) {
  2658. if (length) {
  2659. for (var i = 0; i < length; i++) {
  2660. root[root.length++] = elements[i];
  2661. }
  2662. }
  2663. } else {
  2664. root[root.length++] = elements;
  2665. }
  2666. }
  2667. }
  2668. }
  2669. function jqLiteController(element, name) {
  2670. return jqLiteInheritedData(element, '$' + (name || 'ngController') + 'Controller');
  2671. }
  2672. function jqLiteInheritedData(element, name, value) {
  2673. // if element is the document object work with the html element instead
  2674. // this makes $(document).scope() possible
  2675. if (element.nodeType == NODE_TYPE_DOCUMENT) {
  2676. element = element.documentElement;
  2677. }
  2678. var names = isArray(name) ? name : [name];
  2679. while (element) {
  2680. for (var i = 0, ii = names.length; i < ii; i++) {
  2681. if (isDefined(value = jqLite.data(element, names[i]))) return value;
  2682. }
  2683. // If dealing with a document fragment node with a host element, and no parent, use the host
  2684. // element as the parent. This enables directives within a Shadow DOM or polyfilled Shadow DOM
  2685. // to lookup parent controllers.
  2686. element = element.parentNode || (element.nodeType === NODE_TYPE_DOCUMENT_FRAGMENT && element.host);
  2687. }
  2688. }
  2689. function jqLiteEmpty(element) {
  2690. jqLiteDealoc(element, true);
  2691. while (element.firstChild) {
  2692. element.removeChild(element.firstChild);
  2693. }
  2694. }
  2695. function jqLiteRemove(element, keepData) {
  2696. if (!keepData) jqLiteDealoc(element);
  2697. var parent = element.parentNode;
  2698. if (parent) parent.removeChild(element);
  2699. }
  2700. function jqLiteDocumentLoaded(action, win) {
  2701. win = win || window;
  2702. if (win.document.readyState === 'complete') {
  2703. // Force the action to be run async for consistent behaviour
  2704. // from the action's point of view
  2705. // i.e. it will definitely not be in a $apply
  2706. win.setTimeout(action);
  2707. } else {
  2708. // No need to unbind this handler as load is only ever called once
  2709. jqLite(win).on('load', action);
  2710. }
  2711. }
  2712. //////////////////////////////////////////
  2713. // Functions which are declared directly.
  2714. //////////////////////////////////////////
  2715. var JQLitePrototype = JQLite.prototype = {
  2716. ready: function(fn) {
  2717. var fired = false;
  2718. function trigger() {
  2719. if (fired) return;
  2720. fired = true;
  2721. fn();
  2722. }
  2723. // check if document is already loaded
  2724. if (document.readyState === 'complete') {
  2725. setTimeout(trigger);
  2726. } else {
  2727. this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
  2728. // we can not use jqLite since we are not done loading and jQuery could be loaded later.
  2729. // jshint -W064
  2730. JQLite(window).on('load', trigger); // fallback to window.onload for others
  2731. // jshint +W064
  2732. }
  2733. },
  2734. toString: function() {
  2735. var value = [];
  2736. forEach(this, function(e) { value.push('' + e);});
  2737. return '[' + value.join(', ') + ']';
  2738. },
  2739. eq: function(index) {
  2740. return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
  2741. },
  2742. length: 0,
  2743. push: push,
  2744. sort: [].sort,
  2745. splice: [].splice
  2746. };
  2747. //////////////////////////////////////////
  2748. // Functions iterating getter/setters.
  2749. // these functions return self on setter and
  2750. // value on get.
  2751. //////////////////////////////////////////
  2752. var BOOLEAN_ATTR = {};
  2753. forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
  2754. BOOLEAN_ATTR[lowercase(value)] = value;
  2755. });
  2756. var BOOLEAN_ELEMENTS = {};
  2757. forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
  2758. BOOLEAN_ELEMENTS[value] = true;
  2759. });
  2760. var ALIASED_ATTR = {
  2761. 'ngMinlength': 'minlength',
  2762. 'ngMaxlength': 'maxlength',
  2763. 'ngMin': 'min',
  2764. 'ngMax': 'max',
  2765. 'ngPattern': 'pattern'
  2766. };
  2767. function getBooleanAttrName(element, name) {
  2768. // check dom last since we will most likely fail on name
  2769. var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
  2770. // booleanAttr is here twice to minimize DOM access
  2771. return booleanAttr && BOOLEAN_ELEMENTS[nodeName_(element)] && booleanAttr;
  2772. }
  2773. function getAliasedAttrName(name) {
  2774. return ALIASED_ATTR[name];
  2775. }
  2776. forEach({
  2777. data: jqLiteData,
  2778. removeData: jqLiteRemoveData,
  2779. hasData: jqLiteHasData
  2780. }, function(fn, name) {
  2781. JQLite[name] = fn;
  2782. });
  2783. forEach({
  2784. data: jqLiteData,
  2785. inheritedData: jqLiteInheritedData,
  2786. scope: function(element) {
  2787. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2788. return jqLite.data(element, '$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
  2789. },
  2790. isolateScope: function(element) {
  2791. // Can't use jqLiteData here directly so we stay compatible with jQuery!
  2792. return jqLite.data(element, '$isolateScope') || jqLite.data(element, '$isolateScopeNoTemplate');
  2793. },
  2794. controller: jqLiteController,
  2795. injector: function(element) {
  2796. return jqLiteInheritedData(element, '$injector');
  2797. },
  2798. removeAttr: function(element, name) {
  2799. element.removeAttribute(name);
  2800. },
  2801. hasClass: jqLiteHasClass,
  2802. css: function(element, name, value) {
  2803. name = camelCase(name);
  2804. if (isDefined(value)) {
  2805. element.style[name] = value;
  2806. } else {
  2807. return element.style[name];
  2808. }
  2809. },
  2810. attr: function(element, name, value) {
  2811. var nodeType = element.nodeType;
  2812. if (nodeType === NODE_TYPE_TEXT || nodeType === NODE_TYPE_ATTRIBUTE || nodeType === NODE_TYPE_COMMENT) {
  2813. return;
  2814. }
  2815. var lowercasedName = lowercase(name);
  2816. if (BOOLEAN_ATTR[lowercasedName]) {
  2817. if (isDefined(value)) {
  2818. if (!!value) {
  2819. element[name] = true;
  2820. element.setAttribute(name, lowercasedName);
  2821. } else {
  2822. element[name] = false;
  2823. element.removeAttribute(lowercasedName);
  2824. }
  2825. } else {
  2826. return (element[name] ||
  2827. (element.attributes.getNamedItem(name) || noop).specified)
  2828. ? lowercasedName
  2829. : undefined;
  2830. }
  2831. } else if (isDefined(value)) {
  2832. element.setAttribute(name, value);
  2833. } else if (element.getAttribute) {
  2834. // the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
  2835. // some elements (e.g. Document) don't have get attribute, so return undefined
  2836. var ret = element.getAttribute(name, 2);
  2837. // normalize non-existing attributes to undefined (as jQuery)
  2838. return ret === null ? undefined : ret;
  2839. }
  2840. },
  2841. prop: function(element, name, value) {
  2842. if (isDefined(value)) {
  2843. element[name] = value;
  2844. } else {
  2845. return element[name];
  2846. }
  2847. },
  2848. text: (function() {
  2849. getText.$dv = '';
  2850. return getText;
  2851. function getText(element, value) {
  2852. if (isUndefined(value)) {
  2853. var nodeType = element.nodeType;
  2854. return (nodeType === NODE_TYPE_ELEMENT || nodeType === NODE_TYPE_TEXT) ? element.textContent : '';
  2855. }
  2856. element.textContent = value;
  2857. }
  2858. })(),
  2859. val: function(element, value) {
  2860. if (isUndefined(value)) {
  2861. if (element.multiple && nodeName_(element) === 'select') {
  2862. var result = [];
  2863. forEach(element.options, function(option) {
  2864. if (option.selected) {
  2865. result.push(option.value || option.text);
  2866. }
  2867. });
  2868. return result.length === 0 ? null : result;
  2869. }
  2870. return element.value;
  2871. }
  2872. element.value = value;
  2873. },
  2874. html: function(element, value) {
  2875. if (isUndefined(value)) {
  2876. return element.innerHTML;
  2877. }
  2878. jqLiteDealoc(element, true);
  2879. element.innerHTML = value;
  2880. },
  2881. empty: jqLiteEmpty
  2882. }, function(fn, name) {
  2883. /**
  2884. * Properties: writes return selection, reads return first value
  2885. */
  2886. JQLite.prototype[name] = function(arg1, arg2) {
  2887. var i, key;
  2888. var nodeCount = this.length;
  2889. // jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
  2890. // in a way that survives minification.
  2891. // jqLiteEmpty takes no arguments but is a setter.
  2892. if (fn !== jqLiteEmpty &&
  2893. (isUndefined((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2))) {
  2894. if (isObject(arg1)) {
  2895. // we are a write, but the object properties are the key/values
  2896. for (i = 0; i < nodeCount; i++) {
  2897. if (fn === jqLiteData) {
  2898. // data() takes the whole object in jQuery
  2899. fn(this[i], arg1);
  2900. } else {
  2901. for (key in arg1) {
  2902. fn(this[i], key, arg1[key]);
  2903. }
  2904. }
  2905. }
  2906. // return self for chaining
  2907. return this;
  2908. } else {
  2909. // we are a read, so read the first child.
  2910. // TODO: do we still need this?
  2911. var value = fn.$dv;
  2912. // Only if we have $dv do we iterate over all, otherwise it is just the first element.
  2913. var jj = (isUndefined(value)) ? Math.min(nodeCount, 1) : nodeCount;
  2914. for (var j = 0; j < jj; j++) {
  2915. var nodeValue = fn(this[j], arg1, arg2);
  2916. value = value ? value + nodeValue : nodeValue;
  2917. }
  2918. return value;
  2919. }
  2920. } else {
  2921. // we are a write, so apply to all children
  2922. for (i = 0; i < nodeCount; i++) {
  2923. fn(this[i], arg1, arg2);
  2924. }
  2925. // return self for chaining
  2926. return this;
  2927. }
  2928. };
  2929. });
  2930. function createEventHandler(element, events) {
  2931. var eventHandler = function(event, type) {
  2932. // jQuery specific api
  2933. event.isDefaultPrevented = function() {
  2934. return event.defaultPrevented;
  2935. };
  2936. var eventFns = events[type || event.type];
  2937. var eventFnsLength = eventFns ? eventFns.length : 0;
  2938. if (!eventFnsLength) return;
  2939. if (isUndefined(event.immediatePropagationStopped)) {
  2940. var originalStopImmediatePropagation = event.stopImmediatePropagation;
  2941. event.stopImmediatePropagation = function() {
  2942. event.immediatePropagationStopped = true;
  2943. if (event.stopPropagation) {
  2944. event.stopPropagation();
  2945. }
  2946. if (originalStopImmediatePropagation) {
  2947. originalStopImmediatePropagation.call(event);
  2948. }
  2949. };
  2950. }
  2951. event.isImmediatePropagationStopped = function() {
  2952. return event.immediatePropagationStopped === true;
  2953. };
  2954. // Some events have special handlers that wrap the real handler
  2955. var handlerWrapper = eventFns.specialHandlerWrapper || defaultHandlerWrapper;
  2956. // Copy event handlers in case event handlers array is modified during execution.
  2957. if ((eventFnsLength > 1)) {
  2958. eventFns = shallowCopy(eventFns);
  2959. }
  2960. for (var i = 0; i < eventFnsLength; i++) {
  2961. if (!event.isImmediatePropagationStopped()) {
  2962. handlerWrapper(element, event, eventFns[i]);
  2963. }
  2964. }
  2965. };
  2966. // TODO: this is a hack for angularMocks/clearDataCache that makes it possible to deregister all
  2967. // events on `element`
  2968. eventHandler.elem = element;
  2969. return eventHandler;
  2970. }
  2971. function defaultHandlerWrapper(element, event, handler) {
  2972. handler.call(element, event);
  2973. }
  2974. function specialMouseHandlerWrapper(target, event, handler) {
  2975. // Refer to jQuery's implementation of mouseenter & mouseleave
  2976. // Read about mouseenter and mouseleave:
  2977. // http://www.quirksmode.org/js/events_mouse.html#link8
  2978. var related = event.relatedTarget;
  2979. // For mousenter/leave call the handler if related is outside the target.
  2980. // NB: No relatedTarget if the mouse left/entered the browser window
  2981. if (!related || (related !== target && !jqLiteContains.call(target, related))) {
  2982. handler.call(target, event);
  2983. }
  2984. }
  2985. //////////////////////////////////////////
  2986. // Functions iterating traversal.
  2987. // These functions chain results into a single
  2988. // selector.
  2989. //////////////////////////////////////////
  2990. forEach({
  2991. removeData: jqLiteRemoveData,
  2992. on: function jqLiteOn(element, type, fn, unsupported) {
  2993. if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
  2994. // Do not add event handlers to non-elements because they will not be cleaned up.
  2995. if (!jqLiteAcceptsData(element)) {
  2996. return;
  2997. }
  2998. var expandoStore = jqLiteExpandoStore(element, true);
  2999. var events = expandoStore.events;
  3000. var handle = expandoStore.handle;
  3001. if (!handle) {
  3002. handle = expandoStore.handle = createEventHandler(element, events);
  3003. }
  3004. // http://jsperf.com/string-indexof-vs-split
  3005. var types = type.indexOf(' ') >= 0 ? type.split(' ') : [type];
  3006. var i = types.length;
  3007. var addHandler = function(type, specialHandlerWrapper, noEventListener) {
  3008. var eventFns = events[type];
  3009. if (!eventFns) {
  3010. eventFns = events[type] = [];
  3011. eventFns.specialHandlerWrapper = specialHandlerWrapper;
  3012. if (type !== '$destroy' && !noEventListener) {
  3013. addEventListenerFn(element, type, handle);
  3014. }
  3015. }
  3016. eventFns.push(fn);
  3017. };
  3018. while (i--) {
  3019. type = types[i];
  3020. if (MOUSE_EVENT_MAP[type]) {
  3021. addHandler(MOUSE_EVENT_MAP[type], specialMouseHandlerWrapper);
  3022. addHandler(type, undefined, true);
  3023. } else {
  3024. addHandler(type);
  3025. }
  3026. }
  3027. },
  3028. off: jqLiteOff,
  3029. one: function(element, type, fn) {
  3030. element = jqLite(element);
  3031. //add the listener twice so that when it is called
  3032. //you can remove the original function and still be
  3033. //able to call element.off(ev, fn) normally
  3034. element.on(type, function onFn() {
  3035. element.off(type, fn);
  3036. element.off(type, onFn);
  3037. });
  3038. element.on(type, fn);
  3039. },
  3040. replaceWith: function(element, replaceNode) {
  3041. var index, parent = element.parentNode;
  3042. jqLiteDealoc(element);
  3043. forEach(new JQLite(replaceNode), function(node) {
  3044. if (index) {
  3045. parent.insertBefore(node, index.nextSibling);
  3046. } else {
  3047. parent.replaceChild(node, element);
  3048. }
  3049. index = node;
  3050. });
  3051. },
  3052. children: function(element) {
  3053. var children = [];
  3054. forEach(element.childNodes, function(element) {
  3055. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3056. children.push(element);
  3057. }
  3058. });
  3059. return children;
  3060. },
  3061. contents: function(element) {
  3062. return element.contentDocument || element.childNodes || [];
  3063. },
  3064. append: function(element, node) {
  3065. var nodeType = element.nodeType;
  3066. if (nodeType !== NODE_TYPE_ELEMENT && nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT) return;
  3067. node = new JQLite(node);
  3068. for (var i = 0, ii = node.length; i < ii; i++) {
  3069. var child = node[i];
  3070. element.appendChild(child);
  3071. }
  3072. },
  3073. prepend: function(element, node) {
  3074. if (element.nodeType === NODE_TYPE_ELEMENT) {
  3075. var index = element.firstChild;
  3076. forEach(new JQLite(node), function(child) {
  3077. element.insertBefore(child, index);
  3078. });
  3079. }
  3080. },
  3081. wrap: function(element, wrapNode) {
  3082. wrapNode = jqLite(wrapNode).eq(0).clone()[0];
  3083. var parent = element.parentNode;
  3084. if (parent) {
  3085. parent.replaceChild(wrapNode, element);
  3086. }
  3087. wrapNode.appendChild(element);
  3088. },
  3089. remove: jqLiteRemove,
  3090. detach: function(element) {
  3091. jqLiteRemove(element, true);
  3092. },
  3093. after: function(element, newElement) {
  3094. var index = element, parent = element.parentNode;
  3095. newElement = new JQLite(newElement);
  3096. for (var i = 0, ii = newElement.length; i < ii; i++) {
  3097. var node = newElement[i];
  3098. parent.insertBefore(node, index.nextSibling);
  3099. index = node;
  3100. }
  3101. },
  3102. addClass: jqLiteAddClass,
  3103. removeClass: jqLiteRemoveClass,
  3104. toggleClass: function(element, selector, condition) {
  3105. if (selector) {
  3106. forEach(selector.split(' '), function(className) {
  3107. var classCondition = condition;
  3108. if (isUndefined(classCondition)) {
  3109. classCondition = !jqLiteHasClass(element, className);
  3110. }
  3111. (classCondition ? jqLiteAddClass : jqLiteRemoveClass)(element, className);
  3112. });
  3113. }
  3114. },
  3115. parent: function(element) {
  3116. var parent = element.parentNode;
  3117. return parent && parent.nodeType !== NODE_TYPE_DOCUMENT_FRAGMENT ? parent : null;
  3118. },
  3119. next: function(element) {
  3120. return element.nextElementSibling;
  3121. },
  3122. find: function(element, selector) {
  3123. if (element.getElementsByTagName) {
  3124. return element.getElementsByTagName(selector);
  3125. } else {
  3126. return [];
  3127. }
  3128. },
  3129. clone: jqLiteClone,
  3130. triggerHandler: function(element, event, extraParameters) {
  3131. var dummyEvent, eventFnsCopy, handlerArgs;
  3132. var eventName = event.type || event;
  3133. var expandoStore = jqLiteExpandoStore(element);
  3134. var events = expandoStore && expandoStore.events;
  3135. var eventFns = events && events[eventName];
  3136. if (eventFns) {
  3137. // Create a dummy event to pass to the handlers
  3138. dummyEvent = {
  3139. preventDefault: function() { this.defaultPrevented = true; },
  3140. isDefaultPrevented: function() { return this.defaultPrevented === true; },
  3141. stopImmediatePropagation: function() { this.immediatePropagationStopped = true; },
  3142. isImmediatePropagationStopped: function() { return this.immediatePropagationStopped === true; },
  3143. stopPropagation: noop,
  3144. type: eventName,
  3145. target: element
  3146. };
  3147. // If a custom event was provided then extend our dummy event with it
  3148. if (event.type) {
  3149. dummyEvent = extend(dummyEvent, event);
  3150. }
  3151. // Copy event handlers in case event handlers array is modified during execution.
  3152. eventFnsCopy = shallowCopy(eventFns);
  3153. handlerArgs = extraParameters ? [dummyEvent].concat(extraParameters) : [dummyEvent];
  3154. forEach(eventFnsCopy, function(fn) {
  3155. if (!dummyEvent.isImmediatePropagationStopped()) {
  3156. fn.apply(element, handlerArgs);
  3157. }
  3158. });
  3159. }
  3160. }
  3161. }, function(fn, name) {
  3162. /**
  3163. * chaining functions
  3164. */
  3165. JQLite.prototype[name] = function(arg1, arg2, arg3) {
  3166. var value;
  3167. for (var i = 0, ii = this.length; i < ii; i++) {
  3168. if (isUndefined(value)) {
  3169. value = fn(this[i], arg1, arg2, arg3);
  3170. if (isDefined(value)) {
  3171. // any function which returns a value needs to be wrapped
  3172. value = jqLite(value);
  3173. }
  3174. } else {
  3175. jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
  3176. }
  3177. }
  3178. return isDefined(value) ? value : this;
  3179. };
  3180. // bind legacy bind/unbind to on/off
  3181. JQLite.prototype.bind = JQLite.prototype.on;
  3182. JQLite.prototype.unbind = JQLite.prototype.off;
  3183. });
  3184. // Provider for private $$jqLite service
  3185. function $$jqLiteProvider() {
  3186. this.$get = function $$jqLite() {
  3187. return extend(JQLite, {
  3188. hasClass: function(node, classes) {
  3189. if (node.attr) node = node[0];
  3190. return jqLiteHasClass(node, classes);
  3191. },
  3192. addClass: function(node, classes) {
  3193. if (node.attr) node = node[0];
  3194. return jqLiteAddClass(node, classes);
  3195. },
  3196. removeClass: function(node, classes) {
  3197. if (node.attr) node = node[0];
  3198. return jqLiteRemoveClass(node, classes);
  3199. }
  3200. });
  3201. };
  3202. }
  3203. /**
  3204. * Computes a hash of an 'obj'.
  3205. * Hash of a:
  3206. * string is string
  3207. * number is number as string
  3208. * object is either result of calling $$hashKey function on the object or uniquely generated id,
  3209. * that is also assigned to the $$hashKey property of the object.
  3210. *
  3211. * @param obj
  3212. * @returns {string} hash string such that the same input will have the same hash string.
  3213. * The resulting string key is in 'type:hashKey' format.
  3214. */
  3215. function hashKey(obj, nextUidFn) {
  3216. var key = obj && obj.$$hashKey;
  3217. if (key) {
  3218. if (typeof key === 'function') {
  3219. key = obj.$$hashKey();
  3220. }
  3221. return key;
  3222. }
  3223. var objType = typeof obj;
  3224. if (objType == 'function' || (objType == 'object' && obj !== null)) {
  3225. key = obj.$$hashKey = objType + ':' + (nextUidFn || nextUid)();
  3226. } else {
  3227. key = objType + ':' + obj;
  3228. }
  3229. return key;
  3230. }
  3231. /**
  3232. * HashMap which can use objects as keys
  3233. */
  3234. function HashMap(array, isolatedUid) {
  3235. if (isolatedUid) {
  3236. var uid = 0;
  3237. this.nextUid = function() {
  3238. return ++uid;
  3239. };
  3240. }
  3241. forEach(array, this.put, this);
  3242. }
  3243. HashMap.prototype = {
  3244. /**
  3245. * Store key value pair
  3246. * @param key key to store can be any type
  3247. * @param value value to store can be any type
  3248. */
  3249. put: function(key, value) {
  3250. this[hashKey(key, this.nextUid)] = value;
  3251. },
  3252. /**
  3253. * @param key
  3254. * @returns {Object} the value for the key
  3255. */
  3256. get: function(key) {
  3257. return this[hashKey(key, this.nextUid)];
  3258. },
  3259. /**
  3260. * Remove the key/value pair
  3261. * @param key
  3262. */
  3263. remove: function(key) {
  3264. var value = this[key = hashKey(key, this.nextUid)];
  3265. delete this[key];
  3266. return value;
  3267. }
  3268. };
  3269. var $$HashMapProvider = [function() {
  3270. this.$get = [function() {
  3271. return HashMap;
  3272. }];
  3273. }];
  3274. /**
  3275. * @ngdoc function
  3276. * @module ng
  3277. * @name angular.injector
  3278. * @kind function
  3279. *
  3280. * @description
  3281. * Creates an injector object that can be used for retrieving services as well as for
  3282. * dependency injection (see {@link guide/di dependency injection}).
  3283. *
  3284. * @param {Array.<string|Function>} modules A list of module functions or their aliases. See
  3285. * {@link angular.module}. The `ng` module must be explicitly added.
  3286. * @param {boolean=} [strictDi=false] Whether the injector should be in strict mode, which
  3287. * disallows argument name annotation inference.
  3288. * @returns {injector} Injector object. See {@link auto.$injector $injector}.
  3289. *
  3290. * @example
  3291. * Typical usage
  3292. * ```js
  3293. * // create an injector
  3294. * var $injector = angular.injector(['ng']);
  3295. *
  3296. * // use the injector to kick off your application
  3297. * // use the type inference to auto inject arguments, or use implicit injection
  3298. * $injector.invoke(function($rootScope, $compile, $document) {
  3299. * $compile($document)($rootScope);
  3300. * $rootScope.$digest();
  3301. * });
  3302. * ```
  3303. *
  3304. * Sometimes you want to get access to the injector of a currently running Angular app
  3305. * from outside Angular. Perhaps, you want to inject and compile some markup after the
  3306. * application has been bootstrapped. You can do this using the extra `injector()` added
  3307. * to JQuery/jqLite elements. See {@link angular.element}.
  3308. *
  3309. * *This is fairly rare but could be the case if a third party library is injecting the
  3310. * markup.*
  3311. *
  3312. * In the following example a new block of HTML containing a `ng-controller`
  3313. * directive is added to the end of the document body by JQuery. We then compile and link
  3314. * it into the current AngularJS scope.
  3315. *
  3316. * ```js
  3317. * var $div = $('<div ng-controller="MyCtrl">{{content.label}}</div>');
  3318. * $(document.body).append($div);
  3319. *
  3320. * angular.element(document).injector().invoke(function($compile) {
  3321. * var scope = angular.element($div).scope();
  3322. * $compile($div)(scope);
  3323. * });
  3324. * ```
  3325. */
  3326. /**
  3327. * @ngdoc module
  3328. * @name auto
  3329. * @description
  3330. *
  3331. * Implicit module which gets automatically added to each {@link auto.$injector $injector}.
  3332. */
  3333. var FN_ARGS = /^[^\(]*\(\s*([^\)]*)\)/m;
  3334. var FN_ARG_SPLIT = /,/;
  3335. var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
  3336. var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
  3337. var $injectorMinErr = minErr('$injector');
  3338. function anonFn(fn) {
  3339. // For anonymous functions, showing at the very least the function signature can help in
  3340. // debugging.
  3341. var fnText = fn.toString().replace(STRIP_COMMENTS, ''),
  3342. args = fnText.match(FN_ARGS);
  3343. if (args) {
  3344. return 'function(' + (args[1] || '').replace(/[\s\r\n]+/, ' ') + ')';
  3345. }
  3346. return 'fn';
  3347. }
  3348. function annotate(fn, strictDi, name) {
  3349. var $inject,
  3350. fnText,
  3351. argDecl,
  3352. last;
  3353. if (typeof fn === 'function') {
  3354. if (!($inject = fn.$inject)) {
  3355. $inject = [];
  3356. if (fn.length) {
  3357. if (strictDi) {
  3358. if (!isString(name) || !name) {
  3359. name = fn.name || anonFn(fn);
  3360. }
  3361. throw $injectorMinErr('strictdi',
  3362. '{0} is not using explicit annotation and cannot be invoked in strict mode', name);
  3363. }
  3364. fnText = fn.toString().replace(STRIP_COMMENTS, '');
  3365. argDecl = fnText.match(FN_ARGS);
  3366. forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg) {
  3367. arg.replace(FN_ARG, function(all, underscore, name) {
  3368. $inject.push(name);
  3369. });
  3370. });
  3371. }
  3372. fn.$inject = $inject;
  3373. }
  3374. } else if (isArray(fn)) {
  3375. last = fn.length - 1;
  3376. assertArgFn(fn[last], 'fn');
  3377. $inject = fn.slice(0, last);
  3378. } else {
  3379. assertArgFn(fn, 'fn', true);
  3380. }
  3381. return $inject;
  3382. }
  3383. ///////////////////////////////////////
  3384. /**
  3385. * @ngdoc service
  3386. * @name $injector
  3387. *
  3388. * @description
  3389. *
  3390. * `$injector` is used to retrieve object instances as defined by
  3391. * {@link auto.$provide provider}, instantiate types, invoke methods,
  3392. * and load modules.
  3393. *
  3394. * The following always holds true:
  3395. *
  3396. * ```js
  3397. * var $injector = angular.injector();
  3398. * expect($injector.get('$injector')).toBe($injector);
  3399. * expect($injector.invoke(function($injector) {
  3400. * return $injector;
  3401. * })).toBe($injector);
  3402. * ```
  3403. *
  3404. * # Injection Function Annotation
  3405. *
  3406. * JavaScript does not have annotations, and annotations are needed for dependency injection. The
  3407. * following are all valid ways of annotating function with injection arguments and are equivalent.
  3408. *
  3409. * ```js
  3410. * // inferred (only works if code not minified/obfuscated)
  3411. * $injector.invoke(function(serviceA){});
  3412. *
  3413. * // annotated
  3414. * function explicit(serviceA) {};
  3415. * explicit.$inject = ['serviceA'];
  3416. * $injector.invoke(explicit);
  3417. *
  3418. * // inline
  3419. * $injector.invoke(['serviceA', function(serviceA){}]);
  3420. * ```
  3421. *
  3422. * ## Inference
  3423. *
  3424. * In JavaScript calling `toString()` on a function returns the function definition. The definition
  3425. * can then be parsed and the function arguments can be extracted. This method of discovering
  3426. * annotations is disallowed when the injector is in strict mode.
  3427. * *NOTE:* This does not work with minification, and obfuscation tools since these tools change the
  3428. * argument names.
  3429. *
  3430. * ## `$inject` Annotation
  3431. * By adding an `$inject` property onto a function the injection parameters can be specified.
  3432. *
  3433. * ## Inline
  3434. * As an array of injection names, where the last item in the array is the function to call.
  3435. */
  3436. /**
  3437. * @ngdoc method
  3438. * @name $injector#get
  3439. *
  3440. * @description
  3441. * Return an instance of the service.
  3442. *
  3443. * @param {string} name The name of the instance to retrieve.
  3444. * @param {string=} caller An optional string to provide the origin of the function call for error messages.
  3445. * @return {*} The instance.
  3446. */
  3447. /**
  3448. * @ngdoc method
  3449. * @name $injector#invoke
  3450. *
  3451. * @description
  3452. * Invoke the method and supply the method arguments from the `$injector`.
  3453. *
  3454. * @param {Function|Array.<string|Function>} fn The injectable function to invoke. Function parameters are
  3455. * injected according to the {@link guide/di $inject Annotation} rules.
  3456. * @param {Object=} self The `this` for the invoked method.
  3457. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3458. * object first, before the `$injector` is consulted.
  3459. * @returns {*} the value returned by the invoked `fn` function.
  3460. */
  3461. /**
  3462. * @ngdoc method
  3463. * @name $injector#has
  3464. *
  3465. * @description
  3466. * Allows the user to query if the particular service exists.
  3467. *
  3468. * @param {string} name Name of the service to query.
  3469. * @returns {boolean} `true` if injector has given service.
  3470. */
  3471. /**
  3472. * @ngdoc method
  3473. * @name $injector#instantiate
  3474. * @description
  3475. * Create a new instance of JS type. The method takes a constructor function, invokes the new
  3476. * operator, and supplies all of the arguments to the constructor function as specified by the
  3477. * constructor annotation.
  3478. *
  3479. * @param {Function} Type Annotated constructor function.
  3480. * @param {Object=} locals Optional object. If preset then any argument names are read from this
  3481. * object first, before the `$injector` is consulted.
  3482. * @returns {Object} new instance of `Type`.
  3483. */
  3484. /**
  3485. * @ngdoc method
  3486. * @name $injector#annotate
  3487. *
  3488. * @description
  3489. * Returns an array of service names which the function is requesting for injection. This API is
  3490. * used by the injector to determine which services need to be injected into the function when the
  3491. * function is invoked. There are three ways in which the function can be annotated with the needed
  3492. * dependencies.
  3493. *
  3494. * # Argument names
  3495. *
  3496. * The simplest form is to extract the dependencies from the arguments of the function. This is done
  3497. * by converting the function into a string using `toString()` method and extracting the argument
  3498. * names.
  3499. * ```js
  3500. * // Given
  3501. * function MyController($scope, $route) {
  3502. * // ...
  3503. * }
  3504. *
  3505. * // Then
  3506. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3507. * ```
  3508. *
  3509. * You can disallow this method by using strict injection mode.
  3510. *
  3511. * This method does not work with code minification / obfuscation. For this reason the following
  3512. * annotation strategies are supported.
  3513. *
  3514. * # The `$inject` property
  3515. *
  3516. * If a function has an `$inject` property and its value is an array of strings, then the strings
  3517. * represent names of services to be injected into the function.
  3518. * ```js
  3519. * // Given
  3520. * var MyController = function(obfuscatedScope, obfuscatedRoute) {
  3521. * // ...
  3522. * }
  3523. * // Define function dependencies
  3524. * MyController['$inject'] = ['$scope', '$route'];
  3525. *
  3526. * // Then
  3527. * expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
  3528. * ```
  3529. *
  3530. * # The array notation
  3531. *
  3532. * It is often desirable to inline Injected functions and that's when setting the `$inject` property
  3533. * is very inconvenient. In these situations using the array notation to specify the dependencies in
  3534. * a way that survives minification is a better choice:
  3535. *
  3536. * ```js
  3537. * // We wish to write this (not minification / obfuscation safe)
  3538. * injector.invoke(function($compile, $rootScope) {
  3539. * // ...
  3540. * });
  3541. *
  3542. * // We are forced to write break inlining
  3543. * var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
  3544. * // ...
  3545. * };
  3546. * tmpFn.$inject = ['$compile', '$rootScope'];
  3547. * injector.invoke(tmpFn);
  3548. *
  3549. * // To better support inline function the inline annotation is supported
  3550. * injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
  3551. * // ...
  3552. * }]);
  3553. *
  3554. * // Therefore
  3555. * expect(injector.annotate(
  3556. * ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
  3557. * ).toEqual(['$compile', '$rootScope']);
  3558. * ```
  3559. *
  3560. * @param {Function|Array.<string|Function>} fn Function for which dependent service names need to
  3561. * be retrieved as described above.
  3562. *
  3563. * @param {boolean=} [strictDi=false] Disallow argument name annotation inference.
  3564. *
  3565. * @returns {Array.<string>} The names of the services which the function requires.
  3566. */
  3567. /**
  3568. * @ngdoc service
  3569. * @name $provide
  3570. *
  3571. * @description
  3572. *
  3573. * The {@link auto.$provide $provide} service has a number of methods for registering components
  3574. * with the {@link auto.$injector $injector}. Many of these functions are also exposed on
  3575. * {@link angular.Module}.
  3576. *
  3577. * An Angular **service** is a singleton object created by a **service factory**. These **service
  3578. * factories** are functions which, in turn, are created by a **service provider**.
  3579. * The **service providers** are constructor functions. When instantiated they must contain a
  3580. * property called `$get`, which holds the **service factory** function.
  3581. *
  3582. * When you request a service, the {@link auto.$injector $injector} is responsible for finding the
  3583. * correct **service provider**, instantiating it and then calling its `$get` **service factory**
  3584. * function to get the instance of the **service**.
  3585. *
  3586. * Often services have no configuration options and there is no need to add methods to the service
  3587. * provider. The provider will be no more than a constructor function with a `$get` property. For
  3588. * these cases the {@link auto.$provide $provide} service has additional helper methods to register
  3589. * services without specifying a provider.
  3590. *
  3591. * * {@link auto.$provide#provider provider(provider)} - registers a **service provider** with the
  3592. * {@link auto.$injector $injector}
  3593. * * {@link auto.$provide#constant constant(obj)} - registers a value/object that can be accessed by
  3594. * providers and services.
  3595. * * {@link auto.$provide#value value(obj)} - registers a value/object that can only be accessed by
  3596. * services, not providers.
  3597. * * {@link auto.$provide#factory factory(fn)} - registers a service **factory function**, `fn`,
  3598. * that will be wrapped in a **service provider** object, whose `$get` property will contain the
  3599. * given factory function.
  3600. * * {@link auto.$provide#service service(class)} - registers a **constructor function**, `class`
  3601. * that will be wrapped in a **service provider** object, whose `$get` property will instantiate
  3602. * a new object using the given constructor function.
  3603. *
  3604. * See the individual methods for more information and examples.
  3605. */
  3606. /**
  3607. * @ngdoc method
  3608. * @name $provide#provider
  3609. * @description
  3610. *
  3611. * Register a **provider function** with the {@link auto.$injector $injector}. Provider functions
  3612. * are constructor functions, whose instances are responsible for "providing" a factory for a
  3613. * service.
  3614. *
  3615. * Service provider names start with the name of the service they provide followed by `Provider`.
  3616. * For example, the {@link ng.$log $log} service has a provider called
  3617. * {@link ng.$logProvider $logProvider}.
  3618. *
  3619. * Service provider objects can have additional methods which allow configuration of the provider
  3620. * and its service. Importantly, you can configure what kind of service is created by the `$get`
  3621. * method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
  3622. * method {@link ng.$logProvider#debugEnabled debugEnabled}
  3623. * which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
  3624. * console or not.
  3625. *
  3626. * @param {string} name The name of the instance. NOTE: the provider will be available under `name +
  3627. 'Provider'` key.
  3628. * @param {(Object|function())} provider If the provider is:
  3629. *
  3630. * - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
  3631. * {@link auto.$injector#invoke $injector.invoke()} when an instance needs to be created.
  3632. * - `Constructor`: a new instance of the provider will be created using
  3633. * {@link auto.$injector#instantiate $injector.instantiate()}, then treated as `object`.
  3634. *
  3635. * @returns {Object} registered provider instance
  3636. * @example
  3637. *
  3638. * The following example shows how to create a simple event tracking service and register it using
  3639. * {@link auto.$provide#provider $provide.provider()}.
  3640. *
  3641. * ```js
  3642. * // Define the eventTracker provider
  3643. * function EventTrackerProvider() {
  3644. * var trackingUrl = '/track';
  3645. *
  3646. * // A provider method for configuring where the tracked events should been saved
  3647. * this.setTrackingUrl = function(url) {
  3648. * trackingUrl = url;
  3649. * };
  3650. *
  3651. * // The service factory function
  3652. * this.$get = ['$http', function($http) {
  3653. * var trackedEvents = {};
  3654. * return {
  3655. * // Call this to track an event
  3656. * event: function(event) {
  3657. * var count = trackedEvents[event] || 0;
  3658. * count += 1;
  3659. * trackedEvents[event] = count;
  3660. * return count;
  3661. * },
  3662. * // Call this to save the tracked events to the trackingUrl
  3663. * save: function() {
  3664. * $http.post(trackingUrl, trackedEvents);
  3665. * }
  3666. * };
  3667. * }];
  3668. * }
  3669. *
  3670. * describe('eventTracker', function() {
  3671. * var postSpy;
  3672. *
  3673. * beforeEach(module(function($provide) {
  3674. * // Register the eventTracker provider
  3675. * $provide.provider('eventTracker', EventTrackerProvider);
  3676. * }));
  3677. *
  3678. * beforeEach(module(function(eventTrackerProvider) {
  3679. * // Configure eventTracker provider
  3680. * eventTrackerProvider.setTrackingUrl('/custom-track');
  3681. * }));
  3682. *
  3683. * it('tracks events', inject(function(eventTracker) {
  3684. * expect(eventTracker.event('login')).toEqual(1);
  3685. * expect(eventTracker.event('login')).toEqual(2);
  3686. * }));
  3687. *
  3688. * it('saves to the tracking url', inject(function(eventTracker, $http) {
  3689. * postSpy = spyOn($http, 'post');
  3690. * eventTracker.event('login');
  3691. * eventTracker.save();
  3692. * expect(postSpy).toHaveBeenCalled();
  3693. * expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
  3694. * expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
  3695. * expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
  3696. * }));
  3697. * });
  3698. * ```
  3699. */
  3700. /**
  3701. * @ngdoc method
  3702. * @name $provide#factory
  3703. * @description
  3704. *
  3705. * Register a **service factory**, which will be called to return the service instance.
  3706. * This is short for registering a service where its provider consists of only a `$get` property,
  3707. * which is the given service factory function.
  3708. * You should use {@link auto.$provide#factory $provide.factory(getFn)} if you do not need to
  3709. * configure your service in a provider.
  3710. *
  3711. * @param {string} name The name of the instance.
  3712. * @param {Function|Array.<string|Function>} $getFn The injectable $getFn for the instance creation.
  3713. * Internally this is a short hand for `$provide.provider(name, {$get: $getFn})`.
  3714. * @returns {Object} registered provider instance
  3715. *
  3716. * @example
  3717. * Here is an example of registering a service
  3718. * ```js
  3719. * $provide.factory('ping', ['$http', function($http) {
  3720. * return function ping() {
  3721. * return $http.send('/ping');
  3722. * };
  3723. * }]);
  3724. * ```
  3725. * You would then inject and use this service like this:
  3726. * ```js
  3727. * someModule.controller('Ctrl', ['ping', function(ping) {
  3728. * ping();
  3729. * }]);
  3730. * ```
  3731. */
  3732. /**
  3733. * @ngdoc method
  3734. * @name $provide#service
  3735. * @description
  3736. *
  3737. * Register a **service constructor**, which will be invoked with `new` to create the service
  3738. * instance.
  3739. * This is short for registering a service where its provider's `$get` property is the service
  3740. * constructor function that will be used to instantiate the service instance.
  3741. *
  3742. * You should use {@link auto.$provide#service $provide.service(class)} if you define your service
  3743. * as a type/class.
  3744. *
  3745. * @param {string} name The name of the instance.
  3746. * @param {Function|Array.<string|Function>} constructor An injectable class (constructor function)
  3747. * that will be instantiated.
  3748. * @returns {Object} registered provider instance
  3749. *
  3750. * @example
  3751. * Here is an example of registering a service using
  3752. * {@link auto.$provide#service $provide.service(class)}.
  3753. * ```js
  3754. * var Ping = function($http) {
  3755. * this.$http = $http;
  3756. * };
  3757. *
  3758. * Ping.$inject = ['$http'];
  3759. *
  3760. * Ping.prototype.send = function() {
  3761. * return this.$http.get('/ping');
  3762. * };
  3763. * $provide.service('ping', Ping);
  3764. * ```
  3765. * You would then inject and use this service like this:
  3766. * ```js
  3767. * someModule.controller('Ctrl', ['ping', function(ping) {
  3768. * ping.send();
  3769. * }]);
  3770. * ```
  3771. */
  3772. /**
  3773. * @ngdoc method
  3774. * @name $provide#value
  3775. * @description
  3776. *
  3777. * Register a **value service** with the {@link auto.$injector $injector}, such as a string, a
  3778. * number, an array, an object or a function. This is short for registering a service where its
  3779. * provider's `$get` property is a factory function that takes no arguments and returns the **value
  3780. * service**.
  3781. *
  3782. * Value services are similar to constant services, except that they cannot be injected into a
  3783. * module configuration function (see {@link angular.Module#config}) but they can be overridden by
  3784. * an Angular
  3785. * {@link auto.$provide#decorator decorator}.
  3786. *
  3787. * @param {string} name The name of the instance.
  3788. * @param {*} value The value.
  3789. * @returns {Object} registered provider instance
  3790. *
  3791. * @example
  3792. * Here are some examples of creating value services.
  3793. * ```js
  3794. * $provide.value('ADMIN_USER', 'admin');
  3795. *
  3796. * $provide.value('RoleLookup', { admin: 0, writer: 1, reader: 2 });
  3797. *
  3798. * $provide.value('halfOf', function(value) {
  3799. * return value / 2;
  3800. * });
  3801. * ```
  3802. */
  3803. /**
  3804. * @ngdoc method
  3805. * @name $provide#constant
  3806. * @description
  3807. *
  3808. * Register a **constant service**, such as a string, a number, an array, an object or a function,
  3809. * with the {@link auto.$injector $injector}. Unlike {@link auto.$provide#value value} it can be
  3810. * injected into a module configuration function (see {@link angular.Module#config}) and it cannot
  3811. * be overridden by an Angular {@link auto.$provide#decorator decorator}.
  3812. *
  3813. * @param {string} name The name of the constant.
  3814. * @param {*} value The constant value.
  3815. * @returns {Object} registered instance
  3816. *
  3817. * @example
  3818. * Here a some examples of creating constants:
  3819. * ```js
  3820. * $provide.constant('SHARD_HEIGHT', 306);
  3821. *
  3822. * $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
  3823. *
  3824. * $provide.constant('double', function(value) {
  3825. * return value * 2;
  3826. * });
  3827. * ```
  3828. */
  3829. /**
  3830. * @ngdoc method
  3831. * @name $provide#decorator
  3832. * @description
  3833. *
  3834. * Register a **service decorator** with the {@link auto.$injector $injector}. A service decorator
  3835. * intercepts the creation of a service, allowing it to override or modify the behaviour of the
  3836. * service. The object returned by the decorator may be the original service, or a new service
  3837. * object which replaces or wraps and delegates to the original service.
  3838. *
  3839. * @param {string} name The name of the service to decorate.
  3840. * @param {Function|Array.<string|Function>} decorator This function will be invoked when the service needs to be
  3841. * instantiated and should return the decorated service instance. The function is called using
  3842. * the {@link auto.$injector#invoke injector.invoke} method and is therefore fully injectable.
  3843. * Local injection arguments:
  3844. *
  3845. * * `$delegate` - The original service instance, which can be monkey patched, configured,
  3846. * decorated or delegated to.
  3847. *
  3848. * @example
  3849. * Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
  3850. * calls to {@link ng.$log#error $log.warn()}.
  3851. * ```js
  3852. * $provide.decorator('$log', ['$delegate', function($delegate) {
  3853. * $delegate.warn = $delegate.error;
  3854. * return $delegate;
  3855. * }]);
  3856. * ```
  3857. */
  3858. function createInjector(modulesToLoad, strictDi) {
  3859. strictDi = (strictDi === true);
  3860. var INSTANTIATING = {},
  3861. providerSuffix = 'Provider',
  3862. path = [],
  3863. loadedModules = new HashMap([], true),
  3864. providerCache = {
  3865. $provide: {
  3866. provider: supportObject(provider),
  3867. factory: supportObject(factory),
  3868. service: supportObject(service),
  3869. value: supportObject(value),
  3870. constant: supportObject(constant),
  3871. decorator: decorator
  3872. }
  3873. },
  3874. providerInjector = (providerCache.$injector =
  3875. createInternalInjector(providerCache, function(serviceName, caller) {
  3876. if (angular.isString(caller)) {
  3877. path.push(caller);
  3878. }
  3879. throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
  3880. })),
  3881. instanceCache = {},
  3882. instanceInjector = (instanceCache.$injector =
  3883. createInternalInjector(instanceCache, function(serviceName, caller) {
  3884. var provider = providerInjector.get(serviceName + providerSuffix, caller);
  3885. return instanceInjector.invoke(provider.$get, provider, undefined, serviceName);
  3886. }));
  3887. forEach(loadModules(modulesToLoad), function(fn) { if (fn) instanceInjector.invoke(fn); });
  3888. return instanceInjector;
  3889. ////////////////////////////////////
  3890. // $provider
  3891. ////////////////////////////////////
  3892. function supportObject(delegate) {
  3893. return function(key, value) {
  3894. if (isObject(key)) {
  3895. forEach(key, reverseParams(delegate));
  3896. } else {
  3897. return delegate(key, value);
  3898. }
  3899. };
  3900. }
  3901. function provider(name, provider_) {
  3902. assertNotHasOwnProperty(name, 'service');
  3903. if (isFunction(provider_) || isArray(provider_)) {
  3904. provider_ = providerInjector.instantiate(provider_);
  3905. }
  3906. if (!provider_.$get) {
  3907. throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
  3908. }
  3909. return providerCache[name + providerSuffix] = provider_;
  3910. }
  3911. function enforceReturnValue(name, factory) {
  3912. return function enforcedReturnValue() {
  3913. var result = instanceInjector.invoke(factory, this);
  3914. if (isUndefined(result)) {
  3915. throw $injectorMinErr('undef', "Provider '{0}' must return a value from $get factory method.", name);
  3916. }
  3917. return result;
  3918. };
  3919. }
  3920. function factory(name, factoryFn, enforce) {
  3921. return provider(name, {
  3922. $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn
  3923. });
  3924. }
  3925. function service(name, constructor) {
  3926. return factory(name, ['$injector', function($injector) {
  3927. return $injector.instantiate(constructor);
  3928. }]);
  3929. }
  3930. function value(name, val) { return factory(name, valueFn(val), false); }
  3931. function constant(name, value) {
  3932. assertNotHasOwnProperty(name, 'constant');
  3933. providerCache[name] = value;
  3934. instanceCache[name] = value;
  3935. }
  3936. function decorator(serviceName, decorFn) {
  3937. var origProvider = providerInjector.get(serviceName + providerSuffix),
  3938. orig$get = origProvider.$get;
  3939. origProvider.$get = function() {
  3940. var origInstance = instanceInjector.invoke(orig$get, origProvider);
  3941. return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
  3942. };
  3943. }
  3944. ////////////////////////////////////
  3945. // Module Loading
  3946. ////////////////////////////////////
  3947. function loadModules(modulesToLoad) {
  3948. assertArg(isUndefined(modulesToLoad) || isArray(modulesToLoad), 'modulesToLoad', 'not an array');
  3949. var runBlocks = [], moduleFn;
  3950. forEach(modulesToLoad, function(module) {
  3951. if (loadedModules.get(module)) return;
  3952. loadedModules.put(module, true);
  3953. function runInvokeQueue(queue) {
  3954. var i, ii;
  3955. for (i = 0, ii = queue.length; i < ii; i++) {
  3956. var invokeArgs = queue[i],
  3957. provider = providerInjector.get(invokeArgs[0]);
  3958. provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
  3959. }
  3960. }
  3961. try {
  3962. if (isString(module)) {
  3963. moduleFn = angularModule(module);
  3964. runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
  3965. runInvokeQueue(moduleFn._invokeQueue);
  3966. runInvokeQueue(moduleFn._configBlocks);
  3967. } else if (isFunction(module)) {
  3968. runBlocks.push(providerInjector.invoke(module));
  3969. } else if (isArray(module)) {
  3970. runBlocks.push(providerInjector.invoke(module));
  3971. } else {
  3972. assertArgFn(module, 'module');
  3973. }
  3974. } catch (e) {
  3975. if (isArray(module)) {
  3976. module = module[module.length - 1];
  3977. }
  3978. if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
  3979. // Safari & FF's stack traces don't contain error.message content
  3980. // unlike those of Chrome and IE
  3981. // So if stack doesn't contain message, we create a new string that contains both.
  3982. // Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
  3983. /* jshint -W022 */
  3984. e = e.message + '\n' + e.stack;
  3985. }
  3986. throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
  3987. module, e.stack || e.message || e);
  3988. }
  3989. });
  3990. return runBlocks;
  3991. }
  3992. ////////////////////////////////////
  3993. // internal Injector
  3994. ////////////////////////////////////
  3995. function createInternalInjector(cache, factory) {
  3996. function getService(serviceName, caller) {
  3997. if (cache.hasOwnProperty(serviceName)) {
  3998. if (cache[serviceName] === INSTANTIATING) {
  3999. throw $injectorMinErr('cdep', 'Circular dependency found: {0}',
  4000. serviceName + ' <- ' + path.join(' <- '));
  4001. }
  4002. return cache[serviceName];
  4003. } else {
  4004. try {
  4005. path.unshift(serviceName);
  4006. cache[serviceName] = INSTANTIATING;
  4007. return cache[serviceName] = factory(serviceName, caller);
  4008. } catch (err) {
  4009. if (cache[serviceName] === INSTANTIATING) {
  4010. delete cache[serviceName];
  4011. }
  4012. throw err;
  4013. } finally {
  4014. path.shift();
  4015. }
  4016. }
  4017. }
  4018. function invoke(fn, self, locals, serviceName) {
  4019. if (typeof locals === 'string') {
  4020. serviceName = locals;
  4021. locals = null;
  4022. }
  4023. var args = [],
  4024. $inject = createInjector.$$annotate(fn, strictDi, serviceName),
  4025. length, i,
  4026. key;
  4027. for (i = 0, length = $inject.length; i < length; i++) {
  4028. key = $inject[i];
  4029. if (typeof key !== 'string') {
  4030. throw $injectorMinErr('itkn',
  4031. 'Incorrect injection token! Expected service name as string, got {0}', key);
  4032. }
  4033. args.push(
  4034. locals && locals.hasOwnProperty(key)
  4035. ? locals[key]
  4036. : getService(key, serviceName)
  4037. );
  4038. }
  4039. if (isArray(fn)) {
  4040. fn = fn[length];
  4041. }
  4042. // http://jsperf.com/angularjs-invoke-apply-vs-switch
  4043. // #5388
  4044. return fn.apply(self, args);
  4045. }
  4046. function instantiate(Type, locals, serviceName) {
  4047. // Check if Type is annotated and use just the given function at n-1 as parameter
  4048. // e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
  4049. // Object creation: http://jsperf.com/create-constructor/2
  4050. var instance = Object.create((isArray(Type) ? Type[Type.length - 1] : Type).prototype || null);
  4051. var returnedValue = invoke(Type, instance, locals, serviceName);
  4052. return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
  4053. }
  4054. return {
  4055. invoke: invoke,
  4056. instantiate: instantiate,
  4057. get: getService,
  4058. annotate: createInjector.$$annotate,
  4059. has: function(name) {
  4060. return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
  4061. }
  4062. };
  4063. }
  4064. }
  4065. createInjector.$$annotate = annotate;
  4066. /**
  4067. * @ngdoc provider
  4068. * @name $anchorScrollProvider
  4069. *
  4070. * @description
  4071. * Use `$anchorScrollProvider` to disable automatic scrolling whenever
  4072. * {@link ng.$location#hash $location.hash()} changes.
  4073. */
  4074. function $AnchorScrollProvider() {
  4075. var autoScrollingEnabled = true;
  4076. /**
  4077. * @ngdoc method
  4078. * @name $anchorScrollProvider#disableAutoScrolling
  4079. *
  4080. * @description
  4081. * By default, {@link ng.$anchorScroll $anchorScroll()} will automatically detect changes to
  4082. * {@link ng.$location#hash $location.hash()} and scroll to the element matching the new hash.<br />
  4083. * Use this method to disable automatic scrolling.
  4084. *
  4085. * If automatic scrolling is disabled, one must explicitly call
  4086. * {@link ng.$anchorScroll $anchorScroll()} in order to scroll to the element related to the
  4087. * current hash.
  4088. */
  4089. this.disableAutoScrolling = function() {
  4090. autoScrollingEnabled = false;
  4091. };
  4092. /**
  4093. * @ngdoc service
  4094. * @name $anchorScroll
  4095. * @kind function
  4096. * @requires $window
  4097. * @requires $location
  4098. * @requires $rootScope
  4099. *
  4100. * @description
  4101. * When called, it scrolls to the element related to the specified `hash` or (if omitted) to the
  4102. * current value of {@link ng.$location#hash $location.hash()}, according to the rules specified
  4103. * in the
  4104. * [HTML5 spec](http://www.w3.org/html/wg/drafts/html/master/browsers.html#the-indicated-part-of-the-document).
  4105. *
  4106. * It also watches the {@link ng.$location#hash $location.hash()} and automatically scrolls to
  4107. * match any anchor whenever it changes. This can be disabled by calling
  4108. * {@link ng.$anchorScrollProvider#disableAutoScrolling $anchorScrollProvider.disableAutoScrolling()}.
  4109. *
  4110. * Additionally, you can use its {@link ng.$anchorScroll#yOffset yOffset} property to specify a
  4111. * vertical scroll-offset (either fixed or dynamic).
  4112. *
  4113. * @param {string=} hash The hash specifying the element to scroll to. If omitted, the value of
  4114. * {@link ng.$location#hash $location.hash()} will be used.
  4115. *
  4116. * @property {(number|function|jqLite)} yOffset
  4117. * If set, specifies a vertical scroll-offset. This is often useful when there are fixed
  4118. * positioned elements at the top of the page, such as navbars, headers etc.
  4119. *
  4120. * `yOffset` can be specified in various ways:
  4121. * - **number**: A fixed number of pixels to be used as offset.<br /><br />
  4122. * - **function**: A getter function called everytime `$anchorScroll()` is executed. Must return
  4123. * a number representing the offset (in pixels).<br /><br />
  4124. * - **jqLite**: A jqLite/jQuery element to be used for specifying the offset. The distance from
  4125. * the top of the page to the element's bottom will be used as offset.<br />
  4126. * **Note**: The element will be taken into account only as long as its `position` is set to
  4127. * `fixed`. This option is useful, when dealing with responsive navbars/headers that adjust
  4128. * their height and/or positioning according to the viewport's size.
  4129. *
  4130. * <br />
  4131. * <div class="alert alert-warning">
  4132. * In order for `yOffset` to work properly, scrolling should take place on the document's root and
  4133. * not some child element.
  4134. * </div>
  4135. *
  4136. * @example
  4137. <example module="anchorScrollExample">
  4138. <file name="index.html">
  4139. <div id="scrollArea" ng-controller="ScrollController">
  4140. <a ng-click="gotoBottom()">Go to bottom</a>
  4141. <a id="bottom"></a> You're at the bottom!
  4142. </div>
  4143. </file>
  4144. <file name="script.js">
  4145. angular.module('anchorScrollExample', [])
  4146. .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
  4147. function ($scope, $location, $anchorScroll) {
  4148. $scope.gotoBottom = function() {
  4149. // set the location.hash to the id of
  4150. // the element you wish to scroll to.
  4151. $location.hash('bottom');
  4152. // call $anchorScroll()
  4153. $anchorScroll();
  4154. };
  4155. }]);
  4156. </file>
  4157. <file name="style.css">
  4158. #scrollArea {
  4159. height: 280px;
  4160. overflow: auto;
  4161. }
  4162. #bottom {
  4163. display: block;
  4164. margin-top: 2000px;
  4165. }
  4166. </file>
  4167. </example>
  4168. *
  4169. * <hr />
  4170. * The example below illustrates the use of a vertical scroll-offset (specified as a fixed value).
  4171. * See {@link ng.$anchorScroll#yOffset $anchorScroll.yOffset} for more details.
  4172. *
  4173. * @example
  4174. <example module="anchorScrollOffsetExample">
  4175. <file name="index.html">
  4176. <div class="fixed-header" ng-controller="headerCtrl">
  4177. <a href="" ng-click="gotoAnchor(x)" ng-repeat="x in [1,2,3,4,5]">
  4178. Go to anchor {{x}}
  4179. </a>
  4180. </div>
  4181. <div id="anchor{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
  4182. Anchor {{x}} of 5
  4183. </div>
  4184. </file>
  4185. <file name="script.js">
  4186. angular.module('anchorScrollOffsetExample', [])
  4187. .run(['$anchorScroll', function($anchorScroll) {
  4188. $anchorScroll.yOffset = 50; // always scroll by 50 extra pixels
  4189. }])
  4190. .controller('headerCtrl', ['$anchorScroll', '$location', '$scope',
  4191. function ($anchorScroll, $location, $scope) {
  4192. $scope.gotoAnchor = function(x) {
  4193. var newHash = 'anchor' + x;
  4194. if ($location.hash() !== newHash) {
  4195. // set the $location.hash to `newHash` and
  4196. // $anchorScroll will automatically scroll to it
  4197. $location.hash('anchor' + x);
  4198. } else {
  4199. // call $anchorScroll() explicitly,
  4200. // since $location.hash hasn't changed
  4201. $anchorScroll();
  4202. }
  4203. };
  4204. }
  4205. ]);
  4206. </file>
  4207. <file name="style.css">
  4208. body {
  4209. padding-top: 50px;
  4210. }
  4211. .anchor {
  4212. border: 2px dashed DarkOrchid;
  4213. padding: 10px 10px 200px 10px;
  4214. }
  4215. .fixed-header {
  4216. background-color: rgba(0, 0, 0, 0.2);
  4217. height: 50px;
  4218. position: fixed;
  4219. top: 0; left: 0; right: 0;
  4220. }
  4221. .fixed-header > a {
  4222. display: inline-block;
  4223. margin: 5px 15px;
  4224. }
  4225. </file>
  4226. </example>
  4227. */
  4228. this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
  4229. var document = $window.document;
  4230. // Helper function to get first anchor from a NodeList
  4231. // (using `Array#some()` instead of `angular#forEach()` since it's more performant
  4232. // and working in all supported browsers.)
  4233. function getFirstAnchor(list) {
  4234. var result = null;
  4235. Array.prototype.some.call(list, function(element) {
  4236. if (nodeName_(element) === 'a') {
  4237. result = element;
  4238. return true;
  4239. }
  4240. });
  4241. return result;
  4242. }
  4243. function getYOffset() {
  4244. var offset = scroll.yOffset;
  4245. if (isFunction(offset)) {
  4246. offset = offset();
  4247. } else if (isElement(offset)) {
  4248. var elem = offset[0];
  4249. var style = $window.getComputedStyle(elem);
  4250. if (style.position !== 'fixed') {
  4251. offset = 0;
  4252. } else {
  4253. offset = elem.getBoundingClientRect().bottom;
  4254. }
  4255. } else if (!isNumber(offset)) {
  4256. offset = 0;
  4257. }
  4258. return offset;
  4259. }
  4260. function scrollTo(elem) {
  4261. if (elem) {
  4262. elem.scrollIntoView();
  4263. var offset = getYOffset();
  4264. if (offset) {
  4265. // `offset` is the number of pixels we should scroll UP in order to align `elem` properly.
  4266. // This is true ONLY if the call to `elem.scrollIntoView()` initially aligns `elem` at the
  4267. // top of the viewport.
  4268. //
  4269. // IF the number of pixels from the top of `elem` to the end of the page's content is less
  4270. // than the height of the viewport, then `elem.scrollIntoView()` will align the `elem` some
  4271. // way down the page.
  4272. //
  4273. // This is often the case for elements near the bottom of the page.
  4274. //
  4275. // In such cases we do not need to scroll the whole `offset` up, just the difference between
  4276. // the top of the element and the offset, which is enough to align the top of `elem` at the
  4277. // desired position.
  4278. var elemTop = elem.getBoundingClientRect().top;
  4279. $window.scrollBy(0, elemTop - offset);
  4280. }
  4281. } else {
  4282. $window.scrollTo(0, 0);
  4283. }
  4284. }
  4285. function scroll(hash) {
  4286. hash = isString(hash) ? hash : $location.hash();
  4287. var elm;
  4288. // empty hash, scroll to the top of the page
  4289. if (!hash) scrollTo(null);
  4290. // element with given id
  4291. else if ((elm = document.getElementById(hash))) scrollTo(elm);
  4292. // first anchor with given name :-D
  4293. else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) scrollTo(elm);
  4294. // no element and hash == 'top', scroll to the top of the page
  4295. else if (hash === 'top') scrollTo(null);
  4296. }
  4297. // does not scroll when user clicks on anchor link that is currently on
  4298. // (no url change, no $location.hash() change), browser native does scroll
  4299. if (autoScrollingEnabled) {
  4300. $rootScope.$watch(function autoScrollWatch() {return $location.hash();},
  4301. function autoScrollWatchAction(newVal, oldVal) {
  4302. // skip the initial scroll if $location.hash is empty
  4303. if (newVal === oldVal && newVal === '') return;
  4304. jqLiteDocumentLoaded(function() {
  4305. $rootScope.$evalAsync(scroll);
  4306. });
  4307. });
  4308. }
  4309. return scroll;
  4310. }];
  4311. }
  4312. var $animateMinErr = minErr('$animate');
  4313. var ELEMENT_NODE = 1;
  4314. var NG_ANIMATE_CLASSNAME = 'ng-animate';
  4315. function mergeClasses(a,b) {
  4316. if (!a && !b) return '';
  4317. if (!a) return b;
  4318. if (!b) return a;
  4319. if (isArray(a)) a = a.join(' ');
  4320. if (isArray(b)) b = b.join(' ');
  4321. return a + ' ' + b;
  4322. }
  4323. function extractElementNode(element) {
  4324. for (var i = 0; i < element.length; i++) {
  4325. var elm = element[i];
  4326. if (elm.nodeType === ELEMENT_NODE) {
  4327. return elm;
  4328. }
  4329. }
  4330. }
  4331. function splitClasses(classes) {
  4332. if (isString(classes)) {
  4333. classes = classes.split(' ');
  4334. }
  4335. // Use createMap() to prevent class assumptions involving property names in
  4336. // Object.prototype
  4337. var obj = createMap();
  4338. forEach(classes, function(klass) {
  4339. // sometimes the split leaves empty string values
  4340. // incase extra spaces were applied to the options
  4341. if (klass.length) {
  4342. obj[klass] = true;
  4343. }
  4344. });
  4345. return obj;
  4346. }
  4347. // if any other type of options value besides an Object value is
  4348. // passed into the $animate.method() animation then this helper code
  4349. // will be run which will ignore it. While this patch is not the
  4350. // greatest solution to this, a lot of existing plugins depend on
  4351. // $animate to either call the callback (< 1.2) or return a promise
  4352. // that can be changed. This helper function ensures that the options
  4353. // are wiped clean incase a callback function is provided.
  4354. function prepareAnimateOptions(options) {
  4355. return isObject(options)
  4356. ? options
  4357. : {};
  4358. }
  4359. var $$CoreAnimateRunnerProvider = function() {
  4360. this.$get = ['$q', '$$rAF', function($q, $$rAF) {
  4361. function AnimateRunner() {}
  4362. AnimateRunner.all = noop;
  4363. AnimateRunner.chain = noop;
  4364. AnimateRunner.prototype = {
  4365. end: noop,
  4366. cancel: noop,
  4367. resume: noop,
  4368. pause: noop,
  4369. complete: noop,
  4370. then: function(pass, fail) {
  4371. return $q(function(resolve) {
  4372. $$rAF(function() {
  4373. resolve();
  4374. });
  4375. }).then(pass, fail);
  4376. }
  4377. };
  4378. return AnimateRunner;
  4379. }];
  4380. };
  4381. // this is prefixed with Core since it conflicts with
  4382. // the animateQueueProvider defined in ngAnimate/animateQueue.js
  4383. var $$CoreAnimateQueueProvider = function() {
  4384. var postDigestQueue = new HashMap();
  4385. var postDigestElements = [];
  4386. this.$get = ['$$AnimateRunner', '$rootScope',
  4387. function($$AnimateRunner, $rootScope) {
  4388. return {
  4389. enabled: noop,
  4390. on: noop,
  4391. off: noop,
  4392. pin: noop,
  4393. push: function(element, event, options, domOperation) {
  4394. domOperation && domOperation();
  4395. options = options || {};
  4396. options.from && element.css(options.from);
  4397. options.to && element.css(options.to);
  4398. if (options.addClass || options.removeClass) {
  4399. addRemoveClassesPostDigest(element, options.addClass, options.removeClass);
  4400. }
  4401. return new $$AnimateRunner(); // jshint ignore:line
  4402. }
  4403. };
  4404. function updateData(data, classes, value) {
  4405. var changed = false;
  4406. if (classes) {
  4407. classes = isString(classes) ? classes.split(' ') :
  4408. isArray(classes) ? classes : [];
  4409. forEach(classes, function(className) {
  4410. if (className) {
  4411. changed = true;
  4412. data[className] = value;
  4413. }
  4414. });
  4415. }
  4416. return changed;
  4417. }
  4418. function handleCSSClassChanges() {
  4419. forEach(postDigestElements, function(element) {
  4420. var data = postDigestQueue.get(element);
  4421. if (data) {
  4422. var existing = splitClasses(element.attr('class'));
  4423. var toAdd = '';
  4424. var toRemove = '';
  4425. forEach(data, function(status, className) {
  4426. var hasClass = !!existing[className];
  4427. if (status !== hasClass) {
  4428. if (status) {
  4429. toAdd += (toAdd.length ? ' ' : '') + className;
  4430. } else {
  4431. toRemove += (toRemove.length ? ' ' : '') + className;
  4432. }
  4433. }
  4434. });
  4435. forEach(element, function(elm) {
  4436. toAdd && jqLiteAddClass(elm, toAdd);
  4437. toRemove && jqLiteRemoveClass(elm, toRemove);
  4438. });
  4439. postDigestQueue.remove(element);
  4440. }
  4441. });
  4442. postDigestElements.length = 0;
  4443. }
  4444. function addRemoveClassesPostDigest(element, add, remove) {
  4445. var data = postDigestQueue.get(element) || {};
  4446. var classesAdded = updateData(data, add, true);
  4447. var classesRemoved = updateData(data, remove, false);
  4448. if (classesAdded || classesRemoved) {
  4449. postDigestQueue.put(element, data);
  4450. postDigestElements.push(element);
  4451. if (postDigestElements.length === 1) {
  4452. $rootScope.$$postDigest(handleCSSClassChanges);
  4453. }
  4454. }
  4455. }
  4456. }];
  4457. };
  4458. /**
  4459. * @ngdoc provider
  4460. * @name $animateProvider
  4461. *
  4462. * @description
  4463. * Default implementation of $animate that doesn't perform any animations, instead just
  4464. * synchronously performs DOM updates and resolves the returned runner promise.
  4465. *
  4466. * In order to enable animations the `ngAnimate` module has to be loaded.
  4467. *
  4468. * To see the functional implementation check out `src/ngAnimate/animate.js`.
  4469. */
  4470. var $AnimateProvider = ['$provide', function($provide) {
  4471. var provider = this;
  4472. this.$$registeredAnimations = Object.create(null);
  4473. /**
  4474. * @ngdoc method
  4475. * @name $animateProvider#register
  4476. *
  4477. * @description
  4478. * Registers a new injectable animation factory function. The factory function produces the
  4479. * animation object which contains callback functions for each event that is expected to be
  4480. * animated.
  4481. *
  4482. * * `eventFn`: `function(element, ... , doneFunction, options)`
  4483. * The element to animate, the `doneFunction` and the options fed into the animation. Depending
  4484. * on the type of animation additional arguments will be injected into the animation function. The
  4485. * list below explains the function signatures for the different animation methods:
  4486. *
  4487. * - setClass: function(element, addedClasses, removedClasses, doneFunction, options)
  4488. * - addClass: function(element, addedClasses, doneFunction, options)
  4489. * - removeClass: function(element, removedClasses, doneFunction, options)
  4490. * - enter, leave, move: function(element, doneFunction, options)
  4491. * - animate: function(element, fromStyles, toStyles, doneFunction, options)
  4492. *
  4493. * Make sure to trigger the `doneFunction` once the animation is fully complete.
  4494. *
  4495. * ```js
  4496. * return {
  4497. * //enter, leave, move signature
  4498. * eventFn : function(element, done, options) {
  4499. * //code to run the animation
  4500. * //once complete, then run done()
  4501. * return function endFunction(wasCancelled) {
  4502. * //code to cancel the animation
  4503. * }
  4504. * }
  4505. * }
  4506. * ```
  4507. *
  4508. * @param {string} name The name of the animation (this is what the class-based CSS value will be compared to).
  4509. * @param {Function} factory The factory function that will be executed to return the animation
  4510. * object.
  4511. */
  4512. this.register = function(name, factory) {
  4513. if (name && name.charAt(0) !== '.') {
  4514. throw $animateMinErr('notcsel', "Expecting class selector starting with '.' got '{0}'.", name);
  4515. }
  4516. var key = name + '-animation';
  4517. provider.$$registeredAnimations[name.substr(1)] = key;
  4518. $provide.factory(key, factory);
  4519. };
  4520. /**
  4521. * @ngdoc method
  4522. * @name $animateProvider#classNameFilter
  4523. *
  4524. * @description
  4525. * Sets and/or returns the CSS class regular expression that is checked when performing
  4526. * an animation. Upon bootstrap the classNameFilter value is not set at all and will
  4527. * therefore enable $animate to attempt to perform an animation on any element that is triggered.
  4528. * When setting the `classNameFilter` value, animations will only be performed on elements
  4529. * that successfully match the filter expression. This in turn can boost performance
  4530. * for low-powered devices as well as applications containing a lot of structural operations.
  4531. * @param {RegExp=} expression The className expression which will be checked against all animations
  4532. * @return {RegExp} The current CSS className expression value. If null then there is no expression value
  4533. */
  4534. this.classNameFilter = function(expression) {
  4535. if (arguments.length === 1) {
  4536. this.$$classNameFilter = (expression instanceof RegExp) ? expression : null;
  4537. if (this.$$classNameFilter) {
  4538. var reservedRegex = new RegExp("(\\s+|\\/)" + NG_ANIMATE_CLASSNAME + "(\\s+|\\/)");
  4539. if (reservedRegex.test(this.$$classNameFilter.toString())) {
  4540. throw $animateMinErr('nongcls','$animateProvider.classNameFilter(regex) prohibits accepting a regex value which matches/contains the "{0}" CSS class.', NG_ANIMATE_CLASSNAME);
  4541. }
  4542. }
  4543. }
  4544. return this.$$classNameFilter;
  4545. };
  4546. this.$get = ['$$animateQueue', function($$animateQueue) {
  4547. function domInsert(element, parentElement, afterElement) {
  4548. // if for some reason the previous element was removed
  4549. // from the dom sometime before this code runs then let's
  4550. // just stick to using the parent element as the anchor
  4551. if (afterElement) {
  4552. var afterNode = extractElementNode(afterElement);
  4553. if (afterNode && !afterNode.parentNode && !afterNode.previousElementSibling) {
  4554. afterElement = null;
  4555. }
  4556. }
  4557. afterElement ? afterElement.after(element) : parentElement.prepend(element);
  4558. }
  4559. /**
  4560. * @ngdoc service
  4561. * @name $animate
  4562. * @description The $animate service exposes a series of DOM utility methods that provide support
  4563. * for animation hooks. The default behavior is the application of DOM operations, however,
  4564. * when an animation is detected (and animations are enabled), $animate will do the heavy lifting
  4565. * to ensure that animation runs with the triggered DOM operation.
  4566. *
  4567. * By default $animate doesn't trigger any animations. This is because the `ngAnimate` module isn't
  4568. * included and only when it is active then the animation hooks that `$animate` triggers will be
  4569. * functional. Once active then all structural `ng-` directives will trigger animations as they perform
  4570. * their DOM-related operations (enter, leave and move). Other directives such as `ngClass`,
  4571. * `ngShow`, `ngHide` and `ngMessages` also provide support for animations.
  4572. *
  4573. * It is recommended that the`$animate` service is always used when executing DOM-related procedures within directives.
  4574. *
  4575. * To learn more about enabling animation support, click here to visit the
  4576. * {@link ngAnimate ngAnimate module page}.
  4577. */
  4578. return {
  4579. // we don't call it directly since non-existant arguments may
  4580. // be interpreted as null within the sub enabled function
  4581. /**
  4582. *
  4583. * @ngdoc method
  4584. * @name $animate#on
  4585. * @kind function
  4586. * @description Sets up an event listener to fire whenever the animation event (enter, leave, move, etc...)
  4587. * has fired on the given element or among any of its children. Once the listener is fired, the provided callback
  4588. * is fired with the following params:
  4589. *
  4590. * ```js
  4591. * $animate.on('enter', container,
  4592. * function callback(element, phase) {
  4593. * // cool we detected an enter animation within the container
  4594. * }
  4595. * );
  4596. * ```
  4597. *
  4598. * @param {string} event the animation event that will be captured (e.g. enter, leave, move, addClass, removeClass, etc...)
  4599. * @param {DOMElement} container the container element that will capture each of the animation events that are fired on itself
  4600. * as well as among its children
  4601. * @param {Function} callback the callback function that will be fired when the listener is triggered
  4602. *
  4603. * The arguments present in the callback function are:
  4604. * * `element` - The captured DOM element that the animation was fired on.
  4605. * * `phase` - The phase of the animation. The two possible phases are **start** (when the animation starts) and **close** (when it ends).
  4606. */
  4607. on: $$animateQueue.on,
  4608. /**
  4609. *
  4610. * @ngdoc method
  4611. * @name $animate#off
  4612. * @kind function
  4613. * @description Deregisters an event listener based on the event which has been associated with the provided element. This method
  4614. * can be used in three different ways depending on the arguments:
  4615. *
  4616. * ```js
  4617. * // remove all the animation event listeners listening for `enter`
  4618. * $animate.off('enter');
  4619. *
  4620. * // remove all the animation event listeners listening for `enter` on the given element and its children
  4621. * $animate.off('enter', container);
  4622. *
  4623. * // remove the event listener function provided by `listenerFn` that is set
  4624. * // to listen for `enter` on the given `element` as well as its children
  4625. * $animate.off('enter', container, callback);
  4626. * ```
  4627. *
  4628. * @param {string} event the animation event (e.g. enter, leave, move, addClass, removeClass, etc...)
  4629. * @param {DOMElement=} container the container element the event listener was placed on
  4630. * @param {Function=} callback the callback function that was registered as the listener
  4631. */
  4632. off: $$animateQueue.off,
  4633. /**
  4634. * @ngdoc method
  4635. * @name $animate#pin
  4636. * @kind function
  4637. * @description Associates the provided element with a host parent element to allow the element to be animated even if it exists
  4638. * outside of the DOM structure of the Angular application. By doing so, any animation triggered via `$animate` can be issued on the
  4639. * element despite being outside the realm of the application or within another application. Say for example if the application
  4640. * was bootstrapped on an element that is somewhere inside of the `<body>` tag, but we wanted to allow for an element to be situated
  4641. * as a direct child of `document.body`, then this can be achieved by pinning the element via `$animate.pin(element)`. Keep in mind
  4642. * that calling `$animate.pin(element, parentElement)` will not actually insert into the DOM anywhere; it will just create the association.
  4643. *
  4644. * Note that this feature is only active when the `ngAnimate` module is used.
  4645. *
  4646. * @param {DOMElement} element the external element that will be pinned
  4647. * @param {DOMElement} parentElement the host parent element that will be associated with the external element
  4648. */
  4649. pin: $$animateQueue.pin,
  4650. /**
  4651. *
  4652. * @ngdoc method
  4653. * @name $animate#enabled
  4654. * @kind function
  4655. * @description Used to get and set whether animations are enabled or not on the entire application or on an element and its children. This
  4656. * function can be called in four ways:
  4657. *
  4658. * ```js
  4659. * // returns true or false
  4660. * $animate.enabled();
  4661. *
  4662. * // changes the enabled state for all animations
  4663. * $animate.enabled(false);
  4664. * $animate.enabled(true);
  4665. *
  4666. * // returns true or false if animations are enabled for an element
  4667. * $animate.enabled(element);
  4668. *
  4669. * // changes the enabled state for an element and its children
  4670. * $animate.enabled(element, true);
  4671. * $animate.enabled(element, false);
  4672. * ```
  4673. *
  4674. * @param {DOMElement=} element the element that will be considered for checking/setting the enabled state
  4675. * @param {boolean=} enabled whether or not the animations will be enabled for the element
  4676. *
  4677. * @return {boolean} whether or not animations are enabled
  4678. */
  4679. enabled: $$animateQueue.enabled,
  4680. /**
  4681. * @ngdoc method
  4682. * @name $animate#cancel
  4683. * @kind function
  4684. * @description Cancels the provided animation.
  4685. *
  4686. * @param {Promise} animationPromise The animation promise that is returned when an animation is started.
  4687. */
  4688. cancel: function(runner) {
  4689. runner.end && runner.end();
  4690. },
  4691. /**
  4692. *
  4693. * @ngdoc method
  4694. * @name $animate#enter
  4695. * @kind function
  4696. * @description Inserts the element into the DOM either after the `after` element (if provided) or
  4697. * as the first child within the `parent` element and then triggers an animation.
  4698. * A promise is returned that will be resolved during the next digest once the animation
  4699. * has completed.
  4700. *
  4701. * @param {DOMElement} element the element which will be inserted into the DOM
  4702. * @param {DOMElement} parent the parent element which will append the element as
  4703. * a child (so long as the after element is not present)
  4704. * @param {DOMElement=} after the sibling element after which the element will be appended
  4705. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4706. *
  4707. * @return {Promise} the animation callback promise
  4708. */
  4709. enter: function(element, parent, after, options) {
  4710. parent = parent && jqLite(parent);
  4711. after = after && jqLite(after);
  4712. parent = parent || after.parent();
  4713. domInsert(element, parent, after);
  4714. return $$animateQueue.push(element, 'enter', prepareAnimateOptions(options));
  4715. },
  4716. /**
  4717. *
  4718. * @ngdoc method
  4719. * @name $animate#move
  4720. * @kind function
  4721. * @description Inserts (moves) the element into its new position in the DOM either after
  4722. * the `after` element (if provided) or as the first child within the `parent` element
  4723. * and then triggers an animation. A promise is returned that will be resolved
  4724. * during the next digest once the animation has completed.
  4725. *
  4726. * @param {DOMElement} element the element which will be moved into the new DOM position
  4727. * @param {DOMElement} parent the parent element which will append the element as
  4728. * a child (so long as the after element is not present)
  4729. * @param {DOMElement=} after the sibling element after which the element will be appended
  4730. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4731. *
  4732. * @return {Promise} the animation callback promise
  4733. */
  4734. move: function(element, parent, after, options) {
  4735. parent = parent && jqLite(parent);
  4736. after = after && jqLite(after);
  4737. parent = parent || after.parent();
  4738. domInsert(element, parent, after);
  4739. return $$animateQueue.push(element, 'move', prepareAnimateOptions(options));
  4740. },
  4741. /**
  4742. * @ngdoc method
  4743. * @name $animate#leave
  4744. * @kind function
  4745. * @description Triggers an animation and then removes the element from the DOM.
  4746. * When the function is called a promise is returned that will be resolved during the next
  4747. * digest once the animation has completed.
  4748. *
  4749. * @param {DOMElement} element the element which will be removed from the DOM
  4750. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4751. *
  4752. * @return {Promise} the animation callback promise
  4753. */
  4754. leave: function(element, options) {
  4755. return $$animateQueue.push(element, 'leave', prepareAnimateOptions(options), function() {
  4756. element.remove();
  4757. });
  4758. },
  4759. /**
  4760. * @ngdoc method
  4761. * @name $animate#addClass
  4762. * @kind function
  4763. *
  4764. * @description Triggers an addClass animation surrounding the addition of the provided CSS class(es). Upon
  4765. * execution, the addClass operation will only be handled after the next digest and it will not trigger an
  4766. * animation if element already contains the CSS class or if the class is removed at a later step.
  4767. * Note that class-based animations are treated differently compared to structural animations
  4768. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4769. * depending if CSS or JavaScript animations are used.
  4770. *
  4771. * @param {DOMElement} element the element which the CSS classes will be applied to
  4772. * @param {string} className the CSS class(es) that will be added (multiple classes are separated via spaces)
  4773. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4774. *
  4775. * @return {Promise} the animation callback promise
  4776. */
  4777. addClass: function(element, className, options) {
  4778. options = prepareAnimateOptions(options);
  4779. options.addClass = mergeClasses(options.addclass, className);
  4780. return $$animateQueue.push(element, 'addClass', options);
  4781. },
  4782. /**
  4783. * @ngdoc method
  4784. * @name $animate#removeClass
  4785. * @kind function
  4786. *
  4787. * @description Triggers a removeClass animation surrounding the removal of the provided CSS class(es). Upon
  4788. * execution, the removeClass operation will only be handled after the next digest and it will not trigger an
  4789. * animation if element does not contain the CSS class or if the class is added at a later step.
  4790. * Note that class-based animations are treated differently compared to structural animations
  4791. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4792. * depending if CSS or JavaScript animations are used.
  4793. *
  4794. * @param {DOMElement} element the element which the CSS classes will be applied to
  4795. * @param {string} className the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4796. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4797. *
  4798. * @return {Promise} the animation callback promise
  4799. */
  4800. removeClass: function(element, className, options) {
  4801. options = prepareAnimateOptions(options);
  4802. options.removeClass = mergeClasses(options.removeClass, className);
  4803. return $$animateQueue.push(element, 'removeClass', options);
  4804. },
  4805. /**
  4806. * @ngdoc method
  4807. * @name $animate#setClass
  4808. * @kind function
  4809. *
  4810. * @description Performs both the addition and removal of a CSS classes on an element and (during the process)
  4811. * triggers an animation surrounding the class addition/removal. Much like `$animate.addClass` and
  4812. * `$animate.removeClass`, `setClass` will only evaluate the classes being added/removed once a digest has
  4813. * passed. Note that class-based animations are treated differently compared to structural animations
  4814. * (like enter, move and leave) since the CSS classes may be added/removed at different points
  4815. * depending if CSS or JavaScript animations are used.
  4816. *
  4817. * @param {DOMElement} element the element which the CSS classes will be applied to
  4818. * @param {string} add the CSS class(es) that will be added (multiple classes are separated via spaces)
  4819. * @param {string} remove the CSS class(es) that will be removed (multiple classes are separated via spaces)
  4820. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4821. *
  4822. * @return {Promise} the animation callback promise
  4823. */
  4824. setClass: function(element, add, remove, options) {
  4825. options = prepareAnimateOptions(options);
  4826. options.addClass = mergeClasses(options.addClass, add);
  4827. options.removeClass = mergeClasses(options.removeClass, remove);
  4828. return $$animateQueue.push(element, 'setClass', options);
  4829. },
  4830. /**
  4831. * @ngdoc method
  4832. * @name $animate#animate
  4833. * @kind function
  4834. *
  4835. * @description Performs an inline animation on the element which applies the provided to and from CSS styles to the element.
  4836. * If any detected CSS transition, keyframe or JavaScript matches the provided className value then the animation will take
  4837. * on the provided styles. For example, if a transition animation is set for the given className then the provided from and
  4838. * to styles will be applied alongside the given transition. If a JavaScript animation is detected then the provided styles
  4839. * will be given in as function paramters into the `animate` method (or as apart of the `options` parameter).
  4840. *
  4841. * @param {DOMElement} element the element which the CSS styles will be applied to
  4842. * @param {object} from the from (starting) CSS styles that will be applied to the element and across the animation.
  4843. * @param {object} to the to (destination) CSS styles that will be applied to the element and across the animation.
  4844. * @param {string=} className an optional CSS class that will be applied to the element for the duration of the animation. If
  4845. * this value is left as empty then a CSS class of `ng-inline-animate` will be applied to the element.
  4846. * (Note that if no animation is detected then this value will not be appplied to the element.)
  4847. * @param {object=} options an optional collection of options/styles that will be applied to the element
  4848. *
  4849. * @return {Promise} the animation callback promise
  4850. */
  4851. animate: function(element, from, to, className, options) {
  4852. options = prepareAnimateOptions(options);
  4853. options.from = options.from ? extend(options.from, from) : from;
  4854. options.to = options.to ? extend(options.to, to) : to;
  4855. className = className || 'ng-inline-animate';
  4856. options.tempClasses = mergeClasses(options.tempClasses, className);
  4857. return $$animateQueue.push(element, 'animate', options);
  4858. }
  4859. };
  4860. }];
  4861. }];
  4862. /**
  4863. * @ngdoc service
  4864. * @name $animateCss
  4865. * @kind object
  4866. *
  4867. * @description
  4868. * This is the core version of `$animateCss`. By default, only when the `ngAnimate` is included,
  4869. * then the `$animateCss` service will actually perform animations.
  4870. *
  4871. * Click here {@link ngAnimate.$animateCss to read the documentation for $animateCss}.
  4872. */
  4873. var $CoreAnimateCssProvider = function() {
  4874. this.$get = ['$$rAF', '$q', function($$rAF, $q) {
  4875. var RAFPromise = function() {};
  4876. RAFPromise.prototype = {
  4877. done: function(cancel) {
  4878. this.defer && this.defer[cancel === true ? 'reject' : 'resolve']();
  4879. },
  4880. end: function() {
  4881. this.done();
  4882. },
  4883. cancel: function() {
  4884. this.done(true);
  4885. },
  4886. getPromise: function() {
  4887. if (!this.defer) {
  4888. this.defer = $q.defer();
  4889. }
  4890. return this.defer.promise;
  4891. },
  4892. then: function(f1,f2) {
  4893. return this.getPromise().then(f1,f2);
  4894. },
  4895. 'catch': function(f1) {
  4896. return this.getPromise()['catch'](f1);
  4897. },
  4898. 'finally': function(f1) {
  4899. return this.getPromise()['finally'](f1);
  4900. }
  4901. };
  4902. return function(element, options) {
  4903. // there is no point in applying the styles since
  4904. // there is no animation that goes on at all in
  4905. // this version of $animateCss.
  4906. if (options.cleanupStyles) {
  4907. options.from = options.to = null;
  4908. }
  4909. if (options.from) {
  4910. element.css(options.from);
  4911. options.from = null;
  4912. }
  4913. var closed, runner = new RAFPromise();
  4914. return {
  4915. start: run,
  4916. end: run
  4917. };
  4918. function run() {
  4919. $$rAF(function() {
  4920. close();
  4921. if (!closed) {
  4922. runner.done();
  4923. }
  4924. closed = true;
  4925. });
  4926. return runner;
  4927. }
  4928. function close() {
  4929. if (options.addClass) {
  4930. element.addClass(options.addClass);
  4931. options.addClass = null;
  4932. }
  4933. if (options.removeClass) {
  4934. element.removeClass(options.removeClass);
  4935. options.removeClass = null;
  4936. }
  4937. if (options.to) {
  4938. element.css(options.to);
  4939. options.to = null;
  4940. }
  4941. }
  4942. };
  4943. }];
  4944. };
  4945. /* global stripHash: true */
  4946. /**
  4947. * ! This is a private undocumented service !
  4948. *
  4949. * @name $browser
  4950. * @requires $log
  4951. * @description
  4952. * This object has two goals:
  4953. *
  4954. * - hide all the global state in the browser caused by the window object
  4955. * - abstract away all the browser specific features and inconsistencies
  4956. *
  4957. * For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
  4958. * service, which can be used for convenient testing of the application without the interaction with
  4959. * the real browser apis.
  4960. */
  4961. /**
  4962. * @param {object} window The global window object.
  4963. * @param {object} document jQuery wrapped document.
  4964. * @param {object} $log window.console or an object with the same interface.
  4965. * @param {object} $sniffer $sniffer service
  4966. */
  4967. function Browser(window, document, $log, $sniffer) {
  4968. var self = this,
  4969. rawDocument = document[0],
  4970. location = window.location,
  4971. history = window.history,
  4972. setTimeout = window.setTimeout,
  4973. clearTimeout = window.clearTimeout,
  4974. pendingDeferIds = {};
  4975. self.isMock = false;
  4976. var outstandingRequestCount = 0;
  4977. var outstandingRequestCallbacks = [];
  4978. // TODO(vojta): remove this temporary api
  4979. self.$$completeOutstandingRequest = completeOutstandingRequest;
  4980. self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
  4981. /**
  4982. * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
  4983. * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
  4984. */
  4985. function completeOutstandingRequest(fn) {
  4986. try {
  4987. fn.apply(null, sliceArgs(arguments, 1));
  4988. } finally {
  4989. outstandingRequestCount--;
  4990. if (outstandingRequestCount === 0) {
  4991. while (outstandingRequestCallbacks.length) {
  4992. try {
  4993. outstandingRequestCallbacks.pop()();
  4994. } catch (e) {
  4995. $log.error(e);
  4996. }
  4997. }
  4998. }
  4999. }
  5000. }
  5001. function getHash(url) {
  5002. var index = url.indexOf('#');
  5003. return index === -1 ? '' : url.substr(index);
  5004. }
  5005. /**
  5006. * @private
  5007. * Note: this method is used only by scenario runner
  5008. * TODO(vojta): prefix this method with $$ ?
  5009. * @param {function()} callback Function that will be called when no outstanding request
  5010. */
  5011. self.notifyWhenNoOutstandingRequests = function(callback) {
  5012. if (outstandingRequestCount === 0) {
  5013. callback();
  5014. } else {
  5015. outstandingRequestCallbacks.push(callback);
  5016. }
  5017. };
  5018. //////////////////////////////////////////////////////////////
  5019. // URL API
  5020. //////////////////////////////////////////////////////////////
  5021. var cachedState, lastHistoryState,
  5022. lastBrowserUrl = location.href,
  5023. baseElement = document.find('base'),
  5024. pendingLocation = null;
  5025. cacheState();
  5026. lastHistoryState = cachedState;
  5027. /**
  5028. * @name $browser#url
  5029. *
  5030. * @description
  5031. * GETTER:
  5032. * Without any argument, this method just returns current value of location.href.
  5033. *
  5034. * SETTER:
  5035. * With at least one argument, this method sets url to new value.
  5036. * If html5 history api supported, pushState/replaceState is used, otherwise
  5037. * location.href/location.replace is used.
  5038. * Returns its own instance to allow chaining
  5039. *
  5040. * NOTE: this api is intended for use only by the $location service. Please use the
  5041. * {@link ng.$location $location service} to change url.
  5042. *
  5043. * @param {string} url New url (when used as setter)
  5044. * @param {boolean=} replace Should new url replace current history record?
  5045. * @param {object=} state object to use with pushState/replaceState
  5046. */
  5047. self.url = function(url, replace, state) {
  5048. // In modern browsers `history.state` is `null` by default; treating it separately
  5049. // from `undefined` would cause `$browser.url('/foo')` to change `history.state`
  5050. // to undefined via `pushState`. Instead, let's change `undefined` to `null` here.
  5051. if (isUndefined(state)) {
  5052. state = null;
  5053. }
  5054. // Android Browser BFCache causes location, history reference to become stale.
  5055. if (location !== window.location) location = window.location;
  5056. if (history !== window.history) history = window.history;
  5057. // setter
  5058. if (url) {
  5059. var sameState = lastHistoryState === state;
  5060. // Don't change anything if previous and current URLs and states match. This also prevents
  5061. // IE<10 from getting into redirect loop when in LocationHashbangInHtml5Url mode.
  5062. // See https://github.com/angular/angular.js/commit/ffb2701
  5063. if (lastBrowserUrl === url && (!$sniffer.history || sameState)) {
  5064. return self;
  5065. }
  5066. var sameBase = lastBrowserUrl && stripHash(lastBrowserUrl) === stripHash(url);
  5067. lastBrowserUrl = url;
  5068. lastHistoryState = state;
  5069. // Don't use history API if only the hash changed
  5070. // due to a bug in IE10/IE11 which leads
  5071. // to not firing a `hashchange` nor `popstate` event
  5072. // in some cases (see #9143).
  5073. if ($sniffer.history && (!sameBase || !sameState)) {
  5074. history[replace ? 'replaceState' : 'pushState'](state, '', url);
  5075. cacheState();
  5076. // Do the assignment again so that those two variables are referentially identical.
  5077. lastHistoryState = cachedState;
  5078. } else {
  5079. if (!sameBase || pendingLocation) {
  5080. pendingLocation = url;
  5081. }
  5082. if (replace) {
  5083. location.replace(url);
  5084. } else if (!sameBase) {
  5085. location.href = url;
  5086. } else {
  5087. location.hash = getHash(url);
  5088. }
  5089. if (location.href !== url) {
  5090. pendingLocation = url;
  5091. }
  5092. }
  5093. return self;
  5094. // getter
  5095. } else {
  5096. // - pendingLocation is needed as browsers don't allow to read out
  5097. // the new location.href if a reload happened or if there is a bug like in iOS 9 (see
  5098. // https://openradar.appspot.com/22186109).
  5099. // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
  5100. return pendingLocation || location.href.replace(/%27/g,"'");
  5101. }
  5102. };
  5103. /**
  5104. * @name $browser#state
  5105. *
  5106. * @description
  5107. * This method is a getter.
  5108. *
  5109. * Return history.state or null if history.state is undefined.
  5110. *
  5111. * @returns {object} state
  5112. */
  5113. self.state = function() {
  5114. return cachedState;
  5115. };
  5116. var urlChangeListeners = [],
  5117. urlChangeInit = false;
  5118. function cacheStateAndFireUrlChange() {
  5119. pendingLocation = null;
  5120. cacheState();
  5121. fireUrlChange();
  5122. }
  5123. function getCurrentState() {
  5124. try {
  5125. return history.state;
  5126. } catch (e) {
  5127. // MSIE can reportedly throw when there is no state (UNCONFIRMED).
  5128. }
  5129. }
  5130. // This variable should be used *only* inside the cacheState function.
  5131. var lastCachedState = null;
  5132. function cacheState() {
  5133. // This should be the only place in $browser where `history.state` is read.
  5134. cachedState = getCurrentState();
  5135. cachedState = isUndefined(cachedState) ? null : cachedState;
  5136. // Prevent callbacks fo fire twice if both hashchange & popstate were fired.
  5137. if (equals(cachedState, lastCachedState)) {
  5138. cachedState = lastCachedState;
  5139. }
  5140. lastCachedState = cachedState;
  5141. }
  5142. function fireUrlChange() {
  5143. if (lastBrowserUrl === self.url() && lastHistoryState === cachedState) {
  5144. return;
  5145. }
  5146. lastBrowserUrl = self.url();
  5147. lastHistoryState = cachedState;
  5148. forEach(urlChangeListeners, function(listener) {
  5149. listener(self.url(), cachedState);
  5150. });
  5151. }
  5152. /**
  5153. * @name $browser#onUrlChange
  5154. *
  5155. * @description
  5156. * Register callback function that will be called, when url changes.
  5157. *
  5158. * It's only called when the url is changed from outside of angular:
  5159. * - user types different url into address bar
  5160. * - user clicks on history (forward/back) button
  5161. * - user clicks on a link
  5162. *
  5163. * It's not called when url is changed by $browser.url() method
  5164. *
  5165. * The listener gets called with new url as parameter.
  5166. *
  5167. * NOTE: this api is intended for use only by the $location service. Please use the
  5168. * {@link ng.$location $location service} to monitor url changes in angular apps.
  5169. *
  5170. * @param {function(string)} listener Listener function to be called when url changes.
  5171. * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
  5172. */
  5173. self.onUrlChange = function(callback) {
  5174. // TODO(vojta): refactor to use node's syntax for events
  5175. if (!urlChangeInit) {
  5176. // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
  5177. // don't fire popstate when user change the address bar and don't fire hashchange when url
  5178. // changed by push/replaceState
  5179. // html5 history api - popstate event
  5180. if ($sniffer.history) jqLite(window).on('popstate', cacheStateAndFireUrlChange);
  5181. // hashchange event
  5182. jqLite(window).on('hashchange', cacheStateAndFireUrlChange);
  5183. urlChangeInit = true;
  5184. }
  5185. urlChangeListeners.push(callback);
  5186. return callback;
  5187. };
  5188. /**
  5189. * @private
  5190. * Remove popstate and hashchange handler from window.
  5191. *
  5192. * NOTE: this api is intended for use only by $rootScope.
  5193. */
  5194. self.$$applicationDestroyed = function() {
  5195. jqLite(window).off('hashchange popstate', cacheStateAndFireUrlChange);
  5196. };
  5197. /**
  5198. * Checks whether the url has changed outside of Angular.
  5199. * Needs to be exported to be able to check for changes that have been done in sync,
  5200. * as hashchange/popstate events fire in async.
  5201. */
  5202. self.$$checkUrlChange = fireUrlChange;
  5203. //////////////////////////////////////////////////////////////
  5204. // Misc API
  5205. //////////////////////////////////////////////////////////////
  5206. /**
  5207. * @name $browser#baseHref
  5208. *
  5209. * @description
  5210. * Returns current <base href>
  5211. * (always relative - without domain)
  5212. *
  5213. * @returns {string} The current base href
  5214. */
  5215. self.baseHref = function() {
  5216. var href = baseElement.attr('href');
  5217. return href ? href.replace(/^(https?\:)?\/\/[^\/]*/, '') : '';
  5218. };
  5219. /**
  5220. * @name $browser#defer
  5221. * @param {function()} fn A function, who's execution should be deferred.
  5222. * @param {number=} [delay=0] of milliseconds to defer the function execution.
  5223. * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
  5224. *
  5225. * @description
  5226. * Executes a fn asynchronously via `setTimeout(fn, delay)`.
  5227. *
  5228. * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
  5229. * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
  5230. * via `$browser.defer.flush()`.
  5231. *
  5232. */
  5233. self.defer = function(fn, delay) {
  5234. var timeoutId;
  5235. outstandingRequestCount++;
  5236. timeoutId = setTimeout(function() {
  5237. delete pendingDeferIds[timeoutId];
  5238. completeOutstandingRequest(fn);
  5239. }, delay || 0);
  5240. pendingDeferIds[timeoutId] = true;
  5241. return timeoutId;
  5242. };
  5243. /**
  5244. * @name $browser#defer.cancel
  5245. *
  5246. * @description
  5247. * Cancels a deferred task identified with `deferId`.
  5248. *
  5249. * @param {*} deferId Token returned by the `$browser.defer` function.
  5250. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  5251. * canceled.
  5252. */
  5253. self.defer.cancel = function(deferId) {
  5254. if (pendingDeferIds[deferId]) {
  5255. delete pendingDeferIds[deferId];
  5256. clearTimeout(deferId);
  5257. completeOutstandingRequest(noop);
  5258. return true;
  5259. }
  5260. return false;
  5261. };
  5262. }
  5263. function $BrowserProvider() {
  5264. this.$get = ['$window', '$log', '$sniffer', '$document',
  5265. function($window, $log, $sniffer, $document) {
  5266. return new Browser($window, $document, $log, $sniffer);
  5267. }];
  5268. }
  5269. /**
  5270. * @ngdoc service
  5271. * @name $cacheFactory
  5272. *
  5273. * @description
  5274. * Factory that constructs {@link $cacheFactory.Cache Cache} objects and gives access to
  5275. * them.
  5276. *
  5277. * ```js
  5278. *
  5279. * var cache = $cacheFactory('cacheId');
  5280. * expect($cacheFactory.get('cacheId')).toBe(cache);
  5281. * expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
  5282. *
  5283. * cache.put("key", "value");
  5284. * cache.put("another key", "another value");
  5285. *
  5286. * // We've specified no options on creation
  5287. * expect(cache.info()).toEqual({id: 'cacheId', size: 2});
  5288. *
  5289. * ```
  5290. *
  5291. *
  5292. * @param {string} cacheId Name or id of the newly created cache.
  5293. * @param {object=} options Options object that specifies the cache behavior. Properties:
  5294. *
  5295. * - `{number=}` `capacity` — turns the cache into LRU cache.
  5296. *
  5297. * @returns {object} Newly created cache object with the following set of methods:
  5298. *
  5299. * - `{object}` `info()` — Returns id, size, and options of cache.
  5300. * - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
  5301. * it.
  5302. * - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
  5303. * - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
  5304. * - `{void}` `removeAll()` — Removes all cached values.
  5305. * - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
  5306. *
  5307. * @example
  5308. <example module="cacheExampleApp">
  5309. <file name="index.html">
  5310. <div ng-controller="CacheController">
  5311. <input ng-model="newCacheKey" placeholder="Key">
  5312. <input ng-model="newCacheValue" placeholder="Value">
  5313. <button ng-click="put(newCacheKey, newCacheValue)">Cache</button>
  5314. <p ng-if="keys.length">Cached Values</p>
  5315. <div ng-repeat="key in keys">
  5316. <span ng-bind="key"></span>
  5317. <span>: </span>
  5318. <b ng-bind="cache.get(key)"></b>
  5319. </div>
  5320. <p>Cache Info</p>
  5321. <div ng-repeat="(key, value) in cache.info()">
  5322. <span ng-bind="key"></span>
  5323. <span>: </span>
  5324. <b ng-bind="value"></b>
  5325. </div>
  5326. </div>
  5327. </file>
  5328. <file name="script.js">
  5329. angular.module('cacheExampleApp', []).
  5330. controller('CacheController', ['$scope', '$cacheFactory', function($scope, $cacheFactory) {
  5331. $scope.keys = [];
  5332. $scope.cache = $cacheFactory('cacheId');
  5333. $scope.put = function(key, value) {
  5334. if (angular.isUndefined($scope.cache.get(key))) {
  5335. $scope.keys.push(key);
  5336. }
  5337. $scope.cache.put(key, angular.isUndefined(value) ? null : value);
  5338. };
  5339. }]);
  5340. </file>
  5341. <file name="style.css">
  5342. p {
  5343. margin: 10px 0 3px;
  5344. }
  5345. </file>
  5346. </example>
  5347. */
  5348. function $CacheFactoryProvider() {
  5349. this.$get = function() {
  5350. var caches = {};
  5351. function cacheFactory(cacheId, options) {
  5352. if (cacheId in caches) {
  5353. throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
  5354. }
  5355. var size = 0,
  5356. stats = extend({}, options, {id: cacheId}),
  5357. data = createMap(),
  5358. capacity = (options && options.capacity) || Number.MAX_VALUE,
  5359. lruHash = createMap(),
  5360. freshEnd = null,
  5361. staleEnd = null;
  5362. /**
  5363. * @ngdoc type
  5364. * @name $cacheFactory.Cache
  5365. *
  5366. * @description
  5367. * A cache object used to store and retrieve data, primarily used by
  5368. * {@link $http $http} and the {@link ng.directive:script script} directive to cache
  5369. * templates and other data.
  5370. *
  5371. * ```js
  5372. * angular.module('superCache')
  5373. * .factory('superCache', ['$cacheFactory', function($cacheFactory) {
  5374. * return $cacheFactory('super-cache');
  5375. * }]);
  5376. * ```
  5377. *
  5378. * Example test:
  5379. *
  5380. * ```js
  5381. * it('should behave like a cache', inject(function(superCache) {
  5382. * superCache.put('key', 'value');
  5383. * superCache.put('another key', 'another value');
  5384. *
  5385. * expect(superCache.info()).toEqual({
  5386. * id: 'super-cache',
  5387. * size: 2
  5388. * });
  5389. *
  5390. * superCache.remove('another key');
  5391. * expect(superCache.get('another key')).toBeUndefined();
  5392. *
  5393. * superCache.removeAll();
  5394. * expect(superCache.info()).toEqual({
  5395. * id: 'super-cache',
  5396. * size: 0
  5397. * });
  5398. * }));
  5399. * ```
  5400. */
  5401. return caches[cacheId] = {
  5402. /**
  5403. * @ngdoc method
  5404. * @name $cacheFactory.Cache#put
  5405. * @kind function
  5406. *
  5407. * @description
  5408. * Inserts a named entry into the {@link $cacheFactory.Cache Cache} object to be
  5409. * retrieved later, and incrementing the size of the cache if the key was not already
  5410. * present in the cache. If behaving like an LRU cache, it will also remove stale
  5411. * entries from the set.
  5412. *
  5413. * It will not insert undefined values into the cache.
  5414. *
  5415. * @param {string} key the key under which the cached data is stored.
  5416. * @param {*} value the value to store alongside the key. If it is undefined, the key
  5417. * will not be stored.
  5418. * @returns {*} the value stored.
  5419. */
  5420. put: function(key, value) {
  5421. if (isUndefined(value)) return;
  5422. if (capacity < Number.MAX_VALUE) {
  5423. var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
  5424. refresh(lruEntry);
  5425. }
  5426. if (!(key in data)) size++;
  5427. data[key] = value;
  5428. if (size > capacity) {
  5429. this.remove(staleEnd.key);
  5430. }
  5431. return value;
  5432. },
  5433. /**
  5434. * @ngdoc method
  5435. * @name $cacheFactory.Cache#get
  5436. * @kind function
  5437. *
  5438. * @description
  5439. * Retrieves named data stored in the {@link $cacheFactory.Cache Cache} object.
  5440. *
  5441. * @param {string} key the key of the data to be retrieved
  5442. * @returns {*} the value stored.
  5443. */
  5444. get: function(key) {
  5445. if (capacity < Number.MAX_VALUE) {
  5446. var lruEntry = lruHash[key];
  5447. if (!lruEntry) return;
  5448. refresh(lruEntry);
  5449. }
  5450. return data[key];
  5451. },
  5452. /**
  5453. * @ngdoc method
  5454. * @name $cacheFactory.Cache#remove
  5455. * @kind function
  5456. *
  5457. * @description
  5458. * Removes an entry from the {@link $cacheFactory.Cache Cache} object.
  5459. *
  5460. * @param {string} key the key of the entry to be removed
  5461. */
  5462. remove: function(key) {
  5463. if (capacity < Number.MAX_VALUE) {
  5464. var lruEntry = lruHash[key];
  5465. if (!lruEntry) return;
  5466. if (lruEntry == freshEnd) freshEnd = lruEntry.p;
  5467. if (lruEntry == staleEnd) staleEnd = lruEntry.n;
  5468. link(lruEntry.n,lruEntry.p);
  5469. delete lruHash[key];
  5470. }
  5471. if (!(key in data)) return;
  5472. delete data[key];
  5473. size--;
  5474. },
  5475. /**
  5476. * @ngdoc method
  5477. * @name $cacheFactory.Cache#removeAll
  5478. * @kind function
  5479. *
  5480. * @description
  5481. * Clears the cache object of any entries.
  5482. */
  5483. removeAll: function() {
  5484. data = createMap();
  5485. size = 0;
  5486. lruHash = createMap();
  5487. freshEnd = staleEnd = null;
  5488. },
  5489. /**
  5490. * @ngdoc method
  5491. * @name $cacheFactory.Cache#destroy
  5492. * @kind function
  5493. *
  5494. * @description
  5495. * Destroys the {@link $cacheFactory.Cache Cache} object entirely,
  5496. * removing it from the {@link $cacheFactory $cacheFactory} set.
  5497. */
  5498. destroy: function() {
  5499. data = null;
  5500. stats = null;
  5501. lruHash = null;
  5502. delete caches[cacheId];
  5503. },
  5504. /**
  5505. * @ngdoc method
  5506. * @name $cacheFactory.Cache#info
  5507. * @kind function
  5508. *
  5509. * @description
  5510. * Retrieve information regarding a particular {@link $cacheFactory.Cache Cache}.
  5511. *
  5512. * @returns {object} an object with the following properties:
  5513. * <ul>
  5514. * <li>**id**: the id of the cache instance</li>
  5515. * <li>**size**: the number of entries kept in the cache instance</li>
  5516. * <li>**...**: any additional properties from the options object when creating the
  5517. * cache.</li>
  5518. * </ul>
  5519. */
  5520. info: function() {
  5521. return extend({}, stats, {size: size});
  5522. }
  5523. };
  5524. /**
  5525. * makes the `entry` the freshEnd of the LRU linked list
  5526. */
  5527. function refresh(entry) {
  5528. if (entry != freshEnd) {
  5529. if (!staleEnd) {
  5530. staleEnd = entry;
  5531. } else if (staleEnd == entry) {
  5532. staleEnd = entry.n;
  5533. }
  5534. link(entry.n, entry.p);
  5535. link(entry, freshEnd);
  5536. freshEnd = entry;
  5537. freshEnd.n = null;
  5538. }
  5539. }
  5540. /**
  5541. * bidirectionally links two entries of the LRU linked list
  5542. */
  5543. function link(nextEntry, prevEntry) {
  5544. if (nextEntry != prevEntry) {
  5545. if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
  5546. if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
  5547. }
  5548. }
  5549. }
  5550. /**
  5551. * @ngdoc method
  5552. * @name $cacheFactory#info
  5553. *
  5554. * @description
  5555. * Get information about all the caches that have been created
  5556. *
  5557. * @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
  5558. */
  5559. cacheFactory.info = function() {
  5560. var info = {};
  5561. forEach(caches, function(cache, cacheId) {
  5562. info[cacheId] = cache.info();
  5563. });
  5564. return info;
  5565. };
  5566. /**
  5567. * @ngdoc method
  5568. * @name $cacheFactory#get
  5569. *
  5570. * @description
  5571. * Get access to a cache object by the `cacheId` used when it was created.
  5572. *
  5573. * @param {string} cacheId Name or id of a cache to access.
  5574. * @returns {object} Cache object identified by the cacheId or undefined if no such cache.
  5575. */
  5576. cacheFactory.get = function(cacheId) {
  5577. return caches[cacheId];
  5578. };
  5579. return cacheFactory;
  5580. };
  5581. }
  5582. /**
  5583. * @ngdoc service
  5584. * @name $templateCache
  5585. *
  5586. * @description
  5587. * The first time a template is used, it is loaded in the template cache for quick retrieval. You
  5588. * can load templates directly into the cache in a `script` tag, or by consuming the
  5589. * `$templateCache` service directly.
  5590. *
  5591. * Adding via the `script` tag:
  5592. *
  5593. * ```html
  5594. * <script type="text/ng-template" id="templateId.html">
  5595. * <p>This is the content of the template</p>
  5596. * </script>
  5597. * ```
  5598. *
  5599. * **Note:** the `script` tag containing the template does not need to be included in the `head` of
  5600. * the document, but it must be a descendent of the {@link ng.$rootElement $rootElement} (IE,
  5601. * element with ng-app attribute), otherwise the template will be ignored.
  5602. *
  5603. * Adding via the `$templateCache` service:
  5604. *
  5605. * ```js
  5606. * var myApp = angular.module('myApp', []);
  5607. * myApp.run(function($templateCache) {
  5608. * $templateCache.put('templateId.html', 'This is the content of the template');
  5609. * });
  5610. * ```
  5611. *
  5612. * To retrieve the template later, simply use it in your HTML:
  5613. * ```html
  5614. * <div ng-include=" 'templateId.html' "></div>
  5615. * ```
  5616. *
  5617. * or get it via Javascript:
  5618. * ```js
  5619. * $templateCache.get('templateId.html')
  5620. * ```
  5621. *
  5622. * See {@link ng.$cacheFactory $cacheFactory}.
  5623. *
  5624. */
  5625. function $TemplateCacheProvider() {
  5626. this.$get = ['$cacheFactory', function($cacheFactory) {
  5627. return $cacheFactory('templates');
  5628. }];
  5629. }
  5630. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  5631. * Any commits to this file should be reviewed with security in mind. *
  5632. * Changes to this file can potentially create security vulnerabilities. *
  5633. * An approval from 2 Core members with history of modifying *
  5634. * this file is required. *
  5635. * *
  5636. * Does the change somehow allow for arbitrary javascript to be executed? *
  5637. * Or allows for someone to change the prototype of built-in objects? *
  5638. * Or gives undesired access to variables likes document or window? *
  5639. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  5640. /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
  5641. *
  5642. * DOM-related variables:
  5643. *
  5644. * - "node" - DOM Node
  5645. * - "element" - DOM Element or Node
  5646. * - "$node" or "$element" - jqLite-wrapped node or element
  5647. *
  5648. *
  5649. * Compiler related stuff:
  5650. *
  5651. * - "linkFn" - linking fn of a single directive
  5652. * - "nodeLinkFn" - function that aggregates all linking fns for a particular node
  5653. * - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
  5654. * - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
  5655. */
  5656. /**
  5657. * @ngdoc service
  5658. * @name $compile
  5659. * @kind function
  5660. *
  5661. * @description
  5662. * Compiles an HTML string or DOM into a template and produces a template function, which
  5663. * can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
  5664. *
  5665. * The compilation is a process of walking the DOM tree and matching DOM elements to
  5666. * {@link ng.$compileProvider#directive directives}.
  5667. *
  5668. * <div class="alert alert-warning">
  5669. * **Note:** This document is an in-depth reference of all directive options.
  5670. * For a gentle introduction to directives with examples of common use cases,
  5671. * see the {@link guide/directive directive guide}.
  5672. * </div>
  5673. *
  5674. * ## Comprehensive Directive API
  5675. *
  5676. * There are many different options for a directive.
  5677. *
  5678. * The difference resides in the return value of the factory function.
  5679. * You can either return a "Directive Definition Object" (see below) that defines the directive properties,
  5680. * or just the `postLink` function (all other properties will have the default values).
  5681. *
  5682. * <div class="alert alert-success">
  5683. * **Best Practice:** It's recommended to use the "directive definition object" form.
  5684. * </div>
  5685. *
  5686. * Here's an example directive declared with a Directive Definition Object:
  5687. *
  5688. * ```js
  5689. * var myModule = angular.module(...);
  5690. *
  5691. * myModule.directive('directiveName', function factory(injectables) {
  5692. * var directiveDefinitionObject = {
  5693. * priority: 0,
  5694. * template: '<div></div>', // or // function(tElement, tAttrs) { ... },
  5695. * // or
  5696. * // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
  5697. * transclude: false,
  5698. * restrict: 'A',
  5699. * templateNamespace: 'html',
  5700. * scope: false,
  5701. * controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
  5702. * controllerAs: 'stringIdentifier',
  5703. * bindToController: false,
  5704. * require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
  5705. * compile: function compile(tElement, tAttrs, transclude) {
  5706. * return {
  5707. * pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5708. * post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5709. * }
  5710. * // or
  5711. * // return function postLink( ... ) { ... }
  5712. * },
  5713. * // or
  5714. * // link: {
  5715. * // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
  5716. * // post: function postLink(scope, iElement, iAttrs, controller) { ... }
  5717. * // }
  5718. * // or
  5719. * // link: function postLink( ... ) { ... }
  5720. * };
  5721. * return directiveDefinitionObject;
  5722. * });
  5723. * ```
  5724. *
  5725. * <div class="alert alert-warning">
  5726. * **Note:** Any unspecified options will use the default value. You can see the default values below.
  5727. * </div>
  5728. *
  5729. * Therefore the above can be simplified as:
  5730. *
  5731. * ```js
  5732. * var myModule = angular.module(...);
  5733. *
  5734. * myModule.directive('directiveName', function factory(injectables) {
  5735. * var directiveDefinitionObject = {
  5736. * link: function postLink(scope, iElement, iAttrs) { ... }
  5737. * };
  5738. * return directiveDefinitionObject;
  5739. * // or
  5740. * // return function postLink(scope, iElement, iAttrs) { ... }
  5741. * });
  5742. * ```
  5743. *
  5744. *
  5745. *
  5746. * ### Directive Definition Object
  5747. *
  5748. * The directive definition object provides instructions to the {@link ng.$compile
  5749. * compiler}. The attributes are:
  5750. *
  5751. * #### `multiElement`
  5752. * When this property is set to true, the HTML compiler will collect DOM nodes between
  5753. * nodes with the attributes `directive-name-start` and `directive-name-end`, and group them
  5754. * together as the directive elements. It is recommended that this feature be used on directives
  5755. * which are not strictly behavioural (such as {@link ngClick}), and which
  5756. * do not manipulate or replace child nodes (such as {@link ngInclude}).
  5757. *
  5758. * #### `priority`
  5759. * When there are multiple directives defined on a single DOM element, sometimes it
  5760. * is necessary to specify the order in which the directives are applied. The `priority` is used
  5761. * to sort the directives before their `compile` functions get called. Priority is defined as a
  5762. * number. Directives with greater numerical `priority` are compiled first. Pre-link functions
  5763. * are also run in priority order, but post-link functions are run in reverse order. The order
  5764. * of directives with the same priority is undefined. The default priority is `0`.
  5765. *
  5766. * #### `terminal`
  5767. * If set to true then the current `priority` will be the last set of directives
  5768. * which will execute (any directives at the current priority will still execute
  5769. * as the order of execution on same `priority` is undefined). Note that expressions
  5770. * and other directives used in the directive's template will also be excluded from execution.
  5771. *
  5772. * #### `scope`
  5773. * The scope property can be `true`, an object or a falsy value:
  5774. *
  5775. * * **falsy:** No scope will be created for the directive. The directive will use its parent's scope.
  5776. *
  5777. * * **`true`:** A new child scope that prototypically inherits from its parent will be created for
  5778. * the directive's element. If multiple directives on the same element request a new scope,
  5779. * only one new scope is created. The new scope rule does not apply for the root of the template
  5780. * since the root of the template always gets a new scope.
  5781. *
  5782. * * **`{...}` (an object hash):** A new "isolate" scope is created for the directive's element. The
  5783. * 'isolate' scope differs from normal scope in that it does not prototypically inherit from its parent
  5784. * scope. This is useful when creating reusable components, which should not accidentally read or modify
  5785. * data in the parent scope.
  5786. *
  5787. * The 'isolate' scope object hash defines a set of local scope properties derived from attributes on the
  5788. * directive's element. These local properties are useful for aliasing values for templates. The keys in
  5789. * the object hash map to the name of the property on the isolate scope; the values define how the property
  5790. * is bound to the parent scope, via matching attributes on the directive's element:
  5791. *
  5792. * * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
  5793. * always a string since DOM attributes are strings. If no `attr` name is specified then the
  5794. * attribute name is assumed to be the same as the local name.
  5795. * Given `<widget my-attr="hello {{name}}">` and widget definition
  5796. * of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
  5797. * the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
  5798. * `localName` property on the widget scope. The `name` is read from the parent scope (not
  5799. * component scope).
  5800. *
  5801. * * `=` or `=attr` - set up bi-directional binding between a local scope property and the
  5802. * parent scope property of name defined via the value of the `attr` attribute. If no `attr`
  5803. * name is specified then the attribute name is assumed to be the same as the local name.
  5804. * Given `<widget my-attr="parentModel">` and widget definition of
  5805. * `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
  5806. * value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
  5807. * in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
  5808. * scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
  5809. * can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional. If
  5810. * you want to shallow watch for changes (i.e. $watchCollection instead of $watch) you can use
  5811. * `=*` or `=*attr` (`=*?` or `=*?attr` if the property is optional).
  5812. *
  5813. * * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
  5814. * If no `attr` name is specified then the attribute name is assumed to be the same as the
  5815. * local name. Given `<widget my-attr="count = count + value">` and widget definition of
  5816. * `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
  5817. * a function wrapper for the `count = count + value` expression. Often it's desirable to
  5818. * pass data from the isolated scope via an expression to the parent scope, this can be
  5819. * done by passing a map of local variable names and values into the expression wrapper fn.
  5820. * For example, if the expression is `increment(amount)` then we can specify the amount value
  5821. * by calling the `localFn` as `localFn({amount: 22})`.
  5822. *
  5823. * In general it's possible to apply more than one directive to one element, but there might be limitations
  5824. * depending on the type of scope required by the directives. The following points will help explain these limitations.
  5825. * For simplicity only two directives are taken into account, but it is also applicable for several directives:
  5826. *
  5827. * * **no scope** + **no scope** => Two directives which don't require their own scope will use their parent's scope
  5828. * * **child scope** + **no scope** => Both directives will share one single child scope
  5829. * * **child scope** + **child scope** => Both directives will share one single child scope
  5830. * * **isolated scope** + **no scope** => The isolated directive will use it's own created isolated scope. The other directive will use
  5831. * its parent's scope
  5832. * * **isolated scope** + **child scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives cannot
  5833. * be applied to the same element.
  5834. * * **isolated scope** + **isolated scope** => **Won't work!** Only one scope can be related to one element. Therefore these directives
  5835. * cannot be applied to the same element.
  5836. *
  5837. *
  5838. * #### `bindToController`
  5839. * When an isolate scope is used for a component (see above), and `controllerAs` is used, `bindToController: true` will
  5840. * allow a component to have its properties bound to the controller, rather than to scope. When the controller
  5841. * is instantiated, the initial values of the isolate scope bindings are already available.
  5842. *
  5843. * #### `controller`
  5844. * Controller constructor function. The controller is instantiated before the
  5845. * pre-linking phase and can be accessed by other directives (see
  5846. * `require` attribute). This allows the directives to communicate with each other and augment
  5847. * each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
  5848. *
  5849. * * `$scope` - Current scope associated with the element
  5850. * * `$element` - Current element
  5851. * * `$attrs` - Current attributes object for the element
  5852. * * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
  5853. * `function([scope], cloneLinkingFn, futureParentElement)`.
  5854. * * `scope`: optional argument to override the scope.
  5855. * * `cloneLinkingFn`: optional argument to create clones of the original transcluded content.
  5856. * * `futureParentElement`:
  5857. * * defines the parent to which the `cloneLinkingFn` will add the cloned elements.
  5858. * * default: `$element.parent()` resp. `$element` for `transclude:'element'` resp. `transclude:true`.
  5859. * * only needed for transcludes that are allowed to contain non html elements (e.g. SVG elements)
  5860. * and when the `cloneLinkinFn` is passed,
  5861. * as those elements need to created and cloned in a special way when they are defined outside their
  5862. * usual containers (e.g. like `<svg>`).
  5863. * * See also the `directive.templateNamespace` property.
  5864. *
  5865. *
  5866. * #### `require`
  5867. * Require another directive and inject its controller as the fourth argument to the linking function. The
  5868. * `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
  5869. * injected argument will be an array in corresponding order. If no such directive can be
  5870. * found, or if the directive does not have a controller, then an error is raised (unless no link function
  5871. * is specified, in which case error checking is skipped). The name can be prefixed with:
  5872. *
  5873. * * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
  5874. * * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
  5875. * * `^` - Locate the required controller by searching the element and its parents. Throw an error if not found.
  5876. * * `^^` - Locate the required controller by searching the element's parents. Throw an error if not found.
  5877. * * `?^` - Attempt to locate the required controller by searching the element and its parents or pass
  5878. * `null` to the `link` fn if not found.
  5879. * * `?^^` - Attempt to locate the required controller by searching the element's parents, or pass
  5880. * `null` to the `link` fn if not found.
  5881. *
  5882. *
  5883. * #### `controllerAs`
  5884. * Identifier name for a reference to the controller in the directive's scope.
  5885. * This allows the controller to be referenced from the directive template. This is especially
  5886. * useful when a directive is used as component, i.e. with an `isolate` scope. It's also possible
  5887. * to use it in a directive without an `isolate` / `new` scope, but you need to be aware that the
  5888. * `controllerAs` reference might overwrite a property that already exists on the parent scope.
  5889. *
  5890. *
  5891. * #### `restrict`
  5892. * String of subset of `EACM` which restricts the directive to a specific directive
  5893. * declaration style. If omitted, the defaults (elements and attributes) are used.
  5894. *
  5895. * * `E` - Element name (default): `<my-directive></my-directive>`
  5896. * * `A` - Attribute (default): `<div my-directive="exp"></div>`
  5897. * * `C` - Class: `<div class="my-directive: exp;"></div>`
  5898. * * `M` - Comment: `<!-- directive: my-directive exp -->`
  5899. *
  5900. *
  5901. * #### `templateNamespace`
  5902. * String representing the document type used by the markup in the template.
  5903. * AngularJS needs this information as those elements need to be created and cloned
  5904. * in a special way when they are defined outside their usual containers like `<svg>` and `<math>`.
  5905. *
  5906. * * `html` - All root nodes in the template are HTML. Root nodes may also be
  5907. * top-level elements such as `<svg>` or `<math>`.
  5908. * * `svg` - The root nodes in the template are SVG elements (excluding `<math>`).
  5909. * * `math` - The root nodes in the template are MathML elements (excluding `<svg>`).
  5910. *
  5911. * If no `templateNamespace` is specified, then the namespace is considered to be `html`.
  5912. *
  5913. * #### `template`
  5914. * HTML markup that may:
  5915. * * Replace the contents of the directive's element (default).
  5916. * * Replace the directive's element itself (if `replace` is true - DEPRECATED).
  5917. * * Wrap the contents of the directive's element (if `transclude` is true).
  5918. *
  5919. * Value may be:
  5920. *
  5921. * * A string. For example `<div red-on-hover>{{delete_str}}</div>`.
  5922. * * A function which takes two arguments `tElement` and `tAttrs` (described in the `compile`
  5923. * function api below) and returns a string value.
  5924. *
  5925. *
  5926. * #### `templateUrl`
  5927. * This is similar to `template` but the template is loaded from the specified URL, asynchronously.
  5928. *
  5929. * Because template loading is asynchronous the compiler will suspend compilation of directives on that element
  5930. * for later when the template has been resolved. In the meantime it will continue to compile and link
  5931. * sibling and parent elements as though this element had not contained any directives.
  5932. *
  5933. * The compiler does not suspend the entire compilation to wait for templates to be loaded because this
  5934. * would result in the whole app "stalling" until all templates are loaded asynchronously - even in the
  5935. * case when only one deeply nested directive has `templateUrl`.
  5936. *
  5937. * Template loading is asynchronous even if the template has been preloaded into the {@link $templateCache}
  5938. *
  5939. * You can specify `templateUrl` as a string representing the URL or as a function which takes two
  5940. * arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
  5941. * a string value representing the url. In either case, the template URL is passed through {@link
  5942. * $sce#getTrustedResourceUrl $sce.getTrustedResourceUrl}.
  5943. *
  5944. *
  5945. * #### `replace` ([*DEPRECATED*!], will be removed in next major release - i.e. v2.0)
  5946. * specify what the template should replace. Defaults to `false`.
  5947. *
  5948. * * `true` - the template will replace the directive's element.
  5949. * * `false` - the template will replace the contents of the directive's element.
  5950. *
  5951. * The replacement process migrates all of the attributes / classes from the old element to the new
  5952. * one. See the {@link guide/directive#template-expanding-directive
  5953. * Directives Guide} for an example.
  5954. *
  5955. * There are very few scenarios where element replacement is required for the application function,
  5956. * the main one being reusable custom components that are used within SVG contexts
  5957. * (because SVG doesn't work with custom elements in the DOM tree).
  5958. *
  5959. * #### `transclude`
  5960. * Extract the contents of the element where the directive appears and make it available to the directive.
  5961. * The contents are compiled and provided to the directive as a **transclusion function**. See the
  5962. * {@link $compile#transclusion Transclusion} section below.
  5963. *
  5964. * There are two kinds of transclusion depending upon whether you want to transclude just the contents of the
  5965. * directive's element or the entire element:
  5966. *
  5967. * * `true` - transclude the content (i.e. the child nodes) of the directive's element.
  5968. * * `'element'` - transclude the whole of the directive's element including any directives on this
  5969. * element that defined at a lower priority than this directive. When used, the `template`
  5970. * property is ignored.
  5971. *
  5972. *
  5973. * #### `compile`
  5974. *
  5975. * ```js
  5976. * function compile(tElement, tAttrs, transclude) { ... }
  5977. * ```
  5978. *
  5979. * The compile function deals with transforming the template DOM. Since most directives do not do
  5980. * template transformation, it is not used often. The compile function takes the following arguments:
  5981. *
  5982. * * `tElement` - template element - The element where the directive has been declared. It is
  5983. * safe to do template transformation on the element and child elements only.
  5984. *
  5985. * * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
  5986. * between all directive compile functions.
  5987. *
  5988. * * `transclude` - [*DEPRECATED*!] A transclude linking function: `function(scope, cloneLinkingFn)`
  5989. *
  5990. * <div class="alert alert-warning">
  5991. * **Note:** The template instance and the link instance may be different objects if the template has
  5992. * been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
  5993. * apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
  5994. * should be done in a linking function rather than in a compile function.
  5995. * </div>
  5996. * <div class="alert alert-warning">
  5997. * **Note:** The compile function cannot handle directives that recursively use themselves in their
  5998. * own templates or compile functions. Compiling these directives results in an infinite loop and a
  5999. * stack overflow errors.
  6000. *
  6001. * This can be avoided by manually using $compile in the postLink function to imperatively compile
  6002. * a directive's template instead of relying on automatic template compilation via `template` or
  6003. * `templateUrl` declaration or manual compilation inside the compile function.
  6004. * </div>
  6005. *
  6006. * <div class="alert alert-danger">
  6007. * **Note:** The `transclude` function that is passed to the compile function is deprecated, as it
  6008. * e.g. does not know about the right outer scope. Please use the transclude function that is passed
  6009. * to the link function instead.
  6010. * </div>
  6011. * A compile function can have a return value which can be either a function or an object.
  6012. *
  6013. * * returning a (post-link) function - is equivalent to registering the linking function via the
  6014. * `link` property of the config object when the compile function is empty.
  6015. *
  6016. * * returning an object with function(s) registered via `pre` and `post` properties - allows you to
  6017. * control when a linking function should be called during the linking phase. See info about
  6018. * pre-linking and post-linking functions below.
  6019. *
  6020. *
  6021. * #### `link`
  6022. * This property is used only if the `compile` property is not defined.
  6023. *
  6024. * ```js
  6025. * function link(scope, iElement, iAttrs, controller, transcludeFn) { ... }
  6026. * ```
  6027. *
  6028. * The link function is responsible for registering DOM listeners as well as updating the DOM. It is
  6029. * executed after the template has been cloned. This is where most of the directive logic will be
  6030. * put.
  6031. *
  6032. * * `scope` - {@link ng.$rootScope.Scope Scope} - The scope to be used by the
  6033. * directive for registering {@link ng.$rootScope.Scope#$watch watches}.
  6034. *
  6035. * * `iElement` - instance element - The element where the directive is to be used. It is safe to
  6036. * manipulate the children of the element only in `postLink` function since the children have
  6037. * already been linked.
  6038. *
  6039. * * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
  6040. * between all directive linking functions.
  6041. *
  6042. * * `controller` - the directive's required controller instance(s) - Instances are shared
  6043. * among all directives, which allows the directives to use the controllers as a communication
  6044. * channel. The exact value depends on the directive's `require` property:
  6045. * * no controller(s) required: the directive's own controller, or `undefined` if it doesn't have one
  6046. * * `string`: the controller instance
  6047. * * `array`: array of controller instances
  6048. *
  6049. * If a required controller cannot be found, and it is optional, the instance is `null`,
  6050. * otherwise the {@link error:$compile:ctreq Missing Required Controller} error is thrown.
  6051. *
  6052. * Note that you can also require the directive's own controller - it will be made available like
  6053. * any other controller.
  6054. *
  6055. * * `transcludeFn` - A transclude linking function pre-bound to the correct transclusion scope.
  6056. * This is the same as the `$transclude`
  6057. * parameter of directive controllers, see there for details.
  6058. * `function([scope], cloneLinkingFn, futureParentElement)`.
  6059. *
  6060. * #### Pre-linking function
  6061. *
  6062. * Executed before the child elements are linked. Not safe to do DOM transformation since the
  6063. * compiler linking function will fail to locate the correct elements for linking.
  6064. *
  6065. * #### Post-linking function
  6066. *
  6067. * Executed after the child elements are linked.
  6068. *
  6069. * Note that child elements that contain `templateUrl` directives will not have been compiled
  6070. * and linked since they are waiting for their template to load asynchronously and their own
  6071. * compilation and linking has been suspended until that occurs.
  6072. *
  6073. * It is safe to do DOM transformation in the post-linking function on elements that are not waiting
  6074. * for their async templates to be resolved.
  6075. *
  6076. *
  6077. * ### Transclusion
  6078. *
  6079. * Transclusion is the process of extracting a collection of DOM elements from one part of the DOM and
  6080. * copying them to another part of the DOM, while maintaining their connection to the original AngularJS
  6081. * scope from where they were taken.
  6082. *
  6083. * Transclusion is used (often with {@link ngTransclude}) to insert the
  6084. * original contents of a directive's element into a specified place in the template of the directive.
  6085. * The benefit of transclusion, over simply moving the DOM elements manually, is that the transcluded
  6086. * content has access to the properties on the scope from which it was taken, even if the directive
  6087. * has isolated scope.
  6088. * See the {@link guide/directive#creating-a-directive-that-wraps-other-elements Directives Guide}.
  6089. *
  6090. * This makes it possible for the widget to have private state for its template, while the transcluded
  6091. * content has access to its originating scope.
  6092. *
  6093. * <div class="alert alert-warning">
  6094. * **Note:** When testing an element transclude directive you must not place the directive at the root of the
  6095. * DOM fragment that is being compiled. See {@link guide/unit-testing#testing-transclusion-directives
  6096. * Testing Transclusion Directives}.
  6097. * </div>
  6098. *
  6099. * #### Transclusion Functions
  6100. *
  6101. * When a directive requests transclusion, the compiler extracts its contents and provides a **transclusion
  6102. * function** to the directive's `link` function and `controller`. This transclusion function is a special
  6103. * **linking function** that will return the compiled contents linked to a new transclusion scope.
  6104. *
  6105. * <div class="alert alert-info">
  6106. * If you are just using {@link ngTransclude} then you don't need to worry about this function, since
  6107. * ngTransclude will deal with it for us.
  6108. * </div>
  6109. *
  6110. * If you want to manually control the insertion and removal of the transcluded content in your directive
  6111. * then you must use this transclude function. When you call a transclude function it returns a a jqLite/JQuery
  6112. * object that contains the compiled DOM, which is linked to the correct transclusion scope.
  6113. *
  6114. * When you call a transclusion function you can pass in a **clone attach function**. This function accepts
  6115. * two parameters, `function(clone, scope) { ... }`, where the `clone` is a fresh compiled copy of your transcluded
  6116. * content and the `scope` is the newly created transclusion scope, to which the clone is bound.
  6117. *
  6118. * <div class="alert alert-info">
  6119. * **Best Practice**: Always provide a `cloneFn` (clone attach function) when you call a translude function
  6120. * since you then get a fresh clone of the original DOM and also have access to the new transclusion scope.
  6121. * </div>
  6122. *
  6123. * It is normal practice to attach your transcluded content (`clone`) to the DOM inside your **clone
  6124. * attach function**:
  6125. *
  6126. * ```js
  6127. * var transcludedContent, transclusionScope;
  6128. *
  6129. * $transclude(function(clone, scope) {
  6130. * element.append(clone);
  6131. * transcludedContent = clone;
  6132. * transclusionScope = scope;
  6133. * });
  6134. * ```
  6135. *
  6136. * Later, if you want to remove the transcluded content from your DOM then you should also destroy the
  6137. * associated transclusion scope:
  6138. *
  6139. * ```js
  6140. * transcludedContent.remove();
  6141. * transclusionScope.$destroy();
  6142. * ```
  6143. *
  6144. * <div class="alert alert-info">
  6145. * **Best Practice**: if you intend to add and remove transcluded content manually in your directive
  6146. * (by calling the transclude function to get the DOM and calling `element.remove()` to remove it),
  6147. * then you are also responsible for calling `$destroy` on the transclusion scope.
  6148. * </div>
  6149. *
  6150. * The built-in DOM manipulation directives, such as {@link ngIf}, {@link ngSwitch} and {@link ngRepeat}
  6151. * automatically destroy their transluded clones as necessary so you do not need to worry about this if
  6152. * you are simply using {@link ngTransclude} to inject the transclusion into your directive.
  6153. *
  6154. *
  6155. * #### Transclusion Scopes
  6156. *
  6157. * When you call a transclude function it returns a DOM fragment that is pre-bound to a **transclusion
  6158. * scope**. This scope is special, in that it is a child of the directive's scope (and so gets destroyed
  6159. * when the directive's scope gets destroyed) but it inherits the properties of the scope from which it
  6160. * was taken.
  6161. *
  6162. * For example consider a directive that uses transclusion and isolated scope. The DOM hierarchy might look
  6163. * like this:
  6164. *
  6165. * ```html
  6166. * <div ng-app>
  6167. * <div isolate>
  6168. * <div transclusion>
  6169. * </div>
  6170. * </div>
  6171. * </div>
  6172. * ```
  6173. *
  6174. * The `$parent` scope hierarchy will look like this:
  6175. *
  6176. * ```
  6177. * - $rootScope
  6178. * - isolate
  6179. * - transclusion
  6180. * ```
  6181. *
  6182. * but the scopes will inherit prototypically from different scopes to their `$parent`.
  6183. *
  6184. * ```
  6185. * - $rootScope
  6186. * - transclusion
  6187. * - isolate
  6188. * ```
  6189. *
  6190. *
  6191. * ### Attributes
  6192. *
  6193. * The {@link ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
  6194. * `link()` or `compile()` functions. It has a variety of uses.
  6195. *
  6196. * accessing *Normalized attribute names:*
  6197. * Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
  6198. * the attributes object allows for normalized access to
  6199. * the attributes.
  6200. *
  6201. * * *Directive inter-communication:* All directives share the same instance of the attributes
  6202. * object which allows the directives to use the attributes object as inter directive
  6203. * communication.
  6204. *
  6205. * * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
  6206. * allowing other directives to read the interpolated value.
  6207. *
  6208. * * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
  6209. * that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
  6210. * the only way to easily get the actual value because during the linking phase the interpolation
  6211. * hasn't been evaluated yet and so the value is at this time set to `undefined`.
  6212. *
  6213. * ```js
  6214. * function linkingFn(scope, elm, attrs, ctrl) {
  6215. * // get the attribute value
  6216. * console.log(attrs.ngModel);
  6217. *
  6218. * // change the attribute
  6219. * attrs.$set('ngModel', 'new value');
  6220. *
  6221. * // observe changes to interpolated attribute
  6222. * attrs.$observe('ngModel', function(value) {
  6223. * console.log('ngModel has changed value to ' + value);
  6224. * });
  6225. * }
  6226. * ```
  6227. *
  6228. * ## Example
  6229. *
  6230. * <div class="alert alert-warning">
  6231. * **Note**: Typically directives are registered with `module.directive`. The example below is
  6232. * to illustrate how `$compile` works.
  6233. * </div>
  6234. *
  6235. <example module="compileExample">
  6236. <file name="index.html">
  6237. <script>
  6238. angular.module('compileExample', [], function($compileProvider) {
  6239. // configure new 'compile' directive by passing a directive
  6240. // factory function. The factory function injects the '$compile'
  6241. $compileProvider.directive('compile', function($compile) {
  6242. // directive factory creates a link function
  6243. return function(scope, element, attrs) {
  6244. scope.$watch(
  6245. function(scope) {
  6246. // watch the 'compile' expression for changes
  6247. return scope.$eval(attrs.compile);
  6248. },
  6249. function(value) {
  6250. // when the 'compile' expression changes
  6251. // assign it into the current DOM
  6252. element.html(value);
  6253. // compile the new DOM and link it to the current
  6254. // scope.
  6255. // NOTE: we only compile .childNodes so that
  6256. // we don't get into infinite loop compiling ourselves
  6257. $compile(element.contents())(scope);
  6258. }
  6259. );
  6260. };
  6261. });
  6262. })
  6263. .controller('GreeterController', ['$scope', function($scope) {
  6264. $scope.name = 'Angular';
  6265. $scope.html = 'Hello {{name}}';
  6266. }]);
  6267. </script>
  6268. <div ng-controller="GreeterController">
  6269. <input ng-model="name"> <br/>
  6270. <textarea ng-model="html"></textarea> <br/>
  6271. <div compile="html"></div>
  6272. </div>
  6273. </file>
  6274. <file name="protractor.js" type="protractor">
  6275. it('should auto compile', function() {
  6276. var textarea = $('textarea');
  6277. var output = $('div[compile]');
  6278. // The initial state reads 'Hello Angular'.
  6279. expect(output.getText()).toBe('Hello Angular');
  6280. textarea.clear();
  6281. textarea.sendKeys('{{name}}!');
  6282. expect(output.getText()).toBe('Angular!');
  6283. });
  6284. </file>
  6285. </example>
  6286. *
  6287. *
  6288. * @param {string|DOMElement} element Element or HTML string to compile into a template function.
  6289. * @param {function(angular.Scope, cloneAttachFn=)} transclude function available to directives - DEPRECATED.
  6290. *
  6291. * <div class="alert alert-danger">
  6292. * **Note:** Passing a `transclude` function to the $compile function is deprecated, as it
  6293. * e.g. will not use the right outer scope. Please pass the transclude function as a
  6294. * `parentBoundTranscludeFn` to the link function instead.
  6295. * </div>
  6296. *
  6297. * @param {number} maxPriority only apply directives lower than given priority (Only effects the
  6298. * root element(s), not their children)
  6299. * @returns {function(scope, cloneAttachFn=, options=)} a link function which is used to bind template
  6300. * (a DOM element/tree) to a scope. Where:
  6301. *
  6302. * * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
  6303. * * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
  6304. * `template` and call the `cloneAttachFn` function allowing the caller to attach the
  6305. * cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
  6306. * called as: <br/> `cloneAttachFn(clonedElement, scope)` where:
  6307. *
  6308. * * `clonedElement` - is a clone of the original `element` passed into the compiler.
  6309. * * `scope` - is the current scope with which the linking function is working with.
  6310. *
  6311. * * `options` - An optional object hash with linking options. If `options` is provided, then the following
  6312. * keys may be used to control linking behavior:
  6313. *
  6314. * * `parentBoundTranscludeFn` - the transclude function made available to
  6315. * directives; if given, it will be passed through to the link functions of
  6316. * directives found in `element` during compilation.
  6317. * * `transcludeControllers` - an object hash with keys that map controller names
  6318. * to controller instances; if given, it will make the controllers
  6319. * available to directives.
  6320. * * `futureParentElement` - defines the parent to which the `cloneAttachFn` will add
  6321. * the cloned elements; only needed for transcludes that are allowed to contain non html
  6322. * elements (e.g. SVG elements). See also the directive.controller property.
  6323. *
  6324. * Calling the linking function returns the element of the template. It is either the original
  6325. * element passed in, or the clone of the element if the `cloneAttachFn` is provided.
  6326. *
  6327. * After linking the view is not updated until after a call to $digest which typically is done by
  6328. * Angular automatically.
  6329. *
  6330. * If you need access to the bound view, there are two ways to do it:
  6331. *
  6332. * - If you are not asking the linking function to clone the template, create the DOM element(s)
  6333. * before you send them to the compiler and keep this reference around.
  6334. * ```js
  6335. * var element = $compile('<p>{{total}}</p>')(scope);
  6336. * ```
  6337. *
  6338. * - if on the other hand, you need the element to be cloned, the view reference from the original
  6339. * example would not point to the clone, but rather to the original template that was cloned. In
  6340. * this case, you can access the clone via the cloneAttachFn:
  6341. * ```js
  6342. * var templateElement = angular.element('<p>{{total}}</p>'),
  6343. * scope = ....;
  6344. *
  6345. * var clonedElement = $compile(templateElement)(scope, function(clonedElement, scope) {
  6346. * //attach the clone to DOM document at the right place
  6347. * });
  6348. *
  6349. * //now we have reference to the cloned DOM via `clonedElement`
  6350. * ```
  6351. *
  6352. *
  6353. * For information on how the compiler works, see the
  6354. * {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
  6355. */
  6356. var $compileMinErr = minErr('$compile');
  6357. /**
  6358. * @ngdoc provider
  6359. * @name $compileProvider
  6360. *
  6361. * @description
  6362. */
  6363. $CompileProvider.$inject = ['$provide', '$$sanitizeUriProvider'];
  6364. function $CompileProvider($provide, $$sanitizeUriProvider) {
  6365. var hasDirectives = {},
  6366. Suffix = 'Directive',
  6367. COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\w\-]+)\s+(.*)$/,
  6368. CLASS_DIRECTIVE_REGEXP = /(([\w\-]+)(?:\:([^;]+))?;?)/,
  6369. ALL_OR_NOTHING_ATTRS = makeMap('ngSrc,ngSrcset,src,srcset'),
  6370. REQUIRE_PREFIX_REGEXP = /^(?:(\^\^?)?(\?)?(\^\^?)?)?/;
  6371. // Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
  6372. // The assumption is that future DOM event attribute names will begin with
  6373. // 'on' and be composed of only English letters.
  6374. var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
  6375. function parseIsolateBindings(scope, directiveName, isController) {
  6376. var LOCAL_REGEXP = /^\s*([@&]|=(\*?))(\??)\s*(\w*)\s*$/;
  6377. var bindings = {};
  6378. forEach(scope, function(definition, scopeName) {
  6379. var match = definition.match(LOCAL_REGEXP);
  6380. if (!match) {
  6381. throw $compileMinErr('iscp',
  6382. "Invalid {3} for directive '{0}'." +
  6383. " Definition: {... {1}: '{2}' ...}",
  6384. directiveName, scopeName, definition,
  6385. (isController ? "controller bindings definition" :
  6386. "isolate scope definition"));
  6387. }
  6388. bindings[scopeName] = {
  6389. mode: match[1][0],
  6390. collection: match[2] === '*',
  6391. optional: match[3] === '?',
  6392. attrName: match[4] || scopeName
  6393. };
  6394. });
  6395. return bindings;
  6396. }
  6397. function parseDirectiveBindings(directive, directiveName) {
  6398. var bindings = {
  6399. isolateScope: null,
  6400. bindToController: null
  6401. };
  6402. if (isObject(directive.scope)) {
  6403. if (directive.bindToController === true) {
  6404. bindings.bindToController = parseIsolateBindings(directive.scope,
  6405. directiveName, true);
  6406. bindings.isolateScope = {};
  6407. } else {
  6408. bindings.isolateScope = parseIsolateBindings(directive.scope,
  6409. directiveName, false);
  6410. }
  6411. }
  6412. if (isObject(directive.bindToController)) {
  6413. bindings.bindToController =
  6414. parseIsolateBindings(directive.bindToController, directiveName, true);
  6415. }
  6416. if (isObject(bindings.bindToController)) {
  6417. var controller = directive.controller;
  6418. var controllerAs = directive.controllerAs;
  6419. if (!controller) {
  6420. // There is no controller, there may or may not be a controllerAs property
  6421. throw $compileMinErr('noctrl',
  6422. "Cannot bind to controller without directive '{0}'s controller.",
  6423. directiveName);
  6424. } else if (!identifierForController(controller, controllerAs)) {
  6425. // There is a controller, but no identifier or controllerAs property
  6426. throw $compileMinErr('noident',
  6427. "Cannot bind to controller without identifier for directive '{0}'.",
  6428. directiveName);
  6429. }
  6430. }
  6431. return bindings;
  6432. }
  6433. function assertValidDirectiveName(name) {
  6434. var letter = name.charAt(0);
  6435. if (!letter || letter !== lowercase(letter)) {
  6436. throw $compileMinErr('baddir', "Directive name '{0}' is invalid. The first character must be a lowercase letter", name);
  6437. }
  6438. if (name !== name.trim()) {
  6439. throw $compileMinErr('baddir',
  6440. "Directive name '{0}' is invalid. The name should not contain leading or trailing whitespaces",
  6441. name);
  6442. }
  6443. }
  6444. /**
  6445. * @ngdoc method
  6446. * @name $compileProvider#directive
  6447. * @kind function
  6448. *
  6449. * @description
  6450. * Register a new directive with the compiler.
  6451. *
  6452. * @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
  6453. * will match as <code>ng-bind</code>), or an object map of directives where the keys are the
  6454. * names and the values are the factories.
  6455. * @param {Function|Array} directiveFactory An injectable directive factory function. See
  6456. * {@link guide/directive} for more info.
  6457. * @returns {ng.$compileProvider} Self for chaining.
  6458. */
  6459. this.directive = function registerDirective(name, directiveFactory) {
  6460. assertNotHasOwnProperty(name, 'directive');
  6461. if (isString(name)) {
  6462. assertValidDirectiveName(name);
  6463. assertArg(directiveFactory, 'directiveFactory');
  6464. if (!hasDirectives.hasOwnProperty(name)) {
  6465. hasDirectives[name] = [];
  6466. $provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
  6467. function($injector, $exceptionHandler) {
  6468. var directives = [];
  6469. forEach(hasDirectives[name], function(directiveFactory, index) {
  6470. try {
  6471. var directive = $injector.invoke(directiveFactory);
  6472. if (isFunction(directive)) {
  6473. directive = { compile: valueFn(directive) };
  6474. } else if (!directive.compile && directive.link) {
  6475. directive.compile = valueFn(directive.link);
  6476. }
  6477. directive.priority = directive.priority || 0;
  6478. directive.index = index;
  6479. directive.name = directive.name || name;
  6480. directive.require = directive.require || (directive.controller && directive.name);
  6481. directive.restrict = directive.restrict || 'EA';
  6482. var bindings = directive.$$bindings =
  6483. parseDirectiveBindings(directive, directive.name);
  6484. if (isObject(bindings.isolateScope)) {
  6485. directive.$$isolateBindings = bindings.isolateScope;
  6486. }
  6487. directive.$$moduleName = directiveFactory.$$moduleName;
  6488. directives.push(directive);
  6489. } catch (e) {
  6490. $exceptionHandler(e);
  6491. }
  6492. });
  6493. return directives;
  6494. }]);
  6495. }
  6496. hasDirectives[name].push(directiveFactory);
  6497. } else {
  6498. forEach(name, reverseParams(registerDirective));
  6499. }
  6500. return this;
  6501. };
  6502. /**
  6503. * @ngdoc method
  6504. * @name $compileProvider#aHrefSanitizationWhitelist
  6505. * @kind function
  6506. *
  6507. * @description
  6508. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6509. * urls during a[href] sanitization.
  6510. *
  6511. * The sanitization is a security measure aimed at preventing XSS attacks via html links.
  6512. *
  6513. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  6514. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  6515. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6516. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6517. *
  6518. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6519. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6520. * chaining otherwise.
  6521. */
  6522. this.aHrefSanitizationWhitelist = function(regexp) {
  6523. if (isDefined(regexp)) {
  6524. $$sanitizeUriProvider.aHrefSanitizationWhitelist(regexp);
  6525. return this;
  6526. } else {
  6527. return $$sanitizeUriProvider.aHrefSanitizationWhitelist();
  6528. }
  6529. };
  6530. /**
  6531. * @ngdoc method
  6532. * @name $compileProvider#imgSrcSanitizationWhitelist
  6533. * @kind function
  6534. *
  6535. * @description
  6536. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  6537. * urls during img[src] sanitization.
  6538. *
  6539. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  6540. *
  6541. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  6542. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  6543. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  6544. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  6545. *
  6546. * @param {RegExp=} regexp New regexp to whitelist urls with.
  6547. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  6548. * chaining otherwise.
  6549. */
  6550. this.imgSrcSanitizationWhitelist = function(regexp) {
  6551. if (isDefined(regexp)) {
  6552. $$sanitizeUriProvider.imgSrcSanitizationWhitelist(regexp);
  6553. return this;
  6554. } else {
  6555. return $$sanitizeUriProvider.imgSrcSanitizationWhitelist();
  6556. }
  6557. };
  6558. /**
  6559. * @ngdoc method
  6560. * @name $compileProvider#debugInfoEnabled
  6561. *
  6562. * @param {boolean=} enabled update the debugInfoEnabled state if provided, otherwise just return the
  6563. * current debugInfoEnabled state
  6564. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  6565. *
  6566. * @kind function
  6567. *
  6568. * @description
  6569. * Call this method to enable/disable various debug runtime information in the compiler such as adding
  6570. * binding information and a reference to the current scope on to DOM elements.
  6571. * If enabled, the compiler will add the following to DOM elements that have been bound to the scope
  6572. * * `ng-binding` CSS class
  6573. * * `$binding` data property containing an array of the binding expressions
  6574. *
  6575. * You may want to disable this in production for a significant performance boost. See
  6576. * {@link guide/production#disabling-debug-data Disabling Debug Data} for more.
  6577. *
  6578. * The default value is true.
  6579. */
  6580. var debugInfoEnabled = true;
  6581. this.debugInfoEnabled = function(enabled) {
  6582. if (isDefined(enabled)) {
  6583. debugInfoEnabled = enabled;
  6584. return this;
  6585. }
  6586. return debugInfoEnabled;
  6587. };
  6588. this.$get = [
  6589. '$injector', '$interpolate', '$exceptionHandler', '$templateRequest', '$parse',
  6590. '$controller', '$rootScope', '$document', '$sce', '$animate', '$$sanitizeUri',
  6591. function($injector, $interpolate, $exceptionHandler, $templateRequest, $parse,
  6592. $controller, $rootScope, $document, $sce, $animate, $$sanitizeUri) {
  6593. var Attributes = function(element, attributesToCopy) {
  6594. if (attributesToCopy) {
  6595. var keys = Object.keys(attributesToCopy);
  6596. var i, l, key;
  6597. for (i = 0, l = keys.length; i < l; i++) {
  6598. key = keys[i];
  6599. this[key] = attributesToCopy[key];
  6600. }
  6601. } else {
  6602. this.$attr = {};
  6603. }
  6604. this.$$element = element;
  6605. };
  6606. Attributes.prototype = {
  6607. /**
  6608. * @ngdoc method
  6609. * @name $compile.directive.Attributes#$normalize
  6610. * @kind function
  6611. *
  6612. * @description
  6613. * Converts an attribute name (e.g. dash/colon/underscore-delimited string, optionally prefixed with `x-` or
  6614. * `data-`) to its normalized, camelCase form.
  6615. *
  6616. * Also there is special case for Moz prefix starting with upper case letter.
  6617. *
  6618. * For further information check out the guide on {@link guide/directive#matching-directives Matching Directives}
  6619. *
  6620. * @param {string} name Name to normalize
  6621. */
  6622. $normalize: directiveNormalize,
  6623. /**
  6624. * @ngdoc method
  6625. * @name $compile.directive.Attributes#$addClass
  6626. * @kind function
  6627. *
  6628. * @description
  6629. * Adds the CSS class value specified by the classVal parameter to the element. If animations
  6630. * are enabled then an animation will be triggered for the class addition.
  6631. *
  6632. * @param {string} classVal The className value that will be added to the element
  6633. */
  6634. $addClass: function(classVal) {
  6635. if (classVal && classVal.length > 0) {
  6636. $animate.addClass(this.$$element, classVal);
  6637. }
  6638. },
  6639. /**
  6640. * @ngdoc method
  6641. * @name $compile.directive.Attributes#$removeClass
  6642. * @kind function
  6643. *
  6644. * @description
  6645. * Removes the CSS class value specified by the classVal parameter from the element. If
  6646. * animations are enabled then an animation will be triggered for the class removal.
  6647. *
  6648. * @param {string} classVal The className value that will be removed from the element
  6649. */
  6650. $removeClass: function(classVal) {
  6651. if (classVal && classVal.length > 0) {
  6652. $animate.removeClass(this.$$element, classVal);
  6653. }
  6654. },
  6655. /**
  6656. * @ngdoc method
  6657. * @name $compile.directive.Attributes#$updateClass
  6658. * @kind function
  6659. *
  6660. * @description
  6661. * Adds and removes the appropriate CSS class values to the element based on the difference
  6662. * between the new and old CSS class values (specified as newClasses and oldClasses).
  6663. *
  6664. * @param {string} newClasses The current CSS className value
  6665. * @param {string} oldClasses The former CSS className value
  6666. */
  6667. $updateClass: function(newClasses, oldClasses) {
  6668. var toAdd = tokenDifference(newClasses, oldClasses);
  6669. if (toAdd && toAdd.length) {
  6670. $animate.addClass(this.$$element, toAdd);
  6671. }
  6672. var toRemove = tokenDifference(oldClasses, newClasses);
  6673. if (toRemove && toRemove.length) {
  6674. $animate.removeClass(this.$$element, toRemove);
  6675. }
  6676. },
  6677. /**
  6678. * Set a normalized attribute on the element in a way such that all directives
  6679. * can share the attribute. This function properly handles boolean attributes.
  6680. * @param {string} key Normalized key. (ie ngAttribute)
  6681. * @param {string|boolean} value The value to set. If `null` attribute will be deleted.
  6682. * @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
  6683. * Defaults to true.
  6684. * @param {string=} attrName Optional none normalized name. Defaults to key.
  6685. */
  6686. $set: function(key, value, writeAttr, attrName) {
  6687. // TODO: decide whether or not to throw an error if "class"
  6688. //is set through this function since it may cause $updateClass to
  6689. //become unstable.
  6690. var node = this.$$element[0],
  6691. booleanKey = getBooleanAttrName(node, key),
  6692. aliasedKey = getAliasedAttrName(key),
  6693. observer = key,
  6694. nodeName;
  6695. if (booleanKey) {
  6696. this.$$element.prop(key, value);
  6697. attrName = booleanKey;
  6698. } else if (aliasedKey) {
  6699. this[aliasedKey] = value;
  6700. observer = aliasedKey;
  6701. }
  6702. this[key] = value;
  6703. // translate normalized key to actual key
  6704. if (attrName) {
  6705. this.$attr[key] = attrName;
  6706. } else {
  6707. attrName = this.$attr[key];
  6708. if (!attrName) {
  6709. this.$attr[key] = attrName = snake_case(key, '-');
  6710. }
  6711. }
  6712. nodeName = nodeName_(this.$$element);
  6713. if ((nodeName === 'a' && key === 'href') ||
  6714. (nodeName === 'img' && key === 'src')) {
  6715. // sanitize a[href] and img[src] values
  6716. this[key] = value = $$sanitizeUri(value, key === 'src');
  6717. } else if (nodeName === 'img' && key === 'srcset') {
  6718. // sanitize img[srcset] values
  6719. var result = "";
  6720. // first check if there are spaces because it's not the same pattern
  6721. var trimmedSrcset = trim(value);
  6722. // ( 999x ,| 999w ,| ,|, )
  6723. var srcPattern = /(\s+\d+x\s*,|\s+\d+w\s*,|\s+,|,\s+)/;
  6724. var pattern = /\s/.test(trimmedSrcset) ? srcPattern : /(,)/;
  6725. // split srcset into tuple of uri and descriptor except for the last item
  6726. var rawUris = trimmedSrcset.split(pattern);
  6727. // for each tuples
  6728. var nbrUrisWith2parts = Math.floor(rawUris.length / 2);
  6729. for (var i = 0; i < nbrUrisWith2parts; i++) {
  6730. var innerIdx = i * 2;
  6731. // sanitize the uri
  6732. result += $$sanitizeUri(trim(rawUris[innerIdx]), true);
  6733. // add the descriptor
  6734. result += (" " + trim(rawUris[innerIdx + 1]));
  6735. }
  6736. // split the last item into uri and descriptor
  6737. var lastTuple = trim(rawUris[i * 2]).split(/\s/);
  6738. // sanitize the last uri
  6739. result += $$sanitizeUri(trim(lastTuple[0]), true);
  6740. // and add the last descriptor if any
  6741. if (lastTuple.length === 2) {
  6742. result += (" " + trim(lastTuple[1]));
  6743. }
  6744. this[key] = value = result;
  6745. }
  6746. if (writeAttr !== false) {
  6747. if (value === null || isUndefined(value)) {
  6748. this.$$element.removeAttr(attrName);
  6749. } else {
  6750. this.$$element.attr(attrName, value);
  6751. }
  6752. }
  6753. // fire observers
  6754. var $$observers = this.$$observers;
  6755. $$observers && forEach($$observers[observer], function(fn) {
  6756. try {
  6757. fn(value);
  6758. } catch (e) {
  6759. $exceptionHandler(e);
  6760. }
  6761. });
  6762. },
  6763. /**
  6764. * @ngdoc method
  6765. * @name $compile.directive.Attributes#$observe
  6766. * @kind function
  6767. *
  6768. * @description
  6769. * Observes an interpolated attribute.
  6770. *
  6771. * The observer function will be invoked once during the next `$digest` following
  6772. * compilation. The observer is then invoked whenever the interpolated value
  6773. * changes.
  6774. *
  6775. * @param {string} key Normalized key. (ie ngAttribute) .
  6776. * @param {function(interpolatedValue)} fn Function that will be called whenever
  6777. the interpolated value of the attribute changes.
  6778. * See the {@link guide/directive#text-and-attribute-bindings Directives} guide for more info.
  6779. * @returns {function()} Returns a deregistration function for this observer.
  6780. */
  6781. $observe: function(key, fn) {
  6782. var attrs = this,
  6783. $$observers = (attrs.$$observers || (attrs.$$observers = createMap())),
  6784. listeners = ($$observers[key] || ($$observers[key] = []));
  6785. listeners.push(fn);
  6786. $rootScope.$evalAsync(function() {
  6787. if (!listeners.$$inter && attrs.hasOwnProperty(key) && !isUndefined(attrs[key])) {
  6788. // no one registered attribute interpolation function, so lets call it manually
  6789. fn(attrs[key]);
  6790. }
  6791. });
  6792. return function() {
  6793. arrayRemove(listeners, fn);
  6794. };
  6795. }
  6796. };
  6797. function safeAddClass($element, className) {
  6798. try {
  6799. $element.addClass(className);
  6800. } catch (e) {
  6801. // ignore, since it means that we are trying to set class on
  6802. // SVG element, where class name is read-only.
  6803. }
  6804. }
  6805. var startSymbol = $interpolate.startSymbol(),
  6806. endSymbol = $interpolate.endSymbol(),
  6807. denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
  6808. ? identity
  6809. : function denormalizeTemplate(template) {
  6810. return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
  6811. },
  6812. NG_ATTR_BINDING = /^ngAttr[A-Z]/;
  6813. var MULTI_ELEMENT_DIR_RE = /^(.+)Start$/;
  6814. compile.$$addBindingInfo = debugInfoEnabled ? function $$addBindingInfo($element, binding) {
  6815. var bindings = $element.data('$binding') || [];
  6816. if (isArray(binding)) {
  6817. bindings = bindings.concat(binding);
  6818. } else {
  6819. bindings.push(binding);
  6820. }
  6821. $element.data('$binding', bindings);
  6822. } : noop;
  6823. compile.$$addBindingClass = debugInfoEnabled ? function $$addBindingClass($element) {
  6824. safeAddClass($element, 'ng-binding');
  6825. } : noop;
  6826. compile.$$addScopeInfo = debugInfoEnabled ? function $$addScopeInfo($element, scope, isolated, noTemplate) {
  6827. var dataName = isolated ? (noTemplate ? '$isolateScopeNoTemplate' : '$isolateScope') : '$scope';
  6828. $element.data(dataName, scope);
  6829. } : noop;
  6830. compile.$$addScopeClass = debugInfoEnabled ? function $$addScopeClass($element, isolated) {
  6831. safeAddClass($element, isolated ? 'ng-isolate-scope' : 'ng-scope');
  6832. } : noop;
  6833. return compile;
  6834. //================================
  6835. function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
  6836. previousCompileContext) {
  6837. if (!($compileNodes instanceof jqLite)) {
  6838. // jquery always rewraps, whereas we need to preserve the original selector so that we can
  6839. // modify it.
  6840. $compileNodes = jqLite($compileNodes);
  6841. }
  6842. // We can not compile top level text elements since text nodes can be merged and we will
  6843. // not be able to attach scope data to them, so we will wrap them in <span>
  6844. forEach($compileNodes, function(node, index) {
  6845. if (node.nodeType == NODE_TYPE_TEXT && node.nodeValue.match(/\S+/) /* non-empty */ ) {
  6846. $compileNodes[index] = jqLite(node).wrap('<span></span>').parent()[0];
  6847. }
  6848. });
  6849. var compositeLinkFn =
  6850. compileNodes($compileNodes, transcludeFn, $compileNodes,
  6851. maxPriority, ignoreDirective, previousCompileContext);
  6852. compile.$$addScopeClass($compileNodes);
  6853. var namespace = null;
  6854. return function publicLinkFn(scope, cloneConnectFn, options) {
  6855. assertArg(scope, 'scope');
  6856. if (previousCompileContext && previousCompileContext.needsNewScope) {
  6857. // A parent directive did a replace and a directive on this element asked
  6858. // for transclusion, which caused us to lose a layer of element on which
  6859. // we could hold the new transclusion scope, so we will create it manually
  6860. // here.
  6861. scope = scope.$parent.$new();
  6862. }
  6863. options = options || {};
  6864. var parentBoundTranscludeFn = options.parentBoundTranscludeFn,
  6865. transcludeControllers = options.transcludeControllers,
  6866. futureParentElement = options.futureParentElement;
  6867. // When `parentBoundTranscludeFn` is passed, it is a
  6868. // `controllersBoundTransclude` function (it was previously passed
  6869. // as `transclude` to directive.link) so we must unwrap it to get
  6870. // its `boundTranscludeFn`
  6871. if (parentBoundTranscludeFn && parentBoundTranscludeFn.$$boundTransclude) {
  6872. parentBoundTranscludeFn = parentBoundTranscludeFn.$$boundTransclude;
  6873. }
  6874. if (!namespace) {
  6875. namespace = detectNamespaceForChildElements(futureParentElement);
  6876. }
  6877. var $linkNode;
  6878. if (namespace !== 'html') {
  6879. // When using a directive with replace:true and templateUrl the $compileNodes
  6880. // (or a child element inside of them)
  6881. // might change, so we need to recreate the namespace adapted compileNodes
  6882. // for call to the link function.
  6883. // Note: This will already clone the nodes...
  6884. $linkNode = jqLite(
  6885. wrapTemplate(namespace, jqLite('<div>').append($compileNodes).html())
  6886. );
  6887. } else if (cloneConnectFn) {
  6888. // important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
  6889. // and sometimes changes the structure of the DOM.
  6890. $linkNode = JQLitePrototype.clone.call($compileNodes);
  6891. } else {
  6892. $linkNode = $compileNodes;
  6893. }
  6894. if (transcludeControllers) {
  6895. for (var controllerName in transcludeControllers) {
  6896. $linkNode.data('$' + controllerName + 'Controller', transcludeControllers[controllerName].instance);
  6897. }
  6898. }
  6899. compile.$$addScopeInfo($linkNode, scope);
  6900. if (cloneConnectFn) cloneConnectFn($linkNode, scope);
  6901. if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode, parentBoundTranscludeFn);
  6902. return $linkNode;
  6903. };
  6904. }
  6905. function detectNamespaceForChildElements(parentElement) {
  6906. // TODO: Make this detect MathML as well...
  6907. var node = parentElement && parentElement[0];
  6908. if (!node) {
  6909. return 'html';
  6910. } else {
  6911. return nodeName_(node) !== 'foreignobject' && node.toString().match(/SVG/) ? 'svg' : 'html';
  6912. }
  6913. }
  6914. /**
  6915. * Compile function matches each node in nodeList against the directives. Once all directives
  6916. * for a particular node are collected their compile functions are executed. The compile
  6917. * functions return values - the linking functions - are combined into a composite linking
  6918. * function, which is the a linking function for the node.
  6919. *
  6920. * @param {NodeList} nodeList an array of nodes or NodeList to compile
  6921. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  6922. * scope argument is auto-generated to the new child of the transcluded parent scope.
  6923. * @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
  6924. * the rootElement must be set the jqLite collection of the compile root. This is
  6925. * needed so that the jqLite collection items can be replaced with widgets.
  6926. * @param {number=} maxPriority Max directive priority.
  6927. * @returns {Function} A composite linking function of all of the matched directives or null.
  6928. */
  6929. function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
  6930. previousCompileContext) {
  6931. var linkFns = [],
  6932. attrs, directives, nodeLinkFn, childNodes, childLinkFn, linkFnFound, nodeLinkFnFound;
  6933. for (var i = 0; i < nodeList.length; i++) {
  6934. attrs = new Attributes();
  6935. // we must always refer to nodeList[i] since the nodes can be replaced underneath us.
  6936. directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
  6937. ignoreDirective);
  6938. nodeLinkFn = (directives.length)
  6939. ? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
  6940. null, [], [], previousCompileContext)
  6941. : null;
  6942. if (nodeLinkFn && nodeLinkFn.scope) {
  6943. compile.$$addScopeClass(attrs.$$element);
  6944. }
  6945. childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
  6946. !(childNodes = nodeList[i].childNodes) ||
  6947. !childNodes.length)
  6948. ? null
  6949. : compileNodes(childNodes,
  6950. nodeLinkFn ? (
  6951. (nodeLinkFn.transcludeOnThisElement || !nodeLinkFn.templateOnThisElement)
  6952. && nodeLinkFn.transclude) : transcludeFn);
  6953. if (nodeLinkFn || childLinkFn) {
  6954. linkFns.push(i, nodeLinkFn, childLinkFn);
  6955. linkFnFound = true;
  6956. nodeLinkFnFound = nodeLinkFnFound || nodeLinkFn;
  6957. }
  6958. //use the previous context only for the first element in the virtual group
  6959. previousCompileContext = null;
  6960. }
  6961. // return a linking function if we have found anything, null otherwise
  6962. return linkFnFound ? compositeLinkFn : null;
  6963. function compositeLinkFn(scope, nodeList, $rootElement, parentBoundTranscludeFn) {
  6964. var nodeLinkFn, childLinkFn, node, childScope, i, ii, idx, childBoundTranscludeFn;
  6965. var stableNodeList;
  6966. if (nodeLinkFnFound) {
  6967. // copy nodeList so that if a nodeLinkFn removes or adds an element at this DOM level our
  6968. // offsets don't get screwed up
  6969. var nodeListLength = nodeList.length;
  6970. stableNodeList = new Array(nodeListLength);
  6971. // create a sparse array by only copying the elements which have a linkFn
  6972. for (i = 0; i < linkFns.length; i+=3) {
  6973. idx = linkFns[i];
  6974. stableNodeList[idx] = nodeList[idx];
  6975. }
  6976. } else {
  6977. stableNodeList = nodeList;
  6978. }
  6979. for (i = 0, ii = linkFns.length; i < ii;) {
  6980. node = stableNodeList[linkFns[i++]];
  6981. nodeLinkFn = linkFns[i++];
  6982. childLinkFn = linkFns[i++];
  6983. if (nodeLinkFn) {
  6984. if (nodeLinkFn.scope) {
  6985. childScope = scope.$new();
  6986. compile.$$addScopeInfo(jqLite(node), childScope);
  6987. } else {
  6988. childScope = scope;
  6989. }
  6990. if (nodeLinkFn.transcludeOnThisElement) {
  6991. childBoundTranscludeFn = createBoundTranscludeFn(
  6992. scope, nodeLinkFn.transclude, parentBoundTranscludeFn);
  6993. } else if (!nodeLinkFn.templateOnThisElement && parentBoundTranscludeFn) {
  6994. childBoundTranscludeFn = parentBoundTranscludeFn;
  6995. } else if (!parentBoundTranscludeFn && transcludeFn) {
  6996. childBoundTranscludeFn = createBoundTranscludeFn(scope, transcludeFn);
  6997. } else {
  6998. childBoundTranscludeFn = null;
  6999. }
  7000. nodeLinkFn(childLinkFn, childScope, node, $rootElement, childBoundTranscludeFn);
  7001. } else if (childLinkFn) {
  7002. childLinkFn(scope, node.childNodes, undefined, parentBoundTranscludeFn);
  7003. }
  7004. }
  7005. }
  7006. }
  7007. function createBoundTranscludeFn(scope, transcludeFn, previousBoundTranscludeFn) {
  7008. var boundTranscludeFn = function(transcludedScope, cloneFn, controllers, futureParentElement, containingScope) {
  7009. if (!transcludedScope) {
  7010. transcludedScope = scope.$new(false, containingScope);
  7011. transcludedScope.$$transcluded = true;
  7012. }
  7013. return transcludeFn(transcludedScope, cloneFn, {
  7014. parentBoundTranscludeFn: previousBoundTranscludeFn,
  7015. transcludeControllers: controllers,
  7016. futureParentElement: futureParentElement
  7017. });
  7018. };
  7019. return boundTranscludeFn;
  7020. }
  7021. /**
  7022. * Looks for directives on the given node and adds them to the directive collection which is
  7023. * sorted.
  7024. *
  7025. * @param node Node to search.
  7026. * @param directives An array to which the directives are added to. This array is sorted before
  7027. * the function returns.
  7028. * @param attrs The shared attrs object which is used to populate the normalized attributes.
  7029. * @param {number=} maxPriority Max directive priority.
  7030. */
  7031. function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
  7032. var nodeType = node.nodeType,
  7033. attrsMap = attrs.$attr,
  7034. match,
  7035. className;
  7036. switch (nodeType) {
  7037. case NODE_TYPE_ELEMENT: /* Element */
  7038. // use the node name: <directive>
  7039. addDirective(directives,
  7040. directiveNormalize(nodeName_(node)), 'E', maxPriority, ignoreDirective);
  7041. // iterate over the attributes
  7042. for (var attr, name, nName, ngAttrName, value, isNgAttr, nAttrs = node.attributes,
  7043. j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
  7044. var attrStartName = false;
  7045. var attrEndName = false;
  7046. attr = nAttrs[j];
  7047. name = attr.name;
  7048. value = trim(attr.value);
  7049. // support ngAttr attribute binding
  7050. ngAttrName = directiveNormalize(name);
  7051. if (isNgAttr = NG_ATTR_BINDING.test(ngAttrName)) {
  7052. name = name.replace(PREFIX_REGEXP, '')
  7053. .substr(8).replace(/_(.)/g, function(match, letter) {
  7054. return letter.toUpperCase();
  7055. });
  7056. }
  7057. var multiElementMatch = ngAttrName.match(MULTI_ELEMENT_DIR_RE);
  7058. if (multiElementMatch && directiveIsMultiElement(multiElementMatch[1])) {
  7059. attrStartName = name;
  7060. attrEndName = name.substr(0, name.length - 5) + 'end';
  7061. name = name.substr(0, name.length - 6);
  7062. }
  7063. nName = directiveNormalize(name.toLowerCase());
  7064. attrsMap[nName] = name;
  7065. if (isNgAttr || !attrs.hasOwnProperty(nName)) {
  7066. attrs[nName] = value;
  7067. if (getBooleanAttrName(node, nName)) {
  7068. attrs[nName] = true; // presence means true
  7069. }
  7070. }
  7071. addAttrInterpolateDirective(node, directives, value, nName, isNgAttr);
  7072. addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
  7073. attrEndName);
  7074. }
  7075. // use class as directive
  7076. className = node.className;
  7077. if (isObject(className)) {
  7078. // Maybe SVGAnimatedString
  7079. className = className.animVal;
  7080. }
  7081. if (isString(className) && className !== '') {
  7082. while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
  7083. nName = directiveNormalize(match[2]);
  7084. if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
  7085. attrs[nName] = trim(match[3]);
  7086. }
  7087. className = className.substr(match.index + match[0].length);
  7088. }
  7089. }
  7090. break;
  7091. case NODE_TYPE_TEXT: /* Text Node */
  7092. if (msie === 11) {
  7093. // Workaround for #11781
  7094. while (node.parentNode && node.nextSibling && node.nextSibling.nodeType === NODE_TYPE_TEXT) {
  7095. node.nodeValue = node.nodeValue + node.nextSibling.nodeValue;
  7096. node.parentNode.removeChild(node.nextSibling);
  7097. }
  7098. }
  7099. addTextInterpolateDirective(directives, node.nodeValue);
  7100. break;
  7101. case NODE_TYPE_COMMENT: /* Comment */
  7102. try {
  7103. match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
  7104. if (match) {
  7105. nName = directiveNormalize(match[1]);
  7106. if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
  7107. attrs[nName] = trim(match[2]);
  7108. }
  7109. }
  7110. } catch (e) {
  7111. // turns out that under some circumstances IE9 throws errors when one attempts to read
  7112. // comment's node value.
  7113. // Just ignore it and continue. (Can't seem to reproduce in test case.)
  7114. }
  7115. break;
  7116. }
  7117. directives.sort(byPriority);
  7118. return directives;
  7119. }
  7120. /**
  7121. * Given a node with an directive-start it collects all of the siblings until it finds
  7122. * directive-end.
  7123. * @param node
  7124. * @param attrStart
  7125. * @param attrEnd
  7126. * @returns {*}
  7127. */
  7128. function groupScan(node, attrStart, attrEnd) {
  7129. var nodes = [];
  7130. var depth = 0;
  7131. if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
  7132. do {
  7133. if (!node) {
  7134. throw $compileMinErr('uterdir',
  7135. "Unterminated attribute, found '{0}' but no matching '{1}' found.",
  7136. attrStart, attrEnd);
  7137. }
  7138. if (node.nodeType == NODE_TYPE_ELEMENT) {
  7139. if (node.hasAttribute(attrStart)) depth++;
  7140. if (node.hasAttribute(attrEnd)) depth--;
  7141. }
  7142. nodes.push(node);
  7143. node = node.nextSibling;
  7144. } while (depth > 0);
  7145. } else {
  7146. nodes.push(node);
  7147. }
  7148. return jqLite(nodes);
  7149. }
  7150. /**
  7151. * Wrapper for linking function which converts normal linking function into a grouped
  7152. * linking function.
  7153. * @param linkFn
  7154. * @param attrStart
  7155. * @param attrEnd
  7156. * @returns {Function}
  7157. */
  7158. function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
  7159. return function(scope, element, attrs, controllers, transcludeFn) {
  7160. element = groupScan(element[0], attrStart, attrEnd);
  7161. return linkFn(scope, element, attrs, controllers, transcludeFn);
  7162. };
  7163. }
  7164. /**
  7165. * Once the directives have been collected, their compile functions are executed. This method
  7166. * is responsible for inlining directive templates as well as terminating the application
  7167. * of the directives if the terminal directive has been reached.
  7168. *
  7169. * @param {Array} directives Array of collected directives to execute their compile function.
  7170. * this needs to be pre-sorted by priority order.
  7171. * @param {Node} compileNode The raw DOM node to apply the compile functions to
  7172. * @param {Object} templateAttrs The shared attribute function
  7173. * @param {function(angular.Scope, cloneAttachFn=)} transcludeFn A linking function, where the
  7174. * scope argument is auto-generated to the new
  7175. * child of the transcluded parent scope.
  7176. * @param {JQLite} jqCollection If we are working on the root of the compile tree then this
  7177. * argument has the root jqLite array so that we can replace nodes
  7178. * on it.
  7179. * @param {Object=} originalReplaceDirective An optional directive that will be ignored when
  7180. * compiling the transclusion.
  7181. * @param {Array.<Function>} preLinkFns
  7182. * @param {Array.<Function>} postLinkFns
  7183. * @param {Object} previousCompileContext Context used for previous compilation of the current
  7184. * node
  7185. * @returns {Function} linkFn
  7186. */
  7187. function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
  7188. jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
  7189. previousCompileContext) {
  7190. previousCompileContext = previousCompileContext || {};
  7191. var terminalPriority = -Number.MAX_VALUE,
  7192. newScopeDirective = previousCompileContext.newScopeDirective,
  7193. controllerDirectives = previousCompileContext.controllerDirectives,
  7194. newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
  7195. templateDirective = previousCompileContext.templateDirective,
  7196. nonTlbTranscludeDirective = previousCompileContext.nonTlbTranscludeDirective,
  7197. hasTranscludeDirective = false,
  7198. hasTemplate = false,
  7199. hasElementTranscludeDirective = previousCompileContext.hasElementTranscludeDirective,
  7200. $compileNode = templateAttrs.$$element = jqLite(compileNode),
  7201. directive,
  7202. directiveName,
  7203. $template,
  7204. replaceDirective = originalReplaceDirective,
  7205. childTranscludeFn = transcludeFn,
  7206. linkFn,
  7207. directiveValue;
  7208. // executes all directives on the current element
  7209. for (var i = 0, ii = directives.length; i < ii; i++) {
  7210. directive = directives[i];
  7211. var attrStart = directive.$$start;
  7212. var attrEnd = directive.$$end;
  7213. // collect multiblock sections
  7214. if (attrStart) {
  7215. $compileNode = groupScan(compileNode, attrStart, attrEnd);
  7216. }
  7217. $template = undefined;
  7218. if (terminalPriority > directive.priority) {
  7219. break; // prevent further processing of directives
  7220. }
  7221. if (directiveValue = directive.scope) {
  7222. // skip the check for directives with async templates, we'll check the derived sync
  7223. // directive when the template arrives
  7224. if (!directive.templateUrl) {
  7225. if (isObject(directiveValue)) {
  7226. // This directive is trying to add an isolated scope.
  7227. // Check that there is no scope of any kind already
  7228. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective || newScopeDirective,
  7229. directive, $compileNode);
  7230. newIsolateScopeDirective = directive;
  7231. } else {
  7232. // This directive is trying to add a child scope.
  7233. // Check that there is no isolated scope already
  7234. assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
  7235. $compileNode);
  7236. }
  7237. }
  7238. newScopeDirective = newScopeDirective || directive;
  7239. }
  7240. directiveName = directive.name;
  7241. if (!directive.templateUrl && directive.controller) {
  7242. directiveValue = directive.controller;
  7243. controllerDirectives = controllerDirectives || createMap();
  7244. assertNoDuplicate("'" + directiveName + "' controller",
  7245. controllerDirectives[directiveName], directive, $compileNode);
  7246. controllerDirectives[directiveName] = directive;
  7247. }
  7248. if (directiveValue = directive.transclude) {
  7249. hasTranscludeDirective = true;
  7250. // Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
  7251. // This option should only be used by directives that know how to safely handle element transclusion,
  7252. // where the transcluded nodes are added or replaced after linking.
  7253. if (!directive.$$tlb) {
  7254. assertNoDuplicate('transclusion', nonTlbTranscludeDirective, directive, $compileNode);
  7255. nonTlbTranscludeDirective = directive;
  7256. }
  7257. if (directiveValue == 'element') {
  7258. hasElementTranscludeDirective = true;
  7259. terminalPriority = directive.priority;
  7260. $template = $compileNode;
  7261. $compileNode = templateAttrs.$$element =
  7262. jqLite(document.createComment(' ' + directiveName + ': ' +
  7263. templateAttrs[directiveName] + ' '));
  7264. compileNode = $compileNode[0];
  7265. replaceWith(jqCollection, sliceArgs($template), compileNode);
  7266. childTranscludeFn = compile($template, transcludeFn, terminalPriority,
  7267. replaceDirective && replaceDirective.name, {
  7268. // Don't pass in:
  7269. // - controllerDirectives - otherwise we'll create duplicates controllers
  7270. // - newIsolateScopeDirective or templateDirective - combining templates with
  7271. // element transclusion doesn't make sense.
  7272. //
  7273. // We need only nonTlbTranscludeDirective so that we prevent putting transclusion
  7274. // on the same element more than once.
  7275. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7276. });
  7277. } else {
  7278. $template = jqLite(jqLiteClone(compileNode)).contents();
  7279. $compileNode.empty(); // clear contents
  7280. childTranscludeFn = compile($template, transcludeFn, undefined,
  7281. undefined, { needsNewScope: directive.$$isolateScope || directive.$$newScope});
  7282. }
  7283. }
  7284. if (directive.template) {
  7285. hasTemplate = true;
  7286. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7287. templateDirective = directive;
  7288. directiveValue = (isFunction(directive.template))
  7289. ? directive.template($compileNode, templateAttrs)
  7290. : directive.template;
  7291. directiveValue = denormalizeTemplate(directiveValue);
  7292. if (directive.replace) {
  7293. replaceDirective = directive;
  7294. if (jqLiteIsTextNode(directiveValue)) {
  7295. $template = [];
  7296. } else {
  7297. $template = removeComments(wrapTemplate(directive.templateNamespace, trim(directiveValue)));
  7298. }
  7299. compileNode = $template[0];
  7300. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7301. throw $compileMinErr('tplrt',
  7302. "Template for directive '{0}' must have exactly one root element. {1}",
  7303. directiveName, '');
  7304. }
  7305. replaceWith(jqCollection, $compileNode, compileNode);
  7306. var newTemplateAttrs = {$attr: {}};
  7307. // combine directives from the original node and from the template:
  7308. // - take the array of directives for this element
  7309. // - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
  7310. // - collect directives from the template and sort them by priority
  7311. // - combine directives as: processed + template + unprocessed
  7312. var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
  7313. var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
  7314. if (newIsolateScopeDirective || newScopeDirective) {
  7315. // The original directive caused the current element to be replaced but this element
  7316. // also needs to have a new scope, so we need to tell the template directives
  7317. // that they would need to get their scope from further up, if they require transclusion
  7318. markDirectiveScope(templateDirectives, newIsolateScopeDirective, newScopeDirective);
  7319. }
  7320. directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
  7321. mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
  7322. ii = directives.length;
  7323. } else {
  7324. $compileNode.html(directiveValue);
  7325. }
  7326. }
  7327. if (directive.templateUrl) {
  7328. hasTemplate = true;
  7329. assertNoDuplicate('template', templateDirective, directive, $compileNode);
  7330. templateDirective = directive;
  7331. if (directive.replace) {
  7332. replaceDirective = directive;
  7333. }
  7334. nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
  7335. templateAttrs, jqCollection, hasTranscludeDirective && childTranscludeFn, preLinkFns, postLinkFns, {
  7336. controllerDirectives: controllerDirectives,
  7337. newScopeDirective: (newScopeDirective !== directive) && newScopeDirective,
  7338. newIsolateScopeDirective: newIsolateScopeDirective,
  7339. templateDirective: templateDirective,
  7340. nonTlbTranscludeDirective: nonTlbTranscludeDirective
  7341. });
  7342. ii = directives.length;
  7343. } else if (directive.compile) {
  7344. try {
  7345. linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
  7346. if (isFunction(linkFn)) {
  7347. addLinkFns(null, linkFn, attrStart, attrEnd);
  7348. } else if (linkFn) {
  7349. addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
  7350. }
  7351. } catch (e) {
  7352. $exceptionHandler(e, startingTag($compileNode));
  7353. }
  7354. }
  7355. if (directive.terminal) {
  7356. nodeLinkFn.terminal = true;
  7357. terminalPriority = Math.max(terminalPriority, directive.priority);
  7358. }
  7359. }
  7360. nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
  7361. nodeLinkFn.transcludeOnThisElement = hasTranscludeDirective;
  7362. nodeLinkFn.templateOnThisElement = hasTemplate;
  7363. nodeLinkFn.transclude = childTranscludeFn;
  7364. previousCompileContext.hasElementTranscludeDirective = hasElementTranscludeDirective;
  7365. // might be normal or delayed nodeLinkFn depending on if templateUrl is present
  7366. return nodeLinkFn;
  7367. ////////////////////
  7368. function addLinkFns(pre, post, attrStart, attrEnd) {
  7369. if (pre) {
  7370. if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
  7371. pre.require = directive.require;
  7372. pre.directiveName = directiveName;
  7373. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7374. pre = cloneAndAnnotateFn(pre, {isolateScope: true});
  7375. }
  7376. preLinkFns.push(pre);
  7377. }
  7378. if (post) {
  7379. if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
  7380. post.require = directive.require;
  7381. post.directiveName = directiveName;
  7382. if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
  7383. post = cloneAndAnnotateFn(post, {isolateScope: true});
  7384. }
  7385. postLinkFns.push(post);
  7386. }
  7387. }
  7388. function getControllers(directiveName, require, $element, elementControllers) {
  7389. var value;
  7390. if (isString(require)) {
  7391. var match = require.match(REQUIRE_PREFIX_REGEXP);
  7392. var name = require.substring(match[0].length);
  7393. var inheritType = match[1] || match[3];
  7394. var optional = match[2] === '?';
  7395. //If only parents then start at the parent element
  7396. if (inheritType === '^^') {
  7397. $element = $element.parent();
  7398. //Otherwise attempt getting the controller from elementControllers in case
  7399. //the element is transcluded (and has no data) and to avoid .data if possible
  7400. } else {
  7401. value = elementControllers && elementControllers[name];
  7402. value = value && value.instance;
  7403. }
  7404. if (!value) {
  7405. var dataName = '$' + name + 'Controller';
  7406. value = inheritType ? $element.inheritedData(dataName) : $element.data(dataName);
  7407. }
  7408. if (!value && !optional) {
  7409. throw $compileMinErr('ctreq',
  7410. "Controller '{0}', required by directive '{1}', can't be found!",
  7411. name, directiveName);
  7412. }
  7413. } else if (isArray(require)) {
  7414. value = [];
  7415. for (var i = 0, ii = require.length; i < ii; i++) {
  7416. value[i] = getControllers(directiveName, require[i], $element, elementControllers);
  7417. }
  7418. }
  7419. return value || null;
  7420. }
  7421. function setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope) {
  7422. var elementControllers = createMap();
  7423. for (var controllerKey in controllerDirectives) {
  7424. var directive = controllerDirectives[controllerKey];
  7425. var locals = {
  7426. $scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
  7427. $element: $element,
  7428. $attrs: attrs,
  7429. $transclude: transcludeFn
  7430. };
  7431. var controller = directive.controller;
  7432. if (controller == '@') {
  7433. controller = attrs[directive.name];
  7434. }
  7435. var controllerInstance = $controller(controller, locals, true, directive.controllerAs);
  7436. // For directives with element transclusion the element is a comment,
  7437. // but jQuery .data doesn't support attaching data to comment nodes as it's hard to
  7438. // clean up (http://bugs.jquery.com/ticket/8335).
  7439. // Instead, we save the controllers for the element in a local hash and attach to .data
  7440. // later, once we have the actual element.
  7441. elementControllers[directive.name] = controllerInstance;
  7442. if (!hasElementTranscludeDirective) {
  7443. $element.data('$' + directive.name + 'Controller', controllerInstance.instance);
  7444. }
  7445. }
  7446. return elementControllers;
  7447. }
  7448. function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
  7449. var linkFn, isolateScope, controllerScope, elementControllers, transcludeFn, $element,
  7450. attrs, removeScopeBindingWatches, removeControllerBindingWatches;
  7451. if (compileNode === linkNode) {
  7452. attrs = templateAttrs;
  7453. $element = templateAttrs.$$element;
  7454. } else {
  7455. $element = jqLite(linkNode);
  7456. attrs = new Attributes($element, templateAttrs);
  7457. }
  7458. controllerScope = scope;
  7459. if (newIsolateScopeDirective) {
  7460. isolateScope = scope.$new(true);
  7461. } else if (newScopeDirective) {
  7462. controllerScope = scope.$parent;
  7463. }
  7464. if (boundTranscludeFn) {
  7465. // track `boundTranscludeFn` so it can be unwrapped if `transcludeFn`
  7466. // is later passed as `parentBoundTranscludeFn` to `publicLinkFn`
  7467. transcludeFn = controllersBoundTransclude;
  7468. transcludeFn.$$boundTransclude = boundTranscludeFn;
  7469. }
  7470. if (controllerDirectives) {
  7471. elementControllers = setupControllers($element, attrs, transcludeFn, controllerDirectives, isolateScope, scope);
  7472. }
  7473. if (newIsolateScopeDirective) {
  7474. // Initialize isolate scope bindings for new isolate scope directive.
  7475. compile.$$addScopeInfo($element, isolateScope, true, !(templateDirective && (templateDirective === newIsolateScopeDirective ||
  7476. templateDirective === newIsolateScopeDirective.$$originalDirective)));
  7477. compile.$$addScopeClass($element, true);
  7478. isolateScope.$$isolateBindings =
  7479. newIsolateScopeDirective.$$isolateBindings;
  7480. removeScopeBindingWatches = initializeDirectiveBindings(scope, attrs, isolateScope,
  7481. isolateScope.$$isolateBindings,
  7482. newIsolateScopeDirective);
  7483. if (removeScopeBindingWatches) {
  7484. isolateScope.$on('$destroy', removeScopeBindingWatches);
  7485. }
  7486. }
  7487. // Initialize bindToController bindings
  7488. for (var name in elementControllers) {
  7489. var controllerDirective = controllerDirectives[name];
  7490. var controller = elementControllers[name];
  7491. var bindings = controllerDirective.$$bindings.bindToController;
  7492. if (controller.identifier && bindings) {
  7493. removeControllerBindingWatches =
  7494. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  7495. }
  7496. var controllerResult = controller();
  7497. if (controllerResult !== controller.instance) {
  7498. // If the controller constructor has a return value, overwrite the instance
  7499. // from setupControllers
  7500. controller.instance = controllerResult;
  7501. $element.data('$' + controllerDirective.name + 'Controller', controllerResult);
  7502. removeControllerBindingWatches && removeControllerBindingWatches();
  7503. removeControllerBindingWatches =
  7504. initializeDirectiveBindings(controllerScope, attrs, controller.instance, bindings, controllerDirective);
  7505. }
  7506. }
  7507. // PRELINKING
  7508. for (i = 0, ii = preLinkFns.length; i < ii; i++) {
  7509. linkFn = preLinkFns[i];
  7510. invokeLinkFn(linkFn,
  7511. linkFn.isolateScope ? isolateScope : scope,
  7512. $element,
  7513. attrs,
  7514. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7515. transcludeFn
  7516. );
  7517. }
  7518. // RECURSION
  7519. // We only pass the isolate scope, if the isolate directive has a template,
  7520. // otherwise the child elements do not belong to the isolate directive.
  7521. var scopeToChild = scope;
  7522. if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
  7523. scopeToChild = isolateScope;
  7524. }
  7525. childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
  7526. // POSTLINKING
  7527. for (i = postLinkFns.length - 1; i >= 0; i--) {
  7528. linkFn = postLinkFns[i];
  7529. invokeLinkFn(linkFn,
  7530. linkFn.isolateScope ? isolateScope : scope,
  7531. $element,
  7532. attrs,
  7533. linkFn.require && getControllers(linkFn.directiveName, linkFn.require, $element, elementControllers),
  7534. transcludeFn
  7535. );
  7536. }
  7537. // This is the function that is injected as `$transclude`.
  7538. // Note: all arguments are optional!
  7539. function controllersBoundTransclude(scope, cloneAttachFn, futureParentElement) {
  7540. var transcludeControllers;
  7541. // No scope passed in:
  7542. if (!isScope(scope)) {
  7543. futureParentElement = cloneAttachFn;
  7544. cloneAttachFn = scope;
  7545. scope = undefined;
  7546. }
  7547. if (hasElementTranscludeDirective) {
  7548. transcludeControllers = elementControllers;
  7549. }
  7550. if (!futureParentElement) {
  7551. futureParentElement = hasElementTranscludeDirective ? $element.parent() : $element;
  7552. }
  7553. return boundTranscludeFn(scope, cloneAttachFn, transcludeControllers, futureParentElement, scopeToChild);
  7554. }
  7555. }
  7556. }
  7557. // Depending upon the context in which a directive finds itself it might need to have a new isolated
  7558. // or child scope created. For instance:
  7559. // * if the directive has been pulled into a template because another directive with a higher priority
  7560. // asked for element transclusion
  7561. // * if the directive itself asks for transclusion but it is at the root of a template and the original
  7562. // element was replaced. See https://github.com/angular/angular.js/issues/12936
  7563. function markDirectiveScope(directives, isolateScope, newScope) {
  7564. for (var j = 0, jj = directives.length; j < jj; j++) {
  7565. directives[j] = inherit(directives[j], {$$isolateScope: isolateScope, $$newScope: newScope});
  7566. }
  7567. }
  7568. /**
  7569. * looks up the directive and decorates it with exception handling and proper parameters. We
  7570. * call this the boundDirective.
  7571. *
  7572. * @param {string} name name of the directive to look up.
  7573. * @param {string} location The directive must be found in specific format.
  7574. * String containing any of theses characters:
  7575. *
  7576. * * `E`: element name
  7577. * * `A': attribute
  7578. * * `C`: class
  7579. * * `M`: comment
  7580. * @returns {boolean} true if directive was added.
  7581. */
  7582. function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
  7583. endAttrName) {
  7584. if (name === ignoreDirective) return null;
  7585. var match = null;
  7586. if (hasDirectives.hasOwnProperty(name)) {
  7587. for (var directive, directives = $injector.get(name + Suffix),
  7588. i = 0, ii = directives.length; i < ii; i++) {
  7589. try {
  7590. directive = directives[i];
  7591. if ((isUndefined(maxPriority) || maxPriority > directive.priority) &&
  7592. directive.restrict.indexOf(location) != -1) {
  7593. if (startAttrName) {
  7594. directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
  7595. }
  7596. tDirectives.push(directive);
  7597. match = directive;
  7598. }
  7599. } catch (e) { $exceptionHandler(e); }
  7600. }
  7601. }
  7602. return match;
  7603. }
  7604. /**
  7605. * looks up the directive and returns true if it is a multi-element directive,
  7606. * and therefore requires DOM nodes between -start and -end markers to be grouped
  7607. * together.
  7608. *
  7609. * @param {string} name name of the directive to look up.
  7610. * @returns true if directive was registered as multi-element.
  7611. */
  7612. function directiveIsMultiElement(name) {
  7613. if (hasDirectives.hasOwnProperty(name)) {
  7614. for (var directive, directives = $injector.get(name + Suffix),
  7615. i = 0, ii = directives.length; i < ii; i++) {
  7616. directive = directives[i];
  7617. if (directive.multiElement) {
  7618. return true;
  7619. }
  7620. }
  7621. }
  7622. return false;
  7623. }
  7624. /**
  7625. * When the element is replaced with HTML template then the new attributes
  7626. * on the template need to be merged with the existing attributes in the DOM.
  7627. * The desired effect is to have both of the attributes present.
  7628. *
  7629. * @param {object} dst destination attributes (original DOM)
  7630. * @param {object} src source attributes (from the directive template)
  7631. */
  7632. function mergeTemplateAttributes(dst, src) {
  7633. var srcAttr = src.$attr,
  7634. dstAttr = dst.$attr,
  7635. $element = dst.$$element;
  7636. // reapply the old attributes to the new element
  7637. forEach(dst, function(value, key) {
  7638. if (key.charAt(0) != '$') {
  7639. if (src[key] && src[key] !== value) {
  7640. value += (key === 'style' ? ';' : ' ') + src[key];
  7641. }
  7642. dst.$set(key, value, true, srcAttr[key]);
  7643. }
  7644. });
  7645. // copy the new attributes on the old attrs object
  7646. forEach(src, function(value, key) {
  7647. if (key == 'class') {
  7648. safeAddClass($element, value);
  7649. dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
  7650. } else if (key == 'style') {
  7651. $element.attr('style', $element.attr('style') + ';' + value);
  7652. dst['style'] = (dst['style'] ? dst['style'] + ';' : '') + value;
  7653. // `dst` will never contain hasOwnProperty as DOM parser won't let it.
  7654. // You will get an "InvalidCharacterError: DOM Exception 5" error if you
  7655. // have an attribute like "has-own-property" or "data-has-own-property", etc.
  7656. } else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
  7657. dst[key] = value;
  7658. dstAttr[key] = srcAttr[key];
  7659. }
  7660. });
  7661. }
  7662. function compileTemplateUrl(directives, $compileNode, tAttrs,
  7663. $rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
  7664. var linkQueue = [],
  7665. afterTemplateNodeLinkFn,
  7666. afterTemplateChildLinkFn,
  7667. beforeTemplateCompileNode = $compileNode[0],
  7668. origAsyncDirective = directives.shift(),
  7669. derivedSyncDirective = inherit(origAsyncDirective, {
  7670. templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
  7671. }),
  7672. templateUrl = (isFunction(origAsyncDirective.templateUrl))
  7673. ? origAsyncDirective.templateUrl($compileNode, tAttrs)
  7674. : origAsyncDirective.templateUrl,
  7675. templateNamespace = origAsyncDirective.templateNamespace;
  7676. $compileNode.empty();
  7677. $templateRequest(templateUrl)
  7678. .then(function(content) {
  7679. var compileNode, tempTemplateAttrs, $template, childBoundTranscludeFn;
  7680. content = denormalizeTemplate(content);
  7681. if (origAsyncDirective.replace) {
  7682. if (jqLiteIsTextNode(content)) {
  7683. $template = [];
  7684. } else {
  7685. $template = removeComments(wrapTemplate(templateNamespace, trim(content)));
  7686. }
  7687. compileNode = $template[0];
  7688. if ($template.length != 1 || compileNode.nodeType !== NODE_TYPE_ELEMENT) {
  7689. throw $compileMinErr('tplrt',
  7690. "Template for directive '{0}' must have exactly one root element. {1}",
  7691. origAsyncDirective.name, templateUrl);
  7692. }
  7693. tempTemplateAttrs = {$attr: {}};
  7694. replaceWith($rootElement, $compileNode, compileNode);
  7695. var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
  7696. if (isObject(origAsyncDirective.scope)) {
  7697. // the original directive that caused the template to be loaded async required
  7698. // an isolate scope
  7699. markDirectiveScope(templateDirectives, true);
  7700. }
  7701. directives = templateDirectives.concat(directives);
  7702. mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
  7703. } else {
  7704. compileNode = beforeTemplateCompileNode;
  7705. $compileNode.html(content);
  7706. }
  7707. directives.unshift(derivedSyncDirective);
  7708. afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
  7709. childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
  7710. previousCompileContext);
  7711. forEach($rootElement, function(node, i) {
  7712. if (node == compileNode) {
  7713. $rootElement[i] = $compileNode[0];
  7714. }
  7715. });
  7716. afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
  7717. while (linkQueue.length) {
  7718. var scope = linkQueue.shift(),
  7719. beforeTemplateLinkNode = linkQueue.shift(),
  7720. linkRootElement = linkQueue.shift(),
  7721. boundTranscludeFn = linkQueue.shift(),
  7722. linkNode = $compileNode[0];
  7723. if (scope.$$destroyed) continue;
  7724. if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
  7725. var oldClasses = beforeTemplateLinkNode.className;
  7726. if (!(previousCompileContext.hasElementTranscludeDirective &&
  7727. origAsyncDirective.replace)) {
  7728. // it was cloned therefore we have to clone as well.
  7729. linkNode = jqLiteClone(compileNode);
  7730. }
  7731. replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
  7732. // Copy in CSS classes from original node
  7733. safeAddClass(jqLite(linkNode), oldClasses);
  7734. }
  7735. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7736. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7737. } else {
  7738. childBoundTranscludeFn = boundTranscludeFn;
  7739. }
  7740. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
  7741. childBoundTranscludeFn);
  7742. }
  7743. linkQueue = null;
  7744. });
  7745. return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, boundTranscludeFn) {
  7746. var childBoundTranscludeFn = boundTranscludeFn;
  7747. if (scope.$$destroyed) return;
  7748. if (linkQueue) {
  7749. linkQueue.push(scope,
  7750. node,
  7751. rootElement,
  7752. childBoundTranscludeFn);
  7753. } else {
  7754. if (afterTemplateNodeLinkFn.transcludeOnThisElement) {
  7755. childBoundTranscludeFn = createBoundTranscludeFn(scope, afterTemplateNodeLinkFn.transclude, boundTranscludeFn);
  7756. }
  7757. afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, childBoundTranscludeFn);
  7758. }
  7759. };
  7760. }
  7761. /**
  7762. * Sorting function for bound directives.
  7763. */
  7764. function byPriority(a, b) {
  7765. var diff = b.priority - a.priority;
  7766. if (diff !== 0) return diff;
  7767. if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
  7768. return a.index - b.index;
  7769. }
  7770. function assertNoDuplicate(what, previousDirective, directive, element) {
  7771. function wrapModuleNameIfDefined(moduleName) {
  7772. return moduleName ?
  7773. (' (module: ' + moduleName + ')') :
  7774. '';
  7775. }
  7776. if (previousDirective) {
  7777. throw $compileMinErr('multidir', 'Multiple directives [{0}{1}, {2}{3}] asking for {4} on: {5}',
  7778. previousDirective.name, wrapModuleNameIfDefined(previousDirective.$$moduleName),
  7779. directive.name, wrapModuleNameIfDefined(directive.$$moduleName), what, startingTag(element));
  7780. }
  7781. }
  7782. function addTextInterpolateDirective(directives, text) {
  7783. var interpolateFn = $interpolate(text, true);
  7784. if (interpolateFn) {
  7785. directives.push({
  7786. priority: 0,
  7787. compile: function textInterpolateCompileFn(templateNode) {
  7788. var templateNodeParent = templateNode.parent(),
  7789. hasCompileParent = !!templateNodeParent.length;
  7790. // When transcluding a template that has bindings in the root
  7791. // we don't have a parent and thus need to add the class during linking fn.
  7792. if (hasCompileParent) compile.$$addBindingClass(templateNodeParent);
  7793. return function textInterpolateLinkFn(scope, node) {
  7794. var parent = node.parent();
  7795. if (!hasCompileParent) compile.$$addBindingClass(parent);
  7796. compile.$$addBindingInfo(parent, interpolateFn.expressions);
  7797. scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
  7798. node[0].nodeValue = value;
  7799. });
  7800. };
  7801. }
  7802. });
  7803. }
  7804. }
  7805. function wrapTemplate(type, template) {
  7806. type = lowercase(type || 'html');
  7807. switch (type) {
  7808. case 'svg':
  7809. case 'math':
  7810. var wrapper = document.createElement('div');
  7811. wrapper.innerHTML = '<' + type + '>' + template + '</' + type + '>';
  7812. return wrapper.childNodes[0].childNodes;
  7813. default:
  7814. return template;
  7815. }
  7816. }
  7817. function getTrustedContext(node, attrNormalizedName) {
  7818. if (attrNormalizedName == "srcdoc") {
  7819. return $sce.HTML;
  7820. }
  7821. var tag = nodeName_(node);
  7822. // maction[xlink:href] can source SVG. It's not limited to <maction>.
  7823. if (attrNormalizedName == "xlinkHref" ||
  7824. (tag == "form" && attrNormalizedName == "action") ||
  7825. (tag != "img" && (attrNormalizedName == "src" ||
  7826. attrNormalizedName == "ngSrc"))) {
  7827. return $sce.RESOURCE_URL;
  7828. }
  7829. }
  7830. function addAttrInterpolateDirective(node, directives, value, name, allOrNothing) {
  7831. var trustedContext = getTrustedContext(node, name);
  7832. allOrNothing = ALL_OR_NOTHING_ATTRS[name] || allOrNothing;
  7833. var interpolateFn = $interpolate(value, true, trustedContext, allOrNothing);
  7834. // no interpolation found -> ignore
  7835. if (!interpolateFn) return;
  7836. if (name === "multiple" && nodeName_(node) === "select") {
  7837. throw $compileMinErr("selmulti",
  7838. "Binding to the 'multiple' attribute is not supported. Element: {0}",
  7839. startingTag(node));
  7840. }
  7841. directives.push({
  7842. priority: 100,
  7843. compile: function() {
  7844. return {
  7845. pre: function attrInterpolatePreLinkFn(scope, element, attr) {
  7846. var $$observers = (attr.$$observers || (attr.$$observers = createMap()));
  7847. if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
  7848. throw $compileMinErr('nodomevents',
  7849. "Interpolations for HTML DOM event attributes are disallowed. Please use the " +
  7850. "ng- versions (such as ng-click instead of onclick) instead.");
  7851. }
  7852. // If the attribute has changed since last $interpolate()ed
  7853. var newValue = attr[name];
  7854. if (newValue !== value) {
  7855. // we need to interpolate again since the attribute value has been updated
  7856. // (e.g. by another directive's compile function)
  7857. // ensure unset/empty values make interpolateFn falsy
  7858. interpolateFn = newValue && $interpolate(newValue, true, trustedContext, allOrNothing);
  7859. value = newValue;
  7860. }
  7861. // if attribute was updated so that there is no interpolation going on we don't want to
  7862. // register any observers
  7863. if (!interpolateFn) return;
  7864. // initialize attr object so that it's ready in case we need the value for isolate
  7865. // scope initialization, otherwise the value would not be available from isolate
  7866. // directive's linking fn during linking phase
  7867. attr[name] = interpolateFn(scope);
  7868. ($$observers[name] || ($$observers[name] = [])).$$inter = true;
  7869. (attr.$$observers && attr.$$observers[name].$$scope || scope).
  7870. $watch(interpolateFn, function interpolateFnWatchAction(newValue, oldValue) {
  7871. //special case for class attribute addition + removal
  7872. //so that class changes can tap into the animation
  7873. //hooks provided by the $animate service. Be sure to
  7874. //skip animations when the first digest occurs (when
  7875. //both the new and the old values are the same) since
  7876. //the CSS classes are the non-interpolated values
  7877. if (name === 'class' && newValue != oldValue) {
  7878. attr.$updateClass(newValue, oldValue);
  7879. } else {
  7880. attr.$set(name, newValue);
  7881. }
  7882. });
  7883. }
  7884. };
  7885. }
  7886. });
  7887. }
  7888. /**
  7889. * This is a special jqLite.replaceWith, which can replace items which
  7890. * have no parents, provided that the containing jqLite collection is provided.
  7891. *
  7892. * @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
  7893. * in the root of the tree.
  7894. * @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
  7895. * the shell, but replace its DOM node reference.
  7896. * @param {Node} newNode The new DOM node.
  7897. */
  7898. function replaceWith($rootElement, elementsToRemove, newNode) {
  7899. var firstElementToRemove = elementsToRemove[0],
  7900. removeCount = elementsToRemove.length,
  7901. parent = firstElementToRemove.parentNode,
  7902. i, ii;
  7903. if ($rootElement) {
  7904. for (i = 0, ii = $rootElement.length; i < ii; i++) {
  7905. if ($rootElement[i] == firstElementToRemove) {
  7906. $rootElement[i++] = newNode;
  7907. for (var j = i, j2 = j + removeCount - 1,
  7908. jj = $rootElement.length;
  7909. j < jj; j++, j2++) {
  7910. if (j2 < jj) {
  7911. $rootElement[j] = $rootElement[j2];
  7912. } else {
  7913. delete $rootElement[j];
  7914. }
  7915. }
  7916. $rootElement.length -= removeCount - 1;
  7917. // If the replaced element is also the jQuery .context then replace it
  7918. // .context is a deprecated jQuery api, so we should set it only when jQuery set it
  7919. // http://api.jquery.com/context/
  7920. if ($rootElement.context === firstElementToRemove) {
  7921. $rootElement.context = newNode;
  7922. }
  7923. break;
  7924. }
  7925. }
  7926. }
  7927. if (parent) {
  7928. parent.replaceChild(newNode, firstElementToRemove);
  7929. }
  7930. // TODO(perf): what's this document fragment for? is it needed? can we at least reuse it?
  7931. var fragment = document.createDocumentFragment();
  7932. fragment.appendChild(firstElementToRemove);
  7933. if (jqLite.hasData(firstElementToRemove)) {
  7934. // Copy over user data (that includes Angular's $scope etc.). Don't copy private
  7935. // data here because there's no public interface in jQuery to do that and copying over
  7936. // event listeners (which is the main use of private data) wouldn't work anyway.
  7937. jqLite.data(newNode, jqLite.data(firstElementToRemove));
  7938. // Remove data of the replaced element. We cannot just call .remove()
  7939. // on the element it since that would deallocate scope that is needed
  7940. // for the new node. Instead, remove the data "manually".
  7941. if (!jQuery) {
  7942. delete jqLite.cache[firstElementToRemove[jqLite.expando]];
  7943. } else {
  7944. // jQuery 2.x doesn't expose the data storage. Use jQuery.cleanData to clean up after
  7945. // the replaced element. The cleanData version monkey-patched by Angular would cause
  7946. // the scope to be trashed and we do need the very same scope to work with the new
  7947. // element. However, we cannot just cache the non-patched version and use it here as
  7948. // that would break if another library patches the method after Angular does (one
  7949. // example is jQuery UI). Instead, set a flag indicating scope destroying should be
  7950. // skipped this one time.
  7951. skipDestroyOnNextJQueryCleanData = true;
  7952. jQuery.cleanData([firstElementToRemove]);
  7953. }
  7954. }
  7955. for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
  7956. var element = elementsToRemove[k];
  7957. jqLite(element).remove(); // must do this way to clean up expando
  7958. fragment.appendChild(element);
  7959. delete elementsToRemove[k];
  7960. }
  7961. elementsToRemove[0] = newNode;
  7962. elementsToRemove.length = 1;
  7963. }
  7964. function cloneAndAnnotateFn(fn, annotation) {
  7965. return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
  7966. }
  7967. function invokeLinkFn(linkFn, scope, $element, attrs, controllers, transcludeFn) {
  7968. try {
  7969. linkFn(scope, $element, attrs, controllers, transcludeFn);
  7970. } catch (e) {
  7971. $exceptionHandler(e, startingTag($element));
  7972. }
  7973. }
  7974. // Set up $watches for isolate scope and controller bindings. This process
  7975. // only occurs for isolate scopes and new scopes with controllerAs.
  7976. function initializeDirectiveBindings(scope, attrs, destination, bindings, directive) {
  7977. var removeWatchCollection = [];
  7978. forEach(bindings, function(definition, scopeName) {
  7979. var attrName = definition.attrName,
  7980. optional = definition.optional,
  7981. mode = definition.mode, // @, =, or &
  7982. lastValue,
  7983. parentGet, parentSet, compare;
  7984. switch (mode) {
  7985. case '@':
  7986. if (!optional && !hasOwnProperty.call(attrs, attrName)) {
  7987. destination[scopeName] = attrs[attrName] = void 0;
  7988. }
  7989. attrs.$observe(attrName, function(value) {
  7990. if (isString(value)) {
  7991. destination[scopeName] = value;
  7992. }
  7993. });
  7994. attrs.$$observers[attrName].$$scope = scope;
  7995. if (isString(attrs[attrName])) {
  7996. // If the attribute has been provided then we trigger an interpolation to ensure
  7997. // the value is there for use in the link fn
  7998. destination[scopeName] = $interpolate(attrs[attrName])(scope);
  7999. }
  8000. break;
  8001. case '=':
  8002. if (!hasOwnProperty.call(attrs, attrName)) {
  8003. if (optional) break;
  8004. attrs[attrName] = void 0;
  8005. }
  8006. if (optional && !attrs[attrName]) break;
  8007. parentGet = $parse(attrs[attrName]);
  8008. if (parentGet.literal) {
  8009. compare = equals;
  8010. } else {
  8011. compare = function(a, b) { return a === b || (a !== a && b !== b); };
  8012. }
  8013. parentSet = parentGet.assign || function() {
  8014. // reset the change, or we will throw this exception on every $digest
  8015. lastValue = destination[scopeName] = parentGet(scope);
  8016. throw $compileMinErr('nonassign',
  8017. "Expression '{0}' used with directive '{1}' is non-assignable!",
  8018. attrs[attrName], directive.name);
  8019. };
  8020. lastValue = destination[scopeName] = parentGet(scope);
  8021. var parentValueWatch = function parentValueWatch(parentValue) {
  8022. if (!compare(parentValue, destination[scopeName])) {
  8023. // we are out of sync and need to copy
  8024. if (!compare(parentValue, lastValue)) {
  8025. // parent changed and it has precedence
  8026. destination[scopeName] = parentValue;
  8027. } else {
  8028. // if the parent can be assigned then do so
  8029. parentSet(scope, parentValue = destination[scopeName]);
  8030. }
  8031. }
  8032. return lastValue = parentValue;
  8033. };
  8034. parentValueWatch.$stateful = true;
  8035. var removeWatch;
  8036. if (definition.collection) {
  8037. removeWatch = scope.$watchCollection(attrs[attrName], parentValueWatch);
  8038. } else {
  8039. removeWatch = scope.$watch($parse(attrs[attrName], parentValueWatch), null, parentGet.literal);
  8040. }
  8041. removeWatchCollection.push(removeWatch);
  8042. break;
  8043. case '&':
  8044. // Don't assign Object.prototype method to scope
  8045. parentGet = attrs.hasOwnProperty(attrName) ? $parse(attrs[attrName]) : noop;
  8046. // Don't assign noop to destination if expression is not valid
  8047. if (parentGet === noop && optional) break;
  8048. destination[scopeName] = function(locals) {
  8049. return parentGet(scope, locals);
  8050. };
  8051. break;
  8052. }
  8053. });
  8054. return removeWatchCollection.length && function removeWatches() {
  8055. for (var i = 0, ii = removeWatchCollection.length; i < ii; ++i) {
  8056. removeWatchCollection[i]();
  8057. }
  8058. };
  8059. }
  8060. }];
  8061. }
  8062. var PREFIX_REGEXP = /^((?:x|data)[\:\-_])/i;
  8063. /**
  8064. * Converts all accepted directives format into proper directive name.
  8065. * @param name Name to normalize
  8066. */
  8067. function directiveNormalize(name) {
  8068. return camelCase(name.replace(PREFIX_REGEXP, ''));
  8069. }
  8070. /**
  8071. * @ngdoc type
  8072. * @name $compile.directive.Attributes
  8073. *
  8074. * @description
  8075. * A shared object between directive compile / linking functions which contains normalized DOM
  8076. * element attributes. The values reflect current binding state `{{ }}`. The normalization is
  8077. * needed since all of these are treated as equivalent in Angular:
  8078. *
  8079. * ```
  8080. * <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
  8081. * ```
  8082. */
  8083. /**
  8084. * @ngdoc property
  8085. * @name $compile.directive.Attributes#$attr
  8086. *
  8087. * @description
  8088. * A map of DOM element attribute names to the normalized name. This is
  8089. * needed to do reverse lookup from normalized name back to actual name.
  8090. */
  8091. /**
  8092. * @ngdoc method
  8093. * @name $compile.directive.Attributes#$set
  8094. * @kind function
  8095. *
  8096. * @description
  8097. * Set DOM element attribute value.
  8098. *
  8099. *
  8100. * @param {string} name Normalized element attribute name of the property to modify. The name is
  8101. * reverse-translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
  8102. * property to the original name.
  8103. * @param {string} value Value to set the attribute to. The value can be an interpolated string.
  8104. */
  8105. /**
  8106. * Closure compiler type information
  8107. */
  8108. function nodesetLinkingFn(
  8109. /* angular.Scope */ scope,
  8110. /* NodeList */ nodeList,
  8111. /* Element */ rootElement,
  8112. /* function(Function) */ boundTranscludeFn
  8113. ) {}
  8114. function directiveLinkingFn(
  8115. /* nodesetLinkingFn */ nodesetLinkingFn,
  8116. /* angular.Scope */ scope,
  8117. /* Node */ node,
  8118. /* Element */ rootElement,
  8119. /* function(Function) */ boundTranscludeFn
  8120. ) {}
  8121. function tokenDifference(str1, str2) {
  8122. var values = '',
  8123. tokens1 = str1.split(/\s+/),
  8124. tokens2 = str2.split(/\s+/);
  8125. outer:
  8126. for (var i = 0; i < tokens1.length; i++) {
  8127. var token = tokens1[i];
  8128. for (var j = 0; j < tokens2.length; j++) {
  8129. if (token == tokens2[j]) continue outer;
  8130. }
  8131. values += (values.length > 0 ? ' ' : '') + token;
  8132. }
  8133. return values;
  8134. }
  8135. function removeComments(jqNodes) {
  8136. jqNodes = jqLite(jqNodes);
  8137. var i = jqNodes.length;
  8138. if (i <= 1) {
  8139. return jqNodes;
  8140. }
  8141. while (i--) {
  8142. var node = jqNodes[i];
  8143. if (node.nodeType === NODE_TYPE_COMMENT) {
  8144. splice.call(jqNodes, i, 1);
  8145. }
  8146. }
  8147. return jqNodes;
  8148. }
  8149. var $controllerMinErr = minErr('$controller');
  8150. var CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
  8151. function identifierForController(controller, ident) {
  8152. if (ident && isString(ident)) return ident;
  8153. if (isString(controller)) {
  8154. var match = CNTRL_REG.exec(controller);
  8155. if (match) return match[3];
  8156. }
  8157. }
  8158. /**
  8159. * @ngdoc provider
  8160. * @name $controllerProvider
  8161. * @description
  8162. * The {@link ng.$controller $controller service} is used by Angular to create new
  8163. * controllers.
  8164. *
  8165. * This provider allows controller registration via the
  8166. * {@link ng.$controllerProvider#register register} method.
  8167. */
  8168. function $ControllerProvider() {
  8169. var controllers = {},
  8170. globals = false;
  8171. /**
  8172. * @ngdoc method
  8173. * @name $controllerProvider#register
  8174. * @param {string|Object} name Controller name, or an object map of controllers where the keys are
  8175. * the names and the values are the constructors.
  8176. * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
  8177. * annotations in the array notation).
  8178. */
  8179. this.register = function(name, constructor) {
  8180. assertNotHasOwnProperty(name, 'controller');
  8181. if (isObject(name)) {
  8182. extend(controllers, name);
  8183. } else {
  8184. controllers[name] = constructor;
  8185. }
  8186. };
  8187. /**
  8188. * @ngdoc method
  8189. * @name $controllerProvider#allowGlobals
  8190. * @description If called, allows `$controller` to find controller constructors on `window`
  8191. */
  8192. this.allowGlobals = function() {
  8193. globals = true;
  8194. };
  8195. this.$get = ['$injector', '$window', function($injector, $window) {
  8196. /**
  8197. * @ngdoc service
  8198. * @name $controller
  8199. * @requires $injector
  8200. *
  8201. * @param {Function|string} constructor If called with a function then it's considered to be the
  8202. * controller constructor function. Otherwise it's considered to be a string which is used
  8203. * to retrieve the controller constructor using the following steps:
  8204. *
  8205. * * check if a controller with given name is registered via `$controllerProvider`
  8206. * * check if evaluating the string on the current scope returns a constructor
  8207. * * if $controllerProvider#allowGlobals, check `window[constructor]` on the global
  8208. * `window` object (not recommended)
  8209. *
  8210. * The string can use the `controller as property` syntax, where the controller instance is published
  8211. * as the specified property on the `scope`; the `scope` must be injected into `locals` param for this
  8212. * to work correctly.
  8213. *
  8214. * @param {Object} locals Injection locals for Controller.
  8215. * @return {Object} Instance of given controller.
  8216. *
  8217. * @description
  8218. * `$controller` service is responsible for instantiating controllers.
  8219. *
  8220. * It's just a simple call to {@link auto.$injector $injector}, but extracted into
  8221. * a service, so that one can override this service with [BC version](https://gist.github.com/1649788).
  8222. */
  8223. return function(expression, locals, later, ident) {
  8224. // PRIVATE API:
  8225. // param `later` --- indicates that the controller's constructor is invoked at a later time.
  8226. // If true, $controller will allocate the object with the correct
  8227. // prototype chain, but will not invoke the controller until a returned
  8228. // callback is invoked.
  8229. // param `ident` --- An optional label which overrides the label parsed from the controller
  8230. // expression, if any.
  8231. var instance, match, constructor, identifier;
  8232. later = later === true;
  8233. if (ident && isString(ident)) {
  8234. identifier = ident;
  8235. }
  8236. if (isString(expression)) {
  8237. match = expression.match(CNTRL_REG);
  8238. if (!match) {
  8239. throw $controllerMinErr('ctrlfmt',
  8240. "Badly formed controller string '{0}'. " +
  8241. "Must match `__name__ as __id__` or `__name__`.", expression);
  8242. }
  8243. constructor = match[1],
  8244. identifier = identifier || match[3];
  8245. expression = controllers.hasOwnProperty(constructor)
  8246. ? controllers[constructor]
  8247. : getter(locals.$scope, constructor, true) ||
  8248. (globals ? getter($window, constructor, true) : undefined);
  8249. assertArgFn(expression, constructor, true);
  8250. }
  8251. if (later) {
  8252. // Instantiate controller later:
  8253. // This machinery is used to create an instance of the object before calling the
  8254. // controller's constructor itself.
  8255. //
  8256. // This allows properties to be added to the controller before the constructor is
  8257. // invoked. Primarily, this is used for isolate scope bindings in $compile.
  8258. //
  8259. // This feature is not intended for use by applications, and is thus not documented
  8260. // publicly.
  8261. // Object creation: http://jsperf.com/create-constructor/2
  8262. var controllerPrototype = (isArray(expression) ?
  8263. expression[expression.length - 1] : expression).prototype;
  8264. instance = Object.create(controllerPrototype || null);
  8265. if (identifier) {
  8266. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8267. }
  8268. var instantiate;
  8269. return instantiate = extend(function() {
  8270. var result = $injector.invoke(expression, instance, locals, constructor);
  8271. if (result !== instance && (isObject(result) || isFunction(result))) {
  8272. instance = result;
  8273. if (identifier) {
  8274. // If result changed, re-assign controllerAs value to scope.
  8275. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8276. }
  8277. }
  8278. return instance;
  8279. }, {
  8280. instance: instance,
  8281. identifier: identifier
  8282. });
  8283. }
  8284. instance = $injector.instantiate(expression, locals, constructor);
  8285. if (identifier) {
  8286. addIdentifier(locals, identifier, instance, constructor || expression.name);
  8287. }
  8288. return instance;
  8289. };
  8290. function addIdentifier(locals, identifier, instance, name) {
  8291. if (!(locals && isObject(locals.$scope))) {
  8292. throw minErr('$controller')('noscp',
  8293. "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
  8294. name, identifier);
  8295. }
  8296. locals.$scope[identifier] = instance;
  8297. }
  8298. }];
  8299. }
  8300. /**
  8301. * @ngdoc service
  8302. * @name $document
  8303. * @requires $window
  8304. *
  8305. * @description
  8306. * A {@link angular.element jQuery or jqLite} wrapper for the browser's `window.document` object.
  8307. *
  8308. * @example
  8309. <example module="documentExample">
  8310. <file name="index.html">
  8311. <div ng-controller="ExampleController">
  8312. <p>$document title: <b ng-bind="title"></b></p>
  8313. <p>window.document title: <b ng-bind="windowTitle"></b></p>
  8314. </div>
  8315. </file>
  8316. <file name="script.js">
  8317. angular.module('documentExample', [])
  8318. .controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  8319. $scope.title = $document[0].title;
  8320. $scope.windowTitle = angular.element(window.document)[0].title;
  8321. }]);
  8322. </file>
  8323. </example>
  8324. */
  8325. function $DocumentProvider() {
  8326. this.$get = ['$window', function(window) {
  8327. return jqLite(window.document);
  8328. }];
  8329. }
  8330. /**
  8331. * @ngdoc service
  8332. * @name $exceptionHandler
  8333. * @requires ng.$log
  8334. *
  8335. * @description
  8336. * Any uncaught exception in angular expressions is delegated to this service.
  8337. * The default implementation simply delegates to `$log.error` which logs it into
  8338. * the browser console.
  8339. *
  8340. * In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
  8341. * {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
  8342. *
  8343. * ## Example:
  8344. *
  8345. * ```js
  8346. * angular.module('exceptionOverride', []).factory('$exceptionHandler', function() {
  8347. * return function(exception, cause) {
  8348. * exception.message += ' (caused by "' + cause + '")';
  8349. * throw exception;
  8350. * };
  8351. * });
  8352. * ```
  8353. *
  8354. * This example will override the normal action of `$exceptionHandler`, to make angular
  8355. * exceptions fail hard when they happen, instead of just logging to the console.
  8356. *
  8357. * <hr />
  8358. * Note, that code executed in event-listeners (even those registered using jqLite's `on`/`bind`
  8359. * methods) does not delegate exceptions to the {@link ng.$exceptionHandler $exceptionHandler}
  8360. * (unless executed during a digest).
  8361. *
  8362. * If you wish, you can manually delegate exceptions, e.g.
  8363. * `try { ... } catch(e) { $exceptionHandler(e); }`
  8364. *
  8365. * @param {Error} exception Exception associated with the error.
  8366. * @param {string=} cause optional information about the context in which
  8367. * the error was thrown.
  8368. *
  8369. */
  8370. function $ExceptionHandlerProvider() {
  8371. this.$get = ['$log', function($log) {
  8372. return function(exception, cause) {
  8373. $log.error.apply($log, arguments);
  8374. };
  8375. }];
  8376. }
  8377. var $$ForceReflowProvider = function() {
  8378. this.$get = ['$document', function($document) {
  8379. return function(domNode) {
  8380. //the line below will force the browser to perform a repaint so
  8381. //that all the animated elements within the animation frame will
  8382. //be properly updated and drawn on screen. This is required to
  8383. //ensure that the preparation animation is properly flushed so that
  8384. //the active state picks up from there. DO NOT REMOVE THIS LINE.
  8385. //DO NOT OPTIMIZE THIS LINE. THE MINIFIER WILL REMOVE IT OTHERWISE WHICH
  8386. //WILL RESULT IN AN UNPREDICTABLE BUG THAT IS VERY HARD TO TRACK DOWN AND
  8387. //WILL TAKE YEARS AWAY FROM YOUR LIFE.
  8388. if (domNode) {
  8389. if (!domNode.nodeType && domNode instanceof jqLite) {
  8390. domNode = domNode[0];
  8391. }
  8392. } else {
  8393. domNode = $document[0].body;
  8394. }
  8395. return domNode.offsetWidth + 1;
  8396. };
  8397. }];
  8398. };
  8399. var APPLICATION_JSON = 'application/json';
  8400. var CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': APPLICATION_JSON + ';charset=utf-8'};
  8401. var JSON_START = /^\[|^\{(?!\{)/;
  8402. var JSON_ENDS = {
  8403. '[': /]$/,
  8404. '{': /}$/
  8405. };
  8406. var JSON_PROTECTION_PREFIX = /^\)\]\}',?\n/;
  8407. var $httpMinErr = minErr('$http');
  8408. var $httpMinErrLegacyFn = function(method) {
  8409. return function() {
  8410. throw $httpMinErr('legacy', 'The method `{0}` on the promise returned from `$http` has been disabled.', method);
  8411. };
  8412. };
  8413. function serializeValue(v) {
  8414. if (isObject(v)) {
  8415. return isDate(v) ? v.toISOString() : toJson(v);
  8416. }
  8417. return v;
  8418. }
  8419. function $HttpParamSerializerProvider() {
  8420. /**
  8421. * @ngdoc service
  8422. * @name $httpParamSerializer
  8423. * @description
  8424. *
  8425. * Default {@link $http `$http`} params serializer that converts objects to strings
  8426. * according to the following rules:
  8427. *
  8428. * * `{'foo': 'bar'}` results in `foo=bar`
  8429. * * `{'foo': Date.now()}` results in `foo=2015-04-01T09%3A50%3A49.262Z` (`toISOString()` and encoded representation of a Date object)
  8430. * * `{'foo': ['bar', 'baz']}` results in `foo=bar&foo=baz` (repeated key for each array element)
  8431. * * `{'foo': {'bar':'baz'}}` results in `foo=%7B%22bar%22%3A%22baz%22%7D"` (stringified and encoded representation of an object)
  8432. *
  8433. * Note that serializer will sort the request parameters alphabetically.
  8434. * */
  8435. this.$get = function() {
  8436. return function ngParamSerializer(params) {
  8437. if (!params) return '';
  8438. var parts = [];
  8439. forEachSorted(params, function(value, key) {
  8440. if (value === null || isUndefined(value)) return;
  8441. if (isArray(value)) {
  8442. forEach(value, function(v, k) {
  8443. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(v)));
  8444. });
  8445. } else {
  8446. parts.push(encodeUriQuery(key) + '=' + encodeUriQuery(serializeValue(value)));
  8447. }
  8448. });
  8449. return parts.join('&');
  8450. };
  8451. };
  8452. }
  8453. function $HttpParamSerializerJQLikeProvider() {
  8454. /**
  8455. * @ngdoc service
  8456. * @name $httpParamSerializerJQLike
  8457. * @description
  8458. *
  8459. * Alternative {@link $http `$http`} params serializer that follows
  8460. * jQuery's [`param()`](http://api.jquery.com/jquery.param/) method logic.
  8461. * The serializer will also sort the params alphabetically.
  8462. *
  8463. * To use it for serializing `$http` request parameters, set it as the `paramSerializer` property:
  8464. *
  8465. * ```js
  8466. * $http({
  8467. * url: myUrl,
  8468. * method: 'GET',
  8469. * params: myParams,
  8470. * paramSerializer: '$httpParamSerializerJQLike'
  8471. * });
  8472. * ```
  8473. *
  8474. * It is also possible to set it as the default `paramSerializer` in the
  8475. * {@link $httpProvider#defaults `$httpProvider`}.
  8476. *
  8477. * Additionally, you can inject the serializer and use it explicitly, for example to serialize
  8478. * form data for submission:
  8479. *
  8480. * ```js
  8481. * .controller(function($http, $httpParamSerializerJQLike) {
  8482. * //...
  8483. *
  8484. * $http({
  8485. * url: myUrl,
  8486. * method: 'POST',
  8487. * data: $httpParamSerializerJQLike(myData),
  8488. * headers: {
  8489. * 'Content-Type': 'application/x-www-form-urlencoded'
  8490. * }
  8491. * });
  8492. *
  8493. * });
  8494. * ```
  8495. *
  8496. * */
  8497. this.$get = function() {
  8498. return function jQueryLikeParamSerializer(params) {
  8499. if (!params) return '';
  8500. var parts = [];
  8501. serialize(params, '', true);
  8502. return parts.join('&');
  8503. function serialize(toSerialize, prefix, topLevel) {
  8504. if (toSerialize === null || isUndefined(toSerialize)) return;
  8505. if (isArray(toSerialize)) {
  8506. forEach(toSerialize, function(value, index) {
  8507. serialize(value, prefix + '[' + (isObject(value) ? index : '') + ']');
  8508. });
  8509. } else if (isObject(toSerialize) && !isDate(toSerialize)) {
  8510. forEachSorted(toSerialize, function(value, key) {
  8511. serialize(value, prefix +
  8512. (topLevel ? '' : '[') +
  8513. key +
  8514. (topLevel ? '' : ']'));
  8515. });
  8516. } else {
  8517. parts.push(encodeUriQuery(prefix) + '=' + encodeUriQuery(serializeValue(toSerialize)));
  8518. }
  8519. }
  8520. };
  8521. };
  8522. }
  8523. function defaultHttpResponseTransform(data, headers) {
  8524. if (isString(data)) {
  8525. // Strip json vulnerability protection prefix and trim whitespace
  8526. var tempData = data.replace(JSON_PROTECTION_PREFIX, '').trim();
  8527. if (tempData) {
  8528. var contentType = headers('Content-Type');
  8529. if ((contentType && (contentType.indexOf(APPLICATION_JSON) === 0)) || isJsonLike(tempData)) {
  8530. data = fromJson(tempData);
  8531. }
  8532. }
  8533. }
  8534. return data;
  8535. }
  8536. function isJsonLike(str) {
  8537. var jsonStart = str.match(JSON_START);
  8538. return jsonStart && JSON_ENDS[jsonStart[0]].test(str);
  8539. }
  8540. /**
  8541. * Parse headers into key value object
  8542. *
  8543. * @param {string} headers Raw headers as a string
  8544. * @returns {Object} Parsed headers as key value object
  8545. */
  8546. function parseHeaders(headers) {
  8547. var parsed = createMap(), i;
  8548. function fillInParsed(key, val) {
  8549. if (key) {
  8550. parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
  8551. }
  8552. }
  8553. if (isString(headers)) {
  8554. forEach(headers.split('\n'), function(line) {
  8555. i = line.indexOf(':');
  8556. fillInParsed(lowercase(trim(line.substr(0, i))), trim(line.substr(i + 1)));
  8557. });
  8558. } else if (isObject(headers)) {
  8559. forEach(headers, function(headerVal, headerKey) {
  8560. fillInParsed(lowercase(headerKey), trim(headerVal));
  8561. });
  8562. }
  8563. return parsed;
  8564. }
  8565. /**
  8566. * Returns a function that provides access to parsed headers.
  8567. *
  8568. * Headers are lazy parsed when first requested.
  8569. * @see parseHeaders
  8570. *
  8571. * @param {(string|Object)} headers Headers to provide access to.
  8572. * @returns {function(string=)} Returns a getter function which if called with:
  8573. *
  8574. * - if called with single an argument returns a single header value or null
  8575. * - if called with no arguments returns an object containing all headers.
  8576. */
  8577. function headersGetter(headers) {
  8578. var headersObj;
  8579. return function(name) {
  8580. if (!headersObj) headersObj = parseHeaders(headers);
  8581. if (name) {
  8582. var value = headersObj[lowercase(name)];
  8583. if (value === void 0) {
  8584. value = null;
  8585. }
  8586. return value;
  8587. }
  8588. return headersObj;
  8589. };
  8590. }
  8591. /**
  8592. * Chain all given functions
  8593. *
  8594. * This function is used for both request and response transforming
  8595. *
  8596. * @param {*} data Data to transform.
  8597. * @param {function(string=)} headers HTTP headers getter fn.
  8598. * @param {number} status HTTP status code of the response.
  8599. * @param {(Function|Array.<Function>)} fns Function or an array of functions.
  8600. * @returns {*} Transformed data.
  8601. */
  8602. function transformData(data, headers, status, fns) {
  8603. if (isFunction(fns)) {
  8604. return fns(data, headers, status);
  8605. }
  8606. forEach(fns, function(fn) {
  8607. data = fn(data, headers, status);
  8608. });
  8609. return data;
  8610. }
  8611. function isSuccess(status) {
  8612. return 200 <= status && status < 300;
  8613. }
  8614. /**
  8615. * @ngdoc provider
  8616. * @name $httpProvider
  8617. * @description
  8618. * Use `$httpProvider` to change the default behavior of the {@link ng.$http $http} service.
  8619. * */
  8620. function $HttpProvider() {
  8621. /**
  8622. * @ngdoc property
  8623. * @name $httpProvider#defaults
  8624. * @description
  8625. *
  8626. * Object containing default values for all {@link ng.$http $http} requests.
  8627. *
  8628. * - **`defaults.cache`** - {Object} - an object built with {@link ng.$cacheFactory `$cacheFactory`}
  8629. * that will provide the cache for all requests who set their `cache` property to `true`.
  8630. * If you set the `defaults.cache = false` then only requests that specify their own custom
  8631. * cache object will be cached. See {@link $http#caching $http Caching} for more information.
  8632. *
  8633. * - **`defaults.xsrfCookieName`** - {string} - Name of cookie containing the XSRF token.
  8634. * Defaults value is `'XSRF-TOKEN'`.
  8635. *
  8636. * - **`defaults.xsrfHeaderName`** - {string} - Name of HTTP header to populate with the
  8637. * XSRF token. Defaults value is `'X-XSRF-TOKEN'`.
  8638. *
  8639. * - **`defaults.headers`** - {Object} - Default headers for all $http requests.
  8640. * Refer to {@link ng.$http#setting-http-headers $http} for documentation on
  8641. * setting default headers.
  8642. * - **`defaults.headers.common`**
  8643. * - **`defaults.headers.post`**
  8644. * - **`defaults.headers.put`**
  8645. * - **`defaults.headers.patch`**
  8646. *
  8647. *
  8648. * - **`defaults.paramSerializer`** - `{string|function(Object<string,string>):string}` - A function
  8649. * used to the prepare string representation of request parameters (specified as an object).
  8650. * If specified as string, it is interpreted as a function registered with the {@link auto.$injector $injector}.
  8651. * Defaults to {@link ng.$httpParamSerializer $httpParamSerializer}.
  8652. *
  8653. **/
  8654. var defaults = this.defaults = {
  8655. // transform incoming response data
  8656. transformResponse: [defaultHttpResponseTransform],
  8657. // transform outgoing request data
  8658. transformRequest: [function(d) {
  8659. return isObject(d) && !isFile(d) && !isBlob(d) && !isFormData(d) ? toJson(d) : d;
  8660. }],
  8661. // default headers
  8662. headers: {
  8663. common: {
  8664. 'Accept': 'application/json, text/plain, */*'
  8665. },
  8666. post: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8667. put: shallowCopy(CONTENT_TYPE_APPLICATION_JSON),
  8668. patch: shallowCopy(CONTENT_TYPE_APPLICATION_JSON)
  8669. },
  8670. xsrfCookieName: 'XSRF-TOKEN',
  8671. xsrfHeaderName: 'X-XSRF-TOKEN',
  8672. paramSerializer: '$httpParamSerializer'
  8673. };
  8674. var useApplyAsync = false;
  8675. /**
  8676. * @ngdoc method
  8677. * @name $httpProvider#useApplyAsync
  8678. * @description
  8679. *
  8680. * Configure $http service to combine processing of multiple http responses received at around
  8681. * the same time via {@link ng.$rootScope.Scope#$applyAsync $rootScope.$applyAsync}. This can result in
  8682. * significant performance improvement for bigger applications that make many HTTP requests
  8683. * concurrently (common during application bootstrap).
  8684. *
  8685. * Defaults to false. If no value is specified, returns the current configured value.
  8686. *
  8687. * @param {boolean=} value If true, when requests are loaded, they will schedule a deferred
  8688. * "apply" on the next tick, giving time for subsequent requests in a roughly ~10ms window
  8689. * to load and share the same digest cycle.
  8690. *
  8691. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8692. * otherwise, returns the current configured value.
  8693. **/
  8694. this.useApplyAsync = function(value) {
  8695. if (isDefined(value)) {
  8696. useApplyAsync = !!value;
  8697. return this;
  8698. }
  8699. return useApplyAsync;
  8700. };
  8701. var useLegacyPromise = true;
  8702. /**
  8703. * @ngdoc method
  8704. * @name $httpProvider#useLegacyPromiseExtensions
  8705. * @description
  8706. *
  8707. * Configure `$http` service to return promises without the shorthand methods `success` and `error`.
  8708. * This should be used to make sure that applications work without these methods.
  8709. *
  8710. * Defaults to true. If no value is specified, returns the current configured value.
  8711. *
  8712. * @param {boolean=} value If true, `$http` will return a promise with the deprecated legacy `success` and `error` methods.
  8713. *
  8714. * @returns {boolean|Object} If a value is specified, returns the $httpProvider for chaining.
  8715. * otherwise, returns the current configured value.
  8716. **/
  8717. this.useLegacyPromiseExtensions = function(value) {
  8718. if (isDefined(value)) {
  8719. useLegacyPromise = !!value;
  8720. return this;
  8721. }
  8722. return useLegacyPromise;
  8723. };
  8724. /**
  8725. * @ngdoc property
  8726. * @name $httpProvider#interceptors
  8727. * @description
  8728. *
  8729. * Array containing service factories for all synchronous or asynchronous {@link ng.$http $http}
  8730. * pre-processing of request or postprocessing of responses.
  8731. *
  8732. * These service factories are ordered by request, i.e. they are applied in the same order as the
  8733. * array, on request, but reverse order, on response.
  8734. *
  8735. * {@link ng.$http#interceptors Interceptors detailed info}
  8736. **/
  8737. var interceptorFactories = this.interceptors = [];
  8738. this.$get = ['$httpBackend', '$$cookieReader', '$cacheFactory', '$rootScope', '$q', '$injector',
  8739. function($httpBackend, $$cookieReader, $cacheFactory, $rootScope, $q, $injector) {
  8740. var defaultCache = $cacheFactory('$http');
  8741. /**
  8742. * Make sure that default param serializer is exposed as a function
  8743. */
  8744. defaults.paramSerializer = isString(defaults.paramSerializer) ?
  8745. $injector.get(defaults.paramSerializer) : defaults.paramSerializer;
  8746. /**
  8747. * Interceptors stored in reverse order. Inner interceptors before outer interceptors.
  8748. * The reversal is needed so that we can build up the interception chain around the
  8749. * server request.
  8750. */
  8751. var reversedInterceptors = [];
  8752. forEach(interceptorFactories, function(interceptorFactory) {
  8753. reversedInterceptors.unshift(isString(interceptorFactory)
  8754. ? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
  8755. });
  8756. /**
  8757. * @ngdoc service
  8758. * @kind function
  8759. * @name $http
  8760. * @requires ng.$httpBackend
  8761. * @requires $cacheFactory
  8762. * @requires $rootScope
  8763. * @requires $q
  8764. * @requires $injector
  8765. *
  8766. * @description
  8767. * The `$http` service is a core Angular service that facilitates communication with the remote
  8768. * HTTP servers via the browser's [XMLHttpRequest](https://developer.mozilla.org/en/xmlhttprequest)
  8769. * object or via [JSONP](http://en.wikipedia.org/wiki/JSONP).
  8770. *
  8771. * For unit testing applications that use `$http` service, see
  8772. * {@link ngMock.$httpBackend $httpBackend mock}.
  8773. *
  8774. * For a higher level of abstraction, please check out the {@link ngResource.$resource
  8775. * $resource} service.
  8776. *
  8777. * The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
  8778. * the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
  8779. * it is important to familiarize yourself with these APIs and the guarantees they provide.
  8780. *
  8781. *
  8782. * ## General usage
  8783. * The `$http` service is a function which takes a single argument — a {@link $http#usage configuration object} —
  8784. * that is used to generate an HTTP request and returns a {@link ng.$q promise}.
  8785. *
  8786. * ```js
  8787. * // Simple GET request example:
  8788. * $http({
  8789. * method: 'GET',
  8790. * url: '/someUrl'
  8791. * }).then(function successCallback(response) {
  8792. * // this callback will be called asynchronously
  8793. * // when the response is available
  8794. * }, function errorCallback(response) {
  8795. * // called asynchronously if an error occurs
  8796. * // or server returns response with an error status.
  8797. * });
  8798. * ```
  8799. *
  8800. * The response object has these properties:
  8801. *
  8802. * - **data** – `{string|Object}` – The response body transformed with the transform
  8803. * functions.
  8804. * - **status** – `{number}` – HTTP status code of the response.
  8805. * - **headers** – `{function([headerName])}` – Header getter function.
  8806. * - **config** – `{Object}` – The configuration object that was used to generate the request.
  8807. * - **statusText** – `{string}` – HTTP status text of the response.
  8808. *
  8809. * A response status code between 200 and 299 is considered a success status and
  8810. * will result in the success callback being called. Note that if the response is a redirect,
  8811. * XMLHttpRequest will transparently follow it, meaning that the error callback will not be
  8812. * called for such responses.
  8813. *
  8814. *
  8815. * ## Shortcut methods
  8816. *
  8817. * Shortcut methods are also available. All shortcut methods require passing in the URL, and
  8818. * request data must be passed in for POST/PUT requests. An optional config can be passed as the
  8819. * last argument.
  8820. *
  8821. * ```js
  8822. * $http.get('/someUrl', config).then(successCallback, errorCallback);
  8823. * $http.post('/someUrl', data, config).then(successCallback, errorCallback);
  8824. * ```
  8825. *
  8826. * Complete list of shortcut methods:
  8827. *
  8828. * - {@link ng.$http#get $http.get}
  8829. * - {@link ng.$http#head $http.head}
  8830. * - {@link ng.$http#post $http.post}
  8831. * - {@link ng.$http#put $http.put}
  8832. * - {@link ng.$http#delete $http.delete}
  8833. * - {@link ng.$http#jsonp $http.jsonp}
  8834. * - {@link ng.$http#patch $http.patch}
  8835. *
  8836. *
  8837. * ## Writing Unit Tests that use $http
  8838. * When unit testing (using {@link ngMock ngMock}), it is necessary to call
  8839. * {@link ngMock.$httpBackend#flush $httpBackend.flush()} to flush each pending
  8840. * request using trained responses.
  8841. *
  8842. * ```
  8843. * $httpBackend.expectGET(...);
  8844. * $http.get(...);
  8845. * $httpBackend.flush();
  8846. * ```
  8847. *
  8848. * ## Deprecation Notice
  8849. * <div class="alert alert-danger">
  8850. * The `$http` legacy promise methods `success` and `error` have been deprecated.
  8851. * Use the standard `then` method instead.
  8852. * If {@link $httpProvider#useLegacyPromiseExtensions `$httpProvider.useLegacyPromiseExtensions`} is set to
  8853. * `false` then these methods will throw {@link $http:legacy `$http/legacy`} error.
  8854. * </div>
  8855. *
  8856. * ## Setting HTTP Headers
  8857. *
  8858. * The $http service will automatically add certain HTTP headers to all requests. These defaults
  8859. * can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
  8860. * object, which currently contains this default configuration:
  8861. *
  8862. * - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
  8863. * - `Accept: application/json, text/plain, * / *`
  8864. * - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
  8865. * - `Content-Type: application/json`
  8866. * - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
  8867. * - `Content-Type: application/json`
  8868. *
  8869. * To add or overwrite these defaults, simply add or remove a property from these configuration
  8870. * objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
  8871. * with the lowercased HTTP method name as the key, e.g.
  8872. * `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }`.
  8873. *
  8874. * The defaults can also be set at runtime via the `$http.defaults` object in the same
  8875. * fashion. For example:
  8876. *
  8877. * ```
  8878. * module.run(function($http) {
  8879. * $http.defaults.headers.common.Authorization = 'Basic YmVlcDpib29w'
  8880. * });
  8881. * ```
  8882. *
  8883. * In addition, you can supply a `headers` property in the config object passed when
  8884. * calling `$http(config)`, which overrides the defaults without changing them globally.
  8885. *
  8886. * To explicitly remove a header automatically added via $httpProvider.defaults.headers on a per request basis,
  8887. * Use the `headers` property, setting the desired header to `undefined`. For example:
  8888. *
  8889. * ```js
  8890. * var req = {
  8891. * method: 'POST',
  8892. * url: 'http://example.com',
  8893. * headers: {
  8894. * 'Content-Type': undefined
  8895. * },
  8896. * data: { test: 'test' }
  8897. * }
  8898. *
  8899. * $http(req).then(function(){...}, function(){...});
  8900. * ```
  8901. *
  8902. * ## Transforming Requests and Responses
  8903. *
  8904. * Both requests and responses can be transformed using transformation functions: `transformRequest`
  8905. * and `transformResponse`. These properties can be a single function that returns
  8906. * the transformed value (`function(data, headersGetter, status)`) or an array of such transformation functions,
  8907. * which allows you to `push` or `unshift` a new transformation function into the transformation chain.
  8908. *
  8909. * ### Default Transformations
  8910. *
  8911. * The `$httpProvider` provider and `$http` service expose `defaults.transformRequest` and
  8912. * `defaults.transformResponse` properties. If a request does not provide its own transformations
  8913. * then these will be applied.
  8914. *
  8915. * You can augment or replace the default transformations by modifying these properties by adding to or
  8916. * replacing the array.
  8917. *
  8918. * Angular provides the following default transformations:
  8919. *
  8920. * Request transformations (`$httpProvider.defaults.transformRequest` and `$http.defaults.transformRequest`):
  8921. *
  8922. * - If the `data` property of the request configuration object contains an object, serialize it
  8923. * into JSON format.
  8924. *
  8925. * Response transformations (`$httpProvider.defaults.transformResponse` and `$http.defaults.transformResponse`):
  8926. *
  8927. * - If XSRF prefix is detected, strip it (see Security Considerations section below).
  8928. * - If JSON response is detected, deserialize it using a JSON parser.
  8929. *
  8930. *
  8931. * ### Overriding the Default Transformations Per Request
  8932. *
  8933. * If you wish override the request/response transformations only for a single request then provide
  8934. * `transformRequest` and/or `transformResponse` properties on the configuration object passed
  8935. * into `$http`.
  8936. *
  8937. * Note that if you provide these properties on the config object the default transformations will be
  8938. * overwritten. If you wish to augment the default transformations then you must include them in your
  8939. * local transformation array.
  8940. *
  8941. * The following code demonstrates adding a new response transformation to be run after the default response
  8942. * transformations have been run.
  8943. *
  8944. * ```js
  8945. * function appendTransform(defaults, transform) {
  8946. *
  8947. * // We can't guarantee that the default transformation is an array
  8948. * defaults = angular.isArray(defaults) ? defaults : [defaults];
  8949. *
  8950. * // Append the new transformation to the defaults
  8951. * return defaults.concat(transform);
  8952. * }
  8953. *
  8954. * $http({
  8955. * url: '...',
  8956. * method: 'GET',
  8957. * transformResponse: appendTransform($http.defaults.transformResponse, function(value) {
  8958. * return doTransform(value);
  8959. * })
  8960. * });
  8961. * ```
  8962. *
  8963. *
  8964. * ## Caching
  8965. *
  8966. * To enable caching, set the request configuration `cache` property to `true` (to use default
  8967. * cache) or to a custom cache object (built with {@link ng.$cacheFactory `$cacheFactory`}).
  8968. * When the cache is enabled, `$http` stores the response from the server in the specified
  8969. * cache. The next time the same request is made, the response is served from the cache without
  8970. * sending a request to the server.
  8971. *
  8972. * Note that even if the response is served from cache, delivery of the data is asynchronous in
  8973. * the same way that real requests are.
  8974. *
  8975. * If there are multiple GET requests for the same URL that should be cached using the same
  8976. * cache, but the cache is not populated yet, only one request to the server will be made and
  8977. * the remaining requests will be fulfilled using the response from the first request.
  8978. *
  8979. * You can change the default cache to a new object (built with
  8980. * {@link ng.$cacheFactory `$cacheFactory`}) by updating the
  8981. * {@link ng.$http#defaults `$http.defaults.cache`} property. All requests who set
  8982. * their `cache` property to `true` will now use this cache object.
  8983. *
  8984. * If you set the default cache to `false` then only requests that specify their own custom
  8985. * cache object will be cached.
  8986. *
  8987. * ## Interceptors
  8988. *
  8989. * Before you start creating interceptors, be sure to understand the
  8990. * {@link ng.$q $q and deferred/promise APIs}.
  8991. *
  8992. * For purposes of global error handling, authentication, or any kind of synchronous or
  8993. * asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
  8994. * able to intercept requests before they are handed to the server and
  8995. * responses before they are handed over to the application code that
  8996. * initiated these requests. The interceptors leverage the {@link ng.$q
  8997. * promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
  8998. *
  8999. * The interceptors are service factories that are registered with the `$httpProvider` by
  9000. * adding them to the `$httpProvider.interceptors` array. The factory is called and
  9001. * injected with dependencies (if specified) and returns the interceptor.
  9002. *
  9003. * There are two kinds of interceptors (and two kinds of rejection interceptors):
  9004. *
  9005. * * `request`: interceptors get called with a http {@link $http#usage config} object. The function is free to
  9006. * modify the `config` object or create a new one. The function needs to return the `config`
  9007. * object directly, or a promise containing the `config` or a new `config` object.
  9008. * * `requestError`: interceptor gets called when a previous interceptor threw an error or
  9009. * resolved with a rejection.
  9010. * * `response`: interceptors get called with http `response` object. The function is free to
  9011. * modify the `response` object or create a new one. The function needs to return the `response`
  9012. * object directly, or as a promise containing the `response` or a new `response` object.
  9013. * * `responseError`: interceptor gets called when a previous interceptor threw an error or
  9014. * resolved with a rejection.
  9015. *
  9016. *
  9017. * ```js
  9018. * // register the interceptor as a service
  9019. * $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
  9020. * return {
  9021. * // optional method
  9022. * 'request': function(config) {
  9023. * // do something on success
  9024. * return config;
  9025. * },
  9026. *
  9027. * // optional method
  9028. * 'requestError': function(rejection) {
  9029. * // do something on error
  9030. * if (canRecover(rejection)) {
  9031. * return responseOrNewPromise
  9032. * }
  9033. * return $q.reject(rejection);
  9034. * },
  9035. *
  9036. *
  9037. *
  9038. * // optional method
  9039. * 'response': function(response) {
  9040. * // do something on success
  9041. * return response;
  9042. * },
  9043. *
  9044. * // optional method
  9045. * 'responseError': function(rejection) {
  9046. * // do something on error
  9047. * if (canRecover(rejection)) {
  9048. * return responseOrNewPromise
  9049. * }
  9050. * return $q.reject(rejection);
  9051. * }
  9052. * };
  9053. * });
  9054. *
  9055. * $httpProvider.interceptors.push('myHttpInterceptor');
  9056. *
  9057. *
  9058. * // alternatively, register the interceptor via an anonymous factory
  9059. * $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
  9060. * return {
  9061. * 'request': function(config) {
  9062. * // same as above
  9063. * },
  9064. *
  9065. * 'response': function(response) {
  9066. * // same as above
  9067. * }
  9068. * };
  9069. * });
  9070. * ```
  9071. *
  9072. * ## Security Considerations
  9073. *
  9074. * When designing web applications, consider security threats from:
  9075. *
  9076. * - [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9077. * - [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery)
  9078. *
  9079. * Both server and the client must cooperate in order to eliminate these threats. Angular comes
  9080. * pre-configured with strategies that address these issues, but for this to work backend server
  9081. * cooperation is required.
  9082. *
  9083. * ### JSON Vulnerability Protection
  9084. *
  9085. * A [JSON vulnerability](http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx)
  9086. * allows third party website to turn your JSON resource URL into
  9087. * [JSONP](http://en.wikipedia.org/wiki/JSONP) request under some conditions. To
  9088. * counter this your server can prefix all JSON requests with following string `")]}',\n"`.
  9089. * Angular will automatically strip the prefix before processing it as JSON.
  9090. *
  9091. * For example if your server needs to return:
  9092. * ```js
  9093. * ['one','two']
  9094. * ```
  9095. *
  9096. * which is vulnerable to attack, your server can return:
  9097. * ```js
  9098. * )]}',
  9099. * ['one','two']
  9100. * ```
  9101. *
  9102. * Angular will strip the prefix, before processing the JSON.
  9103. *
  9104. *
  9105. * ### Cross Site Request Forgery (XSRF) Protection
  9106. *
  9107. * [XSRF](http://en.wikipedia.org/wiki/Cross-site_request_forgery) is a technique by which
  9108. * an unauthorized site can gain your user's private data. Angular provides a mechanism
  9109. * to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
  9110. * (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
  9111. * JavaScript that runs on your domain could read the cookie, your server can be assured that
  9112. * the XHR came from JavaScript running on your domain. The header will not be set for
  9113. * cross-domain requests.
  9114. *
  9115. * To take advantage of this, your server needs to set a token in a JavaScript readable session
  9116. * cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
  9117. * server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
  9118. * that only JavaScript running on your domain could have sent the request. The token must be
  9119. * unique for each user and must be verifiable by the server (to prevent the JavaScript from
  9120. * making up its own tokens). We recommend that the token is a digest of your site's
  9121. * authentication cookie with a [salt](https://en.wikipedia.org/wiki/Salt_(cryptography&#41;)
  9122. * for added security.
  9123. *
  9124. * The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
  9125. * properties of either $httpProvider.defaults at config-time, $http.defaults at run-time,
  9126. * or the per-request config object.
  9127. *
  9128. * In order to prevent collisions in environments where multiple Angular apps share the
  9129. * same domain or subdomain, we recommend that each application uses unique cookie name.
  9130. *
  9131. * @param {object} config Object describing the request to be made and how it should be
  9132. * processed. The object has following properties:
  9133. *
  9134. * - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
  9135. * - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
  9136. * - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be serialized
  9137. * with the `paramSerializer` and appended as GET parameters.
  9138. * - **data** – `{string|Object}` – Data to be sent as the request message data.
  9139. * - **headers** – `{Object}` – Map of strings or functions which return strings representing
  9140. * HTTP headers to send to the server. If the return value of a function is null, the
  9141. * header will not be sent. Functions accept a config object as an argument.
  9142. * - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
  9143. * - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
  9144. * - **transformRequest** –
  9145. * `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
  9146. * transform function or an array of such functions. The transform function takes the http
  9147. * request body and headers and returns its transformed (typically serialized) version.
  9148. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9149. * Overriding the Default Transformations}
  9150. * - **transformResponse** –
  9151. * `{function(data, headersGetter, status)|Array.<function(data, headersGetter, status)>}` –
  9152. * transform function or an array of such functions. The transform function takes the http
  9153. * response body, headers and status and returns its transformed (typically deserialized) version.
  9154. * See {@link ng.$http#overriding-the-default-transformations-per-request
  9155. * Overriding the Default TransformationjqLiks}
  9156. * - **paramSerializer** - `{string|function(Object<string,string>):string}` - A function used to
  9157. * prepare the string representation of request parameters (specified as an object).
  9158. * If specified as string, it is interpreted as function registered with the
  9159. * {@link $injector $injector}, which means you can create your own serializer
  9160. * by registering it as a {@link auto.$provide#service service}.
  9161. * The default serializer is the {@link $httpParamSerializer $httpParamSerializer};
  9162. * alternatively, you can use the {@link $httpParamSerializerJQLike $httpParamSerializerJQLike}
  9163. * - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
  9164. * GET request, otherwise if a cache instance built with
  9165. * {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
  9166. * caching.
  9167. * - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
  9168. * that should abort the request when resolved.
  9169. * - **withCredentials** - `{boolean}` - whether to set the `withCredentials` flag on the
  9170. * XHR object. See [requests with credentials](https://developer.mozilla.org/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials)
  9171. * for more information.
  9172. * - **responseType** - `{string}` - see
  9173. * [XMLHttpRequest.responseType](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#xmlhttprequest-responsetype).
  9174. *
  9175. * @returns {HttpPromise} Returns a {@link ng.$q `Promise}` that will be resolved to a response object
  9176. * when the request succeeds or fails.
  9177. *
  9178. *
  9179. * @property {Array.<Object>} pendingRequests Array of config objects for currently pending
  9180. * requests. This is primarily meant to be used for debugging purposes.
  9181. *
  9182. *
  9183. * @example
  9184. <example module="httpExample">
  9185. <file name="index.html">
  9186. <div ng-controller="FetchController">
  9187. <select ng-model="method" aria-label="Request method">
  9188. <option>GET</option>
  9189. <option>JSONP</option>
  9190. </select>
  9191. <input type="text" ng-model="url" size="80" aria-label="URL" />
  9192. <button id="fetchbtn" ng-click="fetch()">fetch</button><br>
  9193. <button id="samplegetbtn" ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
  9194. <button id="samplejsonpbtn"
  9195. ng-click="updateModel('JSONP',
  9196. 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
  9197. Sample JSONP
  9198. </button>
  9199. <button id="invalidjsonpbtn"
  9200. ng-click="updateModel('JSONP', 'https://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
  9201. Invalid JSONP
  9202. </button>
  9203. <pre>http status code: {{status}}</pre>
  9204. <pre>http response data: {{data}}</pre>
  9205. </div>
  9206. </file>
  9207. <file name="script.js">
  9208. angular.module('httpExample', [])
  9209. .controller('FetchController', ['$scope', '$http', '$templateCache',
  9210. function($scope, $http, $templateCache) {
  9211. $scope.method = 'GET';
  9212. $scope.url = 'http-hello.html';
  9213. $scope.fetch = function() {
  9214. $scope.code = null;
  9215. $scope.response = null;
  9216. $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
  9217. then(function(response) {
  9218. $scope.status = response.status;
  9219. $scope.data = response.data;
  9220. }, function(response) {
  9221. $scope.data = response.data || "Request failed";
  9222. $scope.status = response.status;
  9223. });
  9224. };
  9225. $scope.updateModel = function(method, url) {
  9226. $scope.method = method;
  9227. $scope.url = url;
  9228. };
  9229. }]);
  9230. </file>
  9231. <file name="http-hello.html">
  9232. Hello, $http!
  9233. </file>
  9234. <file name="protractor.js" type="protractor">
  9235. var status = element(by.binding('status'));
  9236. var data = element(by.binding('data'));
  9237. var fetchBtn = element(by.id('fetchbtn'));
  9238. var sampleGetBtn = element(by.id('samplegetbtn'));
  9239. var sampleJsonpBtn = element(by.id('samplejsonpbtn'));
  9240. var invalidJsonpBtn = element(by.id('invalidjsonpbtn'));
  9241. it('should make an xhr GET request', function() {
  9242. sampleGetBtn.click();
  9243. fetchBtn.click();
  9244. expect(status.getText()).toMatch('200');
  9245. expect(data.getText()).toMatch(/Hello, \$http!/);
  9246. });
  9247. // Commented out due to flakes. See https://github.com/angular/angular.js/issues/9185
  9248. // it('should make a JSONP request to angularjs.org', function() {
  9249. // sampleJsonpBtn.click();
  9250. // fetchBtn.click();
  9251. // expect(status.getText()).toMatch('200');
  9252. // expect(data.getText()).toMatch(/Super Hero!/);
  9253. // });
  9254. it('should make JSONP request to invalid URL and invoke the error handler',
  9255. function() {
  9256. invalidJsonpBtn.click();
  9257. fetchBtn.click();
  9258. expect(status.getText()).toMatch('0');
  9259. expect(data.getText()).toMatch('Request failed');
  9260. });
  9261. </file>
  9262. </example>
  9263. */
  9264. function $http(requestConfig) {
  9265. if (!angular.isObject(requestConfig)) {
  9266. throw minErr('$http')('badreq', 'Http request configuration must be an object. Received: {0}', requestConfig);
  9267. }
  9268. var config = extend({
  9269. method: 'get',
  9270. transformRequest: defaults.transformRequest,
  9271. transformResponse: defaults.transformResponse,
  9272. paramSerializer: defaults.paramSerializer
  9273. }, requestConfig);
  9274. config.headers = mergeHeaders(requestConfig);
  9275. config.method = uppercase(config.method);
  9276. config.paramSerializer = isString(config.paramSerializer) ?
  9277. $injector.get(config.paramSerializer) : config.paramSerializer;
  9278. var serverRequest = function(config) {
  9279. var headers = config.headers;
  9280. var reqData = transformData(config.data, headersGetter(headers), undefined, config.transformRequest);
  9281. // strip content-type if data is undefined
  9282. if (isUndefined(reqData)) {
  9283. forEach(headers, function(value, header) {
  9284. if (lowercase(header) === 'content-type') {
  9285. delete headers[header];
  9286. }
  9287. });
  9288. }
  9289. if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
  9290. config.withCredentials = defaults.withCredentials;
  9291. }
  9292. // send request
  9293. return sendReq(config, reqData).then(transformResponse, transformResponse);
  9294. };
  9295. var chain = [serverRequest, undefined];
  9296. var promise = $q.when(config);
  9297. // apply interceptors
  9298. forEach(reversedInterceptors, function(interceptor) {
  9299. if (interceptor.request || interceptor.requestError) {
  9300. chain.unshift(interceptor.request, interceptor.requestError);
  9301. }
  9302. if (interceptor.response || interceptor.responseError) {
  9303. chain.push(interceptor.response, interceptor.responseError);
  9304. }
  9305. });
  9306. while (chain.length) {
  9307. var thenFn = chain.shift();
  9308. var rejectFn = chain.shift();
  9309. promise = promise.then(thenFn, rejectFn);
  9310. }
  9311. if (useLegacyPromise) {
  9312. promise.success = function(fn) {
  9313. assertArgFn(fn, 'fn');
  9314. promise.then(function(response) {
  9315. fn(response.data, response.status, response.headers, config);
  9316. });
  9317. return promise;
  9318. };
  9319. promise.error = function(fn) {
  9320. assertArgFn(fn, 'fn');
  9321. promise.then(null, function(response) {
  9322. fn(response.data, response.status, response.headers, config);
  9323. });
  9324. return promise;
  9325. };
  9326. } else {
  9327. promise.success = $httpMinErrLegacyFn('success');
  9328. promise.error = $httpMinErrLegacyFn('error');
  9329. }
  9330. return promise;
  9331. function transformResponse(response) {
  9332. // make a copy since the response must be cacheable
  9333. var resp = extend({}, response);
  9334. resp.data = transformData(response.data, response.headers, response.status,
  9335. config.transformResponse);
  9336. return (isSuccess(response.status))
  9337. ? resp
  9338. : $q.reject(resp);
  9339. }
  9340. function executeHeaderFns(headers, config) {
  9341. var headerContent, processedHeaders = {};
  9342. forEach(headers, function(headerFn, header) {
  9343. if (isFunction(headerFn)) {
  9344. headerContent = headerFn(config);
  9345. if (headerContent != null) {
  9346. processedHeaders[header] = headerContent;
  9347. }
  9348. } else {
  9349. processedHeaders[header] = headerFn;
  9350. }
  9351. });
  9352. return processedHeaders;
  9353. }
  9354. function mergeHeaders(config) {
  9355. var defHeaders = defaults.headers,
  9356. reqHeaders = extend({}, config.headers),
  9357. defHeaderName, lowercaseDefHeaderName, reqHeaderName;
  9358. defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
  9359. // using for-in instead of forEach to avoid unecessary iteration after header has been found
  9360. defaultHeadersIteration:
  9361. for (defHeaderName in defHeaders) {
  9362. lowercaseDefHeaderName = lowercase(defHeaderName);
  9363. for (reqHeaderName in reqHeaders) {
  9364. if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
  9365. continue defaultHeadersIteration;
  9366. }
  9367. }
  9368. reqHeaders[defHeaderName] = defHeaders[defHeaderName];
  9369. }
  9370. // execute if header value is a function for merged headers
  9371. return executeHeaderFns(reqHeaders, shallowCopy(config));
  9372. }
  9373. }
  9374. $http.pendingRequests = [];
  9375. /**
  9376. * @ngdoc method
  9377. * @name $http#get
  9378. *
  9379. * @description
  9380. * Shortcut method to perform `GET` request.
  9381. *
  9382. * @param {string} url Relative or absolute URL specifying the destination of the request
  9383. * @param {Object=} config Optional configuration object
  9384. * @returns {HttpPromise} Future object
  9385. */
  9386. /**
  9387. * @ngdoc method
  9388. * @name $http#delete
  9389. *
  9390. * @description
  9391. * Shortcut method to perform `DELETE` request.
  9392. *
  9393. * @param {string} url Relative or absolute URL specifying the destination of the request
  9394. * @param {Object=} config Optional configuration object
  9395. * @returns {HttpPromise} Future object
  9396. */
  9397. /**
  9398. * @ngdoc method
  9399. * @name $http#head
  9400. *
  9401. * @description
  9402. * Shortcut method to perform `HEAD` request.
  9403. *
  9404. * @param {string} url Relative or absolute URL specifying the destination of the request
  9405. * @param {Object=} config Optional configuration object
  9406. * @returns {HttpPromise} Future object
  9407. */
  9408. /**
  9409. * @ngdoc method
  9410. * @name $http#jsonp
  9411. *
  9412. * @description
  9413. * Shortcut method to perform `JSONP` request.
  9414. *
  9415. * @param {string} url Relative or absolute URL specifying the destination of the request.
  9416. * The name of the callback should be the string `JSON_CALLBACK`.
  9417. * @param {Object=} config Optional configuration object
  9418. * @returns {HttpPromise} Future object
  9419. */
  9420. createShortMethods('get', 'delete', 'head', 'jsonp');
  9421. /**
  9422. * @ngdoc method
  9423. * @name $http#post
  9424. *
  9425. * @description
  9426. * Shortcut method to perform `POST` request.
  9427. *
  9428. * @param {string} url Relative or absolute URL specifying the destination of the request
  9429. * @param {*} data Request content
  9430. * @param {Object=} config Optional configuration object
  9431. * @returns {HttpPromise} Future object
  9432. */
  9433. /**
  9434. * @ngdoc method
  9435. * @name $http#put
  9436. *
  9437. * @description
  9438. * Shortcut method to perform `PUT` request.
  9439. *
  9440. * @param {string} url Relative or absolute URL specifying the destination of the request
  9441. * @param {*} data Request content
  9442. * @param {Object=} config Optional configuration object
  9443. * @returns {HttpPromise} Future object
  9444. */
  9445. /**
  9446. * @ngdoc method
  9447. * @name $http#patch
  9448. *
  9449. * @description
  9450. * Shortcut method to perform `PATCH` request.
  9451. *
  9452. * @param {string} url Relative or absolute URL specifying the destination of the request
  9453. * @param {*} data Request content
  9454. * @param {Object=} config Optional configuration object
  9455. * @returns {HttpPromise} Future object
  9456. */
  9457. createShortMethodsWithData('post', 'put', 'patch');
  9458. /**
  9459. * @ngdoc property
  9460. * @name $http#defaults
  9461. *
  9462. * @description
  9463. * Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
  9464. * default headers, withCredentials as well as request and response transformations.
  9465. *
  9466. * See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
  9467. */
  9468. $http.defaults = defaults;
  9469. return $http;
  9470. function createShortMethods(names) {
  9471. forEach(arguments, function(name) {
  9472. $http[name] = function(url, config) {
  9473. return $http(extend({}, config || {}, {
  9474. method: name,
  9475. url: url
  9476. }));
  9477. };
  9478. });
  9479. }
  9480. function createShortMethodsWithData(name) {
  9481. forEach(arguments, function(name) {
  9482. $http[name] = function(url, data, config) {
  9483. return $http(extend({}, config || {}, {
  9484. method: name,
  9485. url: url,
  9486. data: data
  9487. }));
  9488. };
  9489. });
  9490. }
  9491. /**
  9492. * Makes the request.
  9493. *
  9494. * !!! ACCESSES CLOSURE VARS:
  9495. * $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
  9496. */
  9497. function sendReq(config, reqData) {
  9498. var deferred = $q.defer(),
  9499. promise = deferred.promise,
  9500. cache,
  9501. cachedResp,
  9502. reqHeaders = config.headers,
  9503. url = buildUrl(config.url, config.paramSerializer(config.params));
  9504. $http.pendingRequests.push(config);
  9505. promise.then(removePendingReq, removePendingReq);
  9506. if ((config.cache || defaults.cache) && config.cache !== false &&
  9507. (config.method === 'GET' || config.method === 'JSONP')) {
  9508. cache = isObject(config.cache) ? config.cache
  9509. : isObject(defaults.cache) ? defaults.cache
  9510. : defaultCache;
  9511. }
  9512. if (cache) {
  9513. cachedResp = cache.get(url);
  9514. if (isDefined(cachedResp)) {
  9515. if (isPromiseLike(cachedResp)) {
  9516. // cached request has already been sent, but there is no response yet
  9517. cachedResp.then(resolvePromiseWithResult, resolvePromiseWithResult);
  9518. } else {
  9519. // serving from cache
  9520. if (isArray(cachedResp)) {
  9521. resolvePromise(cachedResp[1], cachedResp[0], shallowCopy(cachedResp[2]), cachedResp[3]);
  9522. } else {
  9523. resolvePromise(cachedResp, 200, {}, 'OK');
  9524. }
  9525. }
  9526. } else {
  9527. // put the promise for the non-transformed response into cache as a placeholder
  9528. cache.put(url, promise);
  9529. }
  9530. }
  9531. // if we won't have the response in cache, set the xsrf headers and
  9532. // send the request to the backend
  9533. if (isUndefined(cachedResp)) {
  9534. var xsrfValue = urlIsSameOrigin(config.url)
  9535. ? $$cookieReader()[config.xsrfCookieName || defaults.xsrfCookieName]
  9536. : undefined;
  9537. if (xsrfValue) {
  9538. reqHeaders[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
  9539. }
  9540. $httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
  9541. config.withCredentials, config.responseType);
  9542. }
  9543. return promise;
  9544. /**
  9545. * Callback registered to $httpBackend():
  9546. * - caches the response if desired
  9547. * - resolves the raw $http promise
  9548. * - calls $apply
  9549. */
  9550. function done(status, response, headersString, statusText) {
  9551. if (cache) {
  9552. if (isSuccess(status)) {
  9553. cache.put(url, [status, response, parseHeaders(headersString), statusText]);
  9554. } else {
  9555. // remove promise from the cache
  9556. cache.remove(url);
  9557. }
  9558. }
  9559. function resolveHttpPromise() {
  9560. resolvePromise(response, status, headersString, statusText);
  9561. }
  9562. if (useApplyAsync) {
  9563. $rootScope.$applyAsync(resolveHttpPromise);
  9564. } else {
  9565. resolveHttpPromise();
  9566. if (!$rootScope.$$phase) $rootScope.$apply();
  9567. }
  9568. }
  9569. /**
  9570. * Resolves the raw $http promise.
  9571. */
  9572. function resolvePromise(response, status, headers, statusText) {
  9573. //status: HTTP response status code, 0, -1 (aborted by timeout / promise)
  9574. status = status >= -1 ? status : 0;
  9575. (isSuccess(status) ? deferred.resolve : deferred.reject)({
  9576. data: response,
  9577. status: status,
  9578. headers: headersGetter(headers),
  9579. config: config,
  9580. statusText: statusText
  9581. });
  9582. }
  9583. function resolvePromiseWithResult(result) {
  9584. resolvePromise(result.data, result.status, shallowCopy(result.headers()), result.statusText);
  9585. }
  9586. function removePendingReq() {
  9587. var idx = $http.pendingRequests.indexOf(config);
  9588. if (idx !== -1) $http.pendingRequests.splice(idx, 1);
  9589. }
  9590. }
  9591. function buildUrl(url, serializedParams) {
  9592. if (serializedParams.length > 0) {
  9593. url += ((url.indexOf('?') == -1) ? '?' : '&') + serializedParams;
  9594. }
  9595. return url;
  9596. }
  9597. }];
  9598. }
  9599. /**
  9600. * @ngdoc service
  9601. * @name $xhrFactory
  9602. *
  9603. * @description
  9604. * Factory function used to create XMLHttpRequest objects.
  9605. *
  9606. * Replace or decorate this service to create your own custom XMLHttpRequest objects.
  9607. *
  9608. * ```
  9609. * angular.module('myApp', [])
  9610. * .factory('$xhrFactory', function() {
  9611. * return function createXhr(method, url) {
  9612. * return new window.XMLHttpRequest({mozSystem: true});
  9613. * };
  9614. * });
  9615. * ```
  9616. *
  9617. * @param {string} method HTTP method of the request (GET, POST, PUT, ..)
  9618. * @param {string} url URL of the request.
  9619. */
  9620. function $xhrFactoryProvider() {
  9621. this.$get = function() {
  9622. return function createXhr() {
  9623. return new window.XMLHttpRequest();
  9624. };
  9625. };
  9626. }
  9627. /**
  9628. * @ngdoc service
  9629. * @name $httpBackend
  9630. * @requires $window
  9631. * @requires $document
  9632. * @requires $xhrFactory
  9633. *
  9634. * @description
  9635. * HTTP backend used by the {@link ng.$http service} that delegates to
  9636. * XMLHttpRequest object or JSONP and deals with browser incompatibilities.
  9637. *
  9638. * You should never need to use this service directly, instead use the higher-level abstractions:
  9639. * {@link ng.$http $http} or {@link ngResource.$resource $resource}.
  9640. *
  9641. * During testing this implementation is swapped with {@link ngMock.$httpBackend mock
  9642. * $httpBackend} which can be trained with responses.
  9643. */
  9644. function $HttpBackendProvider() {
  9645. this.$get = ['$browser', '$window', '$document', '$xhrFactory', function($browser, $window, $document, $xhrFactory) {
  9646. return createHttpBackend($browser, $xhrFactory, $browser.defer, $window.angular.callbacks, $document[0]);
  9647. }];
  9648. }
  9649. function createHttpBackend($browser, createXhr, $browserDefer, callbacks, rawDocument) {
  9650. // TODO(vojta): fix the signature
  9651. return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
  9652. $browser.$$incOutstandingRequestCount();
  9653. url = url || $browser.url();
  9654. if (lowercase(method) == 'jsonp') {
  9655. var callbackId = '_' + (callbacks.counter++).toString(36);
  9656. callbacks[callbackId] = function(data) {
  9657. callbacks[callbackId].data = data;
  9658. callbacks[callbackId].called = true;
  9659. };
  9660. var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
  9661. callbackId, function(status, text) {
  9662. completeRequest(callback, status, callbacks[callbackId].data, "", text);
  9663. callbacks[callbackId] = noop;
  9664. });
  9665. } else {
  9666. var xhr = createXhr(method, url);
  9667. xhr.open(method, url, true);
  9668. forEach(headers, function(value, key) {
  9669. if (isDefined(value)) {
  9670. xhr.setRequestHeader(key, value);
  9671. }
  9672. });
  9673. xhr.onload = function requestLoaded() {
  9674. var statusText = xhr.statusText || '';
  9675. // responseText is the old-school way of retrieving response (supported by IE9)
  9676. // response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
  9677. var response = ('response' in xhr) ? xhr.response : xhr.responseText;
  9678. // normalize IE9 bug (http://bugs.jquery.com/ticket/1450)
  9679. var status = xhr.status === 1223 ? 204 : xhr.status;
  9680. // fix status code when it is 0 (0 status is undocumented).
  9681. // Occurs when accessing file resources or on Android 4.1 stock browser
  9682. // while retrieving files from application cache.
  9683. if (status === 0) {
  9684. status = response ? 200 : urlResolve(url).protocol == 'file' ? 404 : 0;
  9685. }
  9686. completeRequest(callback,
  9687. status,
  9688. response,
  9689. xhr.getAllResponseHeaders(),
  9690. statusText);
  9691. };
  9692. var requestError = function() {
  9693. // The response is always empty
  9694. // See https://xhr.spec.whatwg.org/#request-error-steps and https://fetch.spec.whatwg.org/#concept-network-error
  9695. completeRequest(callback, -1, null, null, '');
  9696. };
  9697. xhr.onerror = requestError;
  9698. xhr.onabort = requestError;
  9699. if (withCredentials) {
  9700. xhr.withCredentials = true;
  9701. }
  9702. if (responseType) {
  9703. try {
  9704. xhr.responseType = responseType;
  9705. } catch (e) {
  9706. // WebKit added support for the json responseType value on 09/03/2013
  9707. // https://bugs.webkit.org/show_bug.cgi?id=73648. Versions of Safari prior to 7 are
  9708. // known to throw when setting the value "json" as the response type. Other older
  9709. // browsers implementing the responseType
  9710. //
  9711. // The json response type can be ignored if not supported, because JSON payloads are
  9712. // parsed on the client-side regardless.
  9713. if (responseType !== 'json') {
  9714. throw e;
  9715. }
  9716. }
  9717. }
  9718. xhr.send(isUndefined(post) ? null : post);
  9719. }
  9720. if (timeout > 0) {
  9721. var timeoutId = $browserDefer(timeoutRequest, timeout);
  9722. } else if (isPromiseLike(timeout)) {
  9723. timeout.then(timeoutRequest);
  9724. }
  9725. function timeoutRequest() {
  9726. jsonpDone && jsonpDone();
  9727. xhr && xhr.abort();
  9728. }
  9729. function completeRequest(callback, status, response, headersString, statusText) {
  9730. // cancel timeout and subsequent timeout promise resolution
  9731. if (isDefined(timeoutId)) {
  9732. $browserDefer.cancel(timeoutId);
  9733. }
  9734. jsonpDone = xhr = null;
  9735. callback(status, response, headersString, statusText);
  9736. $browser.$$completeOutstandingRequest(noop);
  9737. }
  9738. };
  9739. function jsonpReq(url, callbackId, done) {
  9740. // we can't use jQuery/jqLite here because jQuery does crazy stuff with script elements, e.g.:
  9741. // - fetches local scripts via XHR and evals them
  9742. // - adds and immediately removes script elements from the document
  9743. var script = rawDocument.createElement('script'), callback = null;
  9744. script.type = "text/javascript";
  9745. script.src = url;
  9746. script.async = true;
  9747. callback = function(event) {
  9748. removeEventListenerFn(script, "load", callback);
  9749. removeEventListenerFn(script, "error", callback);
  9750. rawDocument.body.removeChild(script);
  9751. script = null;
  9752. var status = -1;
  9753. var text = "unknown";
  9754. if (event) {
  9755. if (event.type === "load" && !callbacks[callbackId].called) {
  9756. event = { type: "error" };
  9757. }
  9758. text = event.type;
  9759. status = event.type === "error" ? 404 : 200;
  9760. }
  9761. if (done) {
  9762. done(status, text);
  9763. }
  9764. };
  9765. addEventListenerFn(script, "load", callback);
  9766. addEventListenerFn(script, "error", callback);
  9767. rawDocument.body.appendChild(script);
  9768. return callback;
  9769. }
  9770. }
  9771. var $interpolateMinErr = angular.$interpolateMinErr = minErr('$interpolate');
  9772. $interpolateMinErr.throwNoconcat = function(text) {
  9773. throw $interpolateMinErr('noconcat',
  9774. "Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
  9775. "interpolations that concatenate multiple expressions when a trusted value is " +
  9776. "required. See http://docs.angularjs.org/api/ng.$sce", text);
  9777. };
  9778. $interpolateMinErr.interr = function(text, err) {
  9779. return $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text, err.toString());
  9780. };
  9781. /**
  9782. * @ngdoc provider
  9783. * @name $interpolateProvider
  9784. *
  9785. * @description
  9786. *
  9787. * Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
  9788. *
  9789. * @example
  9790. <example module="customInterpolationApp">
  9791. <file name="index.html">
  9792. <script>
  9793. var customInterpolationApp = angular.module('customInterpolationApp', []);
  9794. customInterpolationApp.config(function($interpolateProvider) {
  9795. $interpolateProvider.startSymbol('//');
  9796. $interpolateProvider.endSymbol('//');
  9797. });
  9798. customInterpolationApp.controller('DemoController', function() {
  9799. this.label = "This binding is brought you by // interpolation symbols.";
  9800. });
  9801. </script>
  9802. <div ng-app="App" ng-controller="DemoController as demo">
  9803. //demo.label//
  9804. </div>
  9805. </file>
  9806. <file name="protractor.js" type="protractor">
  9807. it('should interpolate binding with custom symbols', function() {
  9808. expect(element(by.binding('demo.label')).getText()).toBe('This binding is brought you by // interpolation symbols.');
  9809. });
  9810. </file>
  9811. </example>
  9812. */
  9813. function $InterpolateProvider() {
  9814. var startSymbol = '{{';
  9815. var endSymbol = '}}';
  9816. /**
  9817. * @ngdoc method
  9818. * @name $interpolateProvider#startSymbol
  9819. * @description
  9820. * Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
  9821. *
  9822. * @param {string=} value new value to set the starting symbol to.
  9823. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9824. */
  9825. this.startSymbol = function(value) {
  9826. if (value) {
  9827. startSymbol = value;
  9828. return this;
  9829. } else {
  9830. return startSymbol;
  9831. }
  9832. };
  9833. /**
  9834. * @ngdoc method
  9835. * @name $interpolateProvider#endSymbol
  9836. * @description
  9837. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  9838. *
  9839. * @param {string=} value new value to set the ending symbol to.
  9840. * @returns {string|self} Returns the symbol when used as getter and self if used as setter.
  9841. */
  9842. this.endSymbol = function(value) {
  9843. if (value) {
  9844. endSymbol = value;
  9845. return this;
  9846. } else {
  9847. return endSymbol;
  9848. }
  9849. };
  9850. this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
  9851. var startSymbolLength = startSymbol.length,
  9852. endSymbolLength = endSymbol.length,
  9853. escapedStartRegexp = new RegExp(startSymbol.replace(/./g, escape), 'g'),
  9854. escapedEndRegexp = new RegExp(endSymbol.replace(/./g, escape), 'g');
  9855. function escape(ch) {
  9856. return '\\\\\\' + ch;
  9857. }
  9858. function unescapeText(text) {
  9859. return text.replace(escapedStartRegexp, startSymbol).
  9860. replace(escapedEndRegexp, endSymbol);
  9861. }
  9862. function stringify(value) {
  9863. if (value == null) { // null || undefined
  9864. return '';
  9865. }
  9866. switch (typeof value) {
  9867. case 'string':
  9868. break;
  9869. case 'number':
  9870. value = '' + value;
  9871. break;
  9872. default:
  9873. value = toJson(value);
  9874. }
  9875. return value;
  9876. }
  9877. /**
  9878. * @ngdoc service
  9879. * @name $interpolate
  9880. * @kind function
  9881. *
  9882. * @requires $parse
  9883. * @requires $sce
  9884. *
  9885. * @description
  9886. *
  9887. * Compiles a string with markup into an interpolation function. This service is used by the
  9888. * HTML {@link ng.$compile $compile} service for data binding. See
  9889. * {@link ng.$interpolateProvider $interpolateProvider} for configuring the
  9890. * interpolation markup.
  9891. *
  9892. *
  9893. * ```js
  9894. * var $interpolate = ...; // injected
  9895. * var exp = $interpolate('Hello {{name | uppercase}}!');
  9896. * expect(exp({name:'Angular'})).toEqual('Hello ANGULAR!');
  9897. * ```
  9898. *
  9899. * `$interpolate` takes an optional fourth argument, `allOrNothing`. If `allOrNothing` is
  9900. * `true`, the interpolation function will return `undefined` unless all embedded expressions
  9901. * evaluate to a value other than `undefined`.
  9902. *
  9903. * ```js
  9904. * var $interpolate = ...; // injected
  9905. * var context = {greeting: 'Hello', name: undefined };
  9906. *
  9907. * // default "forgiving" mode
  9908. * var exp = $interpolate('{{greeting}} {{name}}!');
  9909. * expect(exp(context)).toEqual('Hello !');
  9910. *
  9911. * // "allOrNothing" mode
  9912. * exp = $interpolate('{{greeting}} {{name}}!', false, null, true);
  9913. * expect(exp(context)).toBeUndefined();
  9914. * context.name = 'Angular';
  9915. * expect(exp(context)).toEqual('Hello Angular!');
  9916. * ```
  9917. *
  9918. * `allOrNothing` is useful for interpolating URLs. `ngSrc` and `ngSrcset` use this behavior.
  9919. *
  9920. * ####Escaped Interpolation
  9921. * $interpolate provides a mechanism for escaping interpolation markers. Start and end markers
  9922. * can be escaped by preceding each of their characters with a REVERSE SOLIDUS U+005C (backslash).
  9923. * It will be rendered as a regular start/end marker, and will not be interpreted as an expression
  9924. * or binding.
  9925. *
  9926. * This enables web-servers to prevent script injection attacks and defacing attacks, to some
  9927. * degree, while also enabling code examples to work without relying on the
  9928. * {@link ng.directive:ngNonBindable ngNonBindable} directive.
  9929. *
  9930. * **For security purposes, it is strongly encouraged that web servers escape user-supplied data,
  9931. * replacing angle brackets (&lt;, &gt;) with &amp;lt; and &amp;gt; respectively, and replacing all
  9932. * interpolation start/end markers with their escaped counterparts.**
  9933. *
  9934. * Escaped interpolation markers are only replaced with the actual interpolation markers in rendered
  9935. * output when the $interpolate service processes the text. So, for HTML elements interpolated
  9936. * by {@link ng.$compile $compile}, or otherwise interpolated with the `mustHaveExpression` parameter
  9937. * set to `true`, the interpolated text must contain an unescaped interpolation expression. As such,
  9938. * this is typically useful only when user-data is used in rendering a template from the server, or
  9939. * when otherwise untrusted data is used by a directive.
  9940. *
  9941. * <example>
  9942. * <file name="index.html">
  9943. * <div ng-init="username='A user'">
  9944. * <p ng-init="apptitle='Escaping demo'">{{apptitle}}: \{\{ username = "defaced value"; \}\}
  9945. * </p>
  9946. * <p><strong>{{username}}</strong> attempts to inject code which will deface the
  9947. * application, but fails to accomplish their task, because the server has correctly
  9948. * escaped the interpolation start/end markers with REVERSE SOLIDUS U+005C (backslash)
  9949. * characters.</p>
  9950. * <p>Instead, the result of the attempted script injection is visible, and can be removed
  9951. * from the database by an administrator.</p>
  9952. * </div>
  9953. * </file>
  9954. * </example>
  9955. *
  9956. * @param {string} text The text with markup to interpolate.
  9957. * @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
  9958. * embedded expression in order to return an interpolation function. Strings with no
  9959. * embedded expression will return null for the interpolation function.
  9960. * @param {string=} trustedContext when provided, the returned function passes the interpolated
  9961. * result through {@link ng.$sce#getTrusted $sce.getTrusted(interpolatedResult,
  9962. * trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
  9963. * provides Strict Contextual Escaping for details.
  9964. * @param {boolean=} allOrNothing if `true`, then the returned function returns undefined
  9965. * unless all embedded expressions evaluate to a value other than `undefined`.
  9966. * @returns {function(context)} an interpolation function which is used to compute the
  9967. * interpolated string. The function has these parameters:
  9968. *
  9969. * - `context`: evaluation context for all expressions embedded in the interpolated text
  9970. */
  9971. function $interpolate(text, mustHaveExpression, trustedContext, allOrNothing) {
  9972. allOrNothing = !!allOrNothing;
  9973. var startIndex,
  9974. endIndex,
  9975. index = 0,
  9976. expressions = [],
  9977. parseFns = [],
  9978. textLength = text.length,
  9979. exp,
  9980. concat = [],
  9981. expressionPositions = [];
  9982. while (index < textLength) {
  9983. if (((startIndex = text.indexOf(startSymbol, index)) != -1) &&
  9984. ((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1)) {
  9985. if (index !== startIndex) {
  9986. concat.push(unescapeText(text.substring(index, startIndex)));
  9987. }
  9988. exp = text.substring(startIndex + startSymbolLength, endIndex);
  9989. expressions.push(exp);
  9990. parseFns.push($parse(exp, parseStringifyInterceptor));
  9991. index = endIndex + endSymbolLength;
  9992. expressionPositions.push(concat.length);
  9993. concat.push('');
  9994. } else {
  9995. // we did not find an interpolation, so we have to add the remainder to the separators array
  9996. if (index !== textLength) {
  9997. concat.push(unescapeText(text.substring(index)));
  9998. }
  9999. break;
  10000. }
  10001. }
  10002. // Concatenating expressions makes it hard to reason about whether some combination of
  10003. // concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
  10004. // single expression be used for iframe[src], object[src], etc., we ensure that the value
  10005. // that's used is assigned or constructed by some JS code somewhere that is more testable or
  10006. // make it obvious that you bound the value to some user controlled value. This helps reduce
  10007. // the load when auditing for XSS issues.
  10008. if (trustedContext && concat.length > 1) {
  10009. $interpolateMinErr.throwNoconcat(text);
  10010. }
  10011. if (!mustHaveExpression || expressions.length) {
  10012. var compute = function(values) {
  10013. for (var i = 0, ii = expressions.length; i < ii; i++) {
  10014. if (allOrNothing && isUndefined(values[i])) return;
  10015. concat[expressionPositions[i]] = values[i];
  10016. }
  10017. return concat.join('');
  10018. };
  10019. var getValue = function(value) {
  10020. return trustedContext ?
  10021. $sce.getTrusted(trustedContext, value) :
  10022. $sce.valueOf(value);
  10023. };
  10024. return extend(function interpolationFn(context) {
  10025. var i = 0;
  10026. var ii = expressions.length;
  10027. var values = new Array(ii);
  10028. try {
  10029. for (; i < ii; i++) {
  10030. values[i] = parseFns[i](context);
  10031. }
  10032. return compute(values);
  10033. } catch (err) {
  10034. $exceptionHandler($interpolateMinErr.interr(text, err));
  10035. }
  10036. }, {
  10037. // all of these properties are undocumented for now
  10038. exp: text, //just for compatibility with regular watchers created via $watch
  10039. expressions: expressions,
  10040. $$watchDelegate: function(scope, listener) {
  10041. var lastValue;
  10042. return scope.$watchGroup(parseFns, function interpolateFnWatcher(values, oldValues) {
  10043. var currValue = compute(values);
  10044. if (isFunction(listener)) {
  10045. listener.call(this, currValue, values !== oldValues ? lastValue : currValue, scope);
  10046. }
  10047. lastValue = currValue;
  10048. });
  10049. }
  10050. });
  10051. }
  10052. function parseStringifyInterceptor(value) {
  10053. try {
  10054. value = getValue(value);
  10055. return allOrNothing && !isDefined(value) ? value : stringify(value);
  10056. } catch (err) {
  10057. $exceptionHandler($interpolateMinErr.interr(text, err));
  10058. }
  10059. }
  10060. }
  10061. /**
  10062. * @ngdoc method
  10063. * @name $interpolate#startSymbol
  10064. * @description
  10065. * Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
  10066. *
  10067. * Use {@link ng.$interpolateProvider#startSymbol `$interpolateProvider.startSymbol`} to change
  10068. * the symbol.
  10069. *
  10070. * @returns {string} start symbol.
  10071. */
  10072. $interpolate.startSymbol = function() {
  10073. return startSymbol;
  10074. };
  10075. /**
  10076. * @ngdoc method
  10077. * @name $interpolate#endSymbol
  10078. * @description
  10079. * Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
  10080. *
  10081. * Use {@link ng.$interpolateProvider#endSymbol `$interpolateProvider.endSymbol`} to change
  10082. * the symbol.
  10083. *
  10084. * @returns {string} end symbol.
  10085. */
  10086. $interpolate.endSymbol = function() {
  10087. return endSymbol;
  10088. };
  10089. return $interpolate;
  10090. }];
  10091. }
  10092. function $IntervalProvider() {
  10093. this.$get = ['$rootScope', '$window', '$q', '$$q',
  10094. function($rootScope, $window, $q, $$q) {
  10095. var intervals = {};
  10096. /**
  10097. * @ngdoc service
  10098. * @name $interval
  10099. *
  10100. * @description
  10101. * Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
  10102. * milliseconds.
  10103. *
  10104. * The return value of registering an interval function is a promise. This promise will be
  10105. * notified upon each tick of the interval, and will be resolved after `count` iterations, or
  10106. * run indefinitely if `count` is not defined. The value of the notification will be the
  10107. * number of iterations that have run.
  10108. * To cancel an interval, call `$interval.cancel(promise)`.
  10109. *
  10110. * In tests you can use {@link ngMock.$interval#flush `$interval.flush(millis)`} to
  10111. * move forward by `millis` milliseconds and trigger any functions scheduled to run in that
  10112. * time.
  10113. *
  10114. * <div class="alert alert-warning">
  10115. * **Note**: Intervals created by this service must be explicitly destroyed when you are finished
  10116. * with them. In particular they are not automatically destroyed when a controller's scope or a
  10117. * directive's element are destroyed.
  10118. * You should take this into consideration and make sure to always cancel the interval at the
  10119. * appropriate moment. See the example below for more details on how and when to do this.
  10120. * </div>
  10121. *
  10122. * @param {function()} fn A function that should be called repeatedly.
  10123. * @param {number} delay Number of milliseconds between each function call.
  10124. * @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
  10125. * indefinitely.
  10126. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  10127. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  10128. * @param {...*=} Pass additional parameters to the executed function.
  10129. * @returns {promise} A promise which will be notified on each iteration.
  10130. *
  10131. * @example
  10132. * <example module="intervalExample">
  10133. * <file name="index.html">
  10134. * <script>
  10135. * angular.module('intervalExample', [])
  10136. * .controller('ExampleController', ['$scope', '$interval',
  10137. * function($scope, $interval) {
  10138. * $scope.format = 'M/d/yy h:mm:ss a';
  10139. * $scope.blood_1 = 100;
  10140. * $scope.blood_2 = 120;
  10141. *
  10142. * var stop;
  10143. * $scope.fight = function() {
  10144. * // Don't start a new fight if we are already fighting
  10145. * if ( angular.isDefined(stop) ) return;
  10146. *
  10147. * stop = $interval(function() {
  10148. * if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
  10149. * $scope.blood_1 = $scope.blood_1 - 3;
  10150. * $scope.blood_2 = $scope.blood_2 - 4;
  10151. * } else {
  10152. * $scope.stopFight();
  10153. * }
  10154. * }, 100);
  10155. * };
  10156. *
  10157. * $scope.stopFight = function() {
  10158. * if (angular.isDefined(stop)) {
  10159. * $interval.cancel(stop);
  10160. * stop = undefined;
  10161. * }
  10162. * };
  10163. *
  10164. * $scope.resetFight = function() {
  10165. * $scope.blood_1 = 100;
  10166. * $scope.blood_2 = 120;
  10167. * };
  10168. *
  10169. * $scope.$on('$destroy', function() {
  10170. * // Make sure that the interval is destroyed too
  10171. * $scope.stopFight();
  10172. * });
  10173. * }])
  10174. * // Register the 'myCurrentTime' directive factory method.
  10175. * // We inject $interval and dateFilter service since the factory method is DI.
  10176. * .directive('myCurrentTime', ['$interval', 'dateFilter',
  10177. * function($interval, dateFilter) {
  10178. * // return the directive link function. (compile function not needed)
  10179. * return function(scope, element, attrs) {
  10180. * var format, // date format
  10181. * stopTime; // so that we can cancel the time updates
  10182. *
  10183. * // used to update the UI
  10184. * function updateTime() {
  10185. * element.text(dateFilter(new Date(), format));
  10186. * }
  10187. *
  10188. * // watch the expression, and update the UI on change.
  10189. * scope.$watch(attrs.myCurrentTime, function(value) {
  10190. * format = value;
  10191. * updateTime();
  10192. * });
  10193. *
  10194. * stopTime = $interval(updateTime, 1000);
  10195. *
  10196. * // listen on DOM destroy (removal) event, and cancel the next UI update
  10197. * // to prevent updating time after the DOM element was removed.
  10198. * element.on('$destroy', function() {
  10199. * $interval.cancel(stopTime);
  10200. * });
  10201. * }
  10202. * }]);
  10203. * </script>
  10204. *
  10205. * <div>
  10206. * <div ng-controller="ExampleController">
  10207. * <label>Date format: <input ng-model="format"></label> <hr/>
  10208. * Current time is: <span my-current-time="format"></span>
  10209. * <hr/>
  10210. * Blood 1 : <font color='red'>{{blood_1}}</font>
  10211. * Blood 2 : <font color='red'>{{blood_2}}</font>
  10212. * <button type="button" data-ng-click="fight()">Fight</button>
  10213. * <button type="button" data-ng-click="stopFight()">StopFight</button>
  10214. * <button type="button" data-ng-click="resetFight()">resetFight</button>
  10215. * </div>
  10216. * </div>
  10217. *
  10218. * </file>
  10219. * </example>
  10220. */
  10221. function interval(fn, delay, count, invokeApply) {
  10222. var hasParams = arguments.length > 4,
  10223. args = hasParams ? sliceArgs(arguments, 4) : [],
  10224. setInterval = $window.setInterval,
  10225. clearInterval = $window.clearInterval,
  10226. iteration = 0,
  10227. skipApply = (isDefined(invokeApply) && !invokeApply),
  10228. deferred = (skipApply ? $$q : $q).defer(),
  10229. promise = deferred.promise;
  10230. count = isDefined(count) ? count : 0;
  10231. promise.then(null, null, (!hasParams) ? fn : function() {
  10232. fn.apply(null, args);
  10233. });
  10234. promise.$$intervalId = setInterval(function tick() {
  10235. deferred.notify(iteration++);
  10236. if (count > 0 && iteration >= count) {
  10237. deferred.resolve(iteration);
  10238. clearInterval(promise.$$intervalId);
  10239. delete intervals[promise.$$intervalId];
  10240. }
  10241. if (!skipApply) $rootScope.$apply();
  10242. }, delay);
  10243. intervals[promise.$$intervalId] = deferred;
  10244. return promise;
  10245. }
  10246. /**
  10247. * @ngdoc method
  10248. * @name $interval#cancel
  10249. *
  10250. * @description
  10251. * Cancels a task associated with the `promise`.
  10252. *
  10253. * @param {Promise=} promise returned by the `$interval` function.
  10254. * @returns {boolean} Returns `true` if the task was successfully canceled.
  10255. */
  10256. interval.cancel = function(promise) {
  10257. if (promise && promise.$$intervalId in intervals) {
  10258. intervals[promise.$$intervalId].reject('canceled');
  10259. $window.clearInterval(promise.$$intervalId);
  10260. delete intervals[promise.$$intervalId];
  10261. return true;
  10262. }
  10263. return false;
  10264. };
  10265. return interval;
  10266. }];
  10267. }
  10268. /**
  10269. * @ngdoc service
  10270. * @name $locale
  10271. *
  10272. * @description
  10273. * $locale service provides localization rules for various Angular components. As of right now the
  10274. * only public api is:
  10275. *
  10276. * * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
  10277. */
  10278. var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
  10279. DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
  10280. var $locationMinErr = minErr('$location');
  10281. /**
  10282. * Encode path using encodeUriSegment, ignoring forward slashes
  10283. *
  10284. * @param {string} path Path to encode
  10285. * @returns {string}
  10286. */
  10287. function encodePath(path) {
  10288. var segments = path.split('/'),
  10289. i = segments.length;
  10290. while (i--) {
  10291. segments[i] = encodeUriSegment(segments[i]);
  10292. }
  10293. return segments.join('/');
  10294. }
  10295. function parseAbsoluteUrl(absoluteUrl, locationObj) {
  10296. var parsedUrl = urlResolve(absoluteUrl);
  10297. locationObj.$$protocol = parsedUrl.protocol;
  10298. locationObj.$$host = parsedUrl.hostname;
  10299. locationObj.$$port = toInt(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
  10300. }
  10301. function parseAppUrl(relativeUrl, locationObj) {
  10302. var prefixed = (relativeUrl.charAt(0) !== '/');
  10303. if (prefixed) {
  10304. relativeUrl = '/' + relativeUrl;
  10305. }
  10306. var match = urlResolve(relativeUrl);
  10307. locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
  10308. match.pathname.substring(1) : match.pathname);
  10309. locationObj.$$search = parseKeyValue(match.search);
  10310. locationObj.$$hash = decodeURIComponent(match.hash);
  10311. // make sure path starts with '/';
  10312. if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
  10313. locationObj.$$path = '/' + locationObj.$$path;
  10314. }
  10315. }
  10316. /**
  10317. *
  10318. * @param {string} begin
  10319. * @param {string} whole
  10320. * @returns {string} returns text from whole after begin or undefined if it does not begin with
  10321. * expected string.
  10322. */
  10323. function beginsWith(begin, whole) {
  10324. if (whole.indexOf(begin) === 0) {
  10325. return whole.substr(begin.length);
  10326. }
  10327. }
  10328. function stripHash(url) {
  10329. var index = url.indexOf('#');
  10330. return index == -1 ? url : url.substr(0, index);
  10331. }
  10332. function trimEmptyHash(url) {
  10333. return url.replace(/(#.+)|#$/, '$1');
  10334. }
  10335. function stripFile(url) {
  10336. return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
  10337. }
  10338. /* return the server only (scheme://host:port) */
  10339. function serverBase(url) {
  10340. return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
  10341. }
  10342. /**
  10343. * LocationHtml5Url represents an url
  10344. * This object is exposed as $location service when HTML5 mode is enabled and supported
  10345. *
  10346. * @constructor
  10347. * @param {string} appBase application base URL
  10348. * @param {string} appBaseNoFile application base URL stripped of any filename
  10349. * @param {string} basePrefix url path prefix
  10350. */
  10351. function LocationHtml5Url(appBase, appBaseNoFile, basePrefix) {
  10352. this.$$html5 = true;
  10353. basePrefix = basePrefix || '';
  10354. parseAbsoluteUrl(appBase, this);
  10355. /**
  10356. * Parse given html5 (regular) url string into properties
  10357. * @param {string} url HTML5 url
  10358. * @private
  10359. */
  10360. this.$$parse = function(url) {
  10361. var pathUrl = beginsWith(appBaseNoFile, url);
  10362. if (!isString(pathUrl)) {
  10363. throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
  10364. appBaseNoFile);
  10365. }
  10366. parseAppUrl(pathUrl, this);
  10367. if (!this.$$path) {
  10368. this.$$path = '/';
  10369. }
  10370. this.$$compose();
  10371. };
  10372. /**
  10373. * Compose url and update `absUrl` property
  10374. * @private
  10375. */
  10376. this.$$compose = function() {
  10377. var search = toKeyValue(this.$$search),
  10378. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10379. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10380. this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
  10381. };
  10382. this.$$parseLinkUrl = function(url, relHref) {
  10383. if (relHref && relHref[0] === '#') {
  10384. // special case for links to hash fragments:
  10385. // keep the old url and only replace the hash fragment
  10386. this.hash(relHref.slice(1));
  10387. return true;
  10388. }
  10389. var appUrl, prevAppUrl;
  10390. var rewrittenUrl;
  10391. if (isDefined(appUrl = beginsWith(appBase, url))) {
  10392. prevAppUrl = appUrl;
  10393. if (isDefined(appUrl = beginsWith(basePrefix, appUrl))) {
  10394. rewrittenUrl = appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
  10395. } else {
  10396. rewrittenUrl = appBase + prevAppUrl;
  10397. }
  10398. } else if (isDefined(appUrl = beginsWith(appBaseNoFile, url))) {
  10399. rewrittenUrl = appBaseNoFile + appUrl;
  10400. } else if (appBaseNoFile == url + '/') {
  10401. rewrittenUrl = appBaseNoFile;
  10402. }
  10403. if (rewrittenUrl) {
  10404. this.$$parse(rewrittenUrl);
  10405. }
  10406. return !!rewrittenUrl;
  10407. };
  10408. }
  10409. /**
  10410. * LocationHashbangUrl represents url
  10411. * This object is exposed as $location service when developer doesn't opt into html5 mode.
  10412. * It also serves as the base class for html5 mode fallback on legacy browsers.
  10413. *
  10414. * @constructor
  10415. * @param {string} appBase application base URL
  10416. * @param {string} appBaseNoFile application base URL stripped of any filename
  10417. * @param {string} hashPrefix hashbang prefix
  10418. */
  10419. function LocationHashbangUrl(appBase, appBaseNoFile, hashPrefix) {
  10420. parseAbsoluteUrl(appBase, this);
  10421. /**
  10422. * Parse given hashbang url into properties
  10423. * @param {string} url Hashbang url
  10424. * @private
  10425. */
  10426. this.$$parse = function(url) {
  10427. var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
  10428. var withoutHashUrl;
  10429. if (!isUndefined(withoutBaseUrl) && withoutBaseUrl.charAt(0) === '#') {
  10430. // The rest of the url starts with a hash so we have
  10431. // got either a hashbang path or a plain hash fragment
  10432. withoutHashUrl = beginsWith(hashPrefix, withoutBaseUrl);
  10433. if (isUndefined(withoutHashUrl)) {
  10434. // There was no hashbang prefix so we just have a hash fragment
  10435. withoutHashUrl = withoutBaseUrl;
  10436. }
  10437. } else {
  10438. // There was no hashbang path nor hash fragment:
  10439. // If we are in HTML5 mode we use what is left as the path;
  10440. // Otherwise we ignore what is left
  10441. if (this.$$html5) {
  10442. withoutHashUrl = withoutBaseUrl;
  10443. } else {
  10444. withoutHashUrl = '';
  10445. if (isUndefined(withoutBaseUrl)) {
  10446. appBase = url;
  10447. this.replace();
  10448. }
  10449. }
  10450. }
  10451. parseAppUrl(withoutHashUrl, this);
  10452. this.$$path = removeWindowsDriveName(this.$$path, withoutHashUrl, appBase);
  10453. this.$$compose();
  10454. /*
  10455. * In Windows, on an anchor node on documents loaded from
  10456. * the filesystem, the browser will return a pathname
  10457. * prefixed with the drive name ('/C:/path') when a
  10458. * pathname without a drive is set:
  10459. * * a.setAttribute('href', '/foo')
  10460. * * a.pathname === '/C:/foo' //true
  10461. *
  10462. * Inside of Angular, we're always using pathnames that
  10463. * do not include drive names for routing.
  10464. */
  10465. function removeWindowsDriveName(path, url, base) {
  10466. /*
  10467. Matches paths for file protocol on windows,
  10468. such as /C:/foo/bar, and captures only /foo/bar.
  10469. */
  10470. var windowsFilePathExp = /^\/[A-Z]:(\/.*)/;
  10471. var firstPathSegmentMatch;
  10472. //Get the relative path from the input URL.
  10473. if (url.indexOf(base) === 0) {
  10474. url = url.replace(base, '');
  10475. }
  10476. // The input URL intentionally contains a first path segment that ends with a colon.
  10477. if (windowsFilePathExp.exec(url)) {
  10478. return path;
  10479. }
  10480. firstPathSegmentMatch = windowsFilePathExp.exec(path);
  10481. return firstPathSegmentMatch ? firstPathSegmentMatch[1] : path;
  10482. }
  10483. };
  10484. /**
  10485. * Compose hashbang url and update `absUrl` property
  10486. * @private
  10487. */
  10488. this.$$compose = function() {
  10489. var search = toKeyValue(this.$$search),
  10490. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10491. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10492. this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
  10493. };
  10494. this.$$parseLinkUrl = function(url, relHref) {
  10495. if (stripHash(appBase) == stripHash(url)) {
  10496. this.$$parse(url);
  10497. return true;
  10498. }
  10499. return false;
  10500. };
  10501. }
  10502. /**
  10503. * LocationHashbangUrl represents url
  10504. * This object is exposed as $location service when html5 history api is enabled but the browser
  10505. * does not support it.
  10506. *
  10507. * @constructor
  10508. * @param {string} appBase application base URL
  10509. * @param {string} appBaseNoFile application base URL stripped of any filename
  10510. * @param {string} hashPrefix hashbang prefix
  10511. */
  10512. function LocationHashbangInHtml5Url(appBase, appBaseNoFile, hashPrefix) {
  10513. this.$$html5 = true;
  10514. LocationHashbangUrl.apply(this, arguments);
  10515. this.$$parseLinkUrl = function(url, relHref) {
  10516. if (relHref && relHref[0] === '#') {
  10517. // special case for links to hash fragments:
  10518. // keep the old url and only replace the hash fragment
  10519. this.hash(relHref.slice(1));
  10520. return true;
  10521. }
  10522. var rewrittenUrl;
  10523. var appUrl;
  10524. if (appBase == stripHash(url)) {
  10525. rewrittenUrl = url;
  10526. } else if ((appUrl = beginsWith(appBaseNoFile, url))) {
  10527. rewrittenUrl = appBase + hashPrefix + appUrl;
  10528. } else if (appBaseNoFile === url + '/') {
  10529. rewrittenUrl = appBaseNoFile;
  10530. }
  10531. if (rewrittenUrl) {
  10532. this.$$parse(rewrittenUrl);
  10533. }
  10534. return !!rewrittenUrl;
  10535. };
  10536. this.$$compose = function() {
  10537. var search = toKeyValue(this.$$search),
  10538. hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
  10539. this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
  10540. // include hashPrefix in $$absUrl when $$url is empty so IE9 does not reload page because of removal of '#'
  10541. this.$$absUrl = appBase + hashPrefix + this.$$url;
  10542. };
  10543. }
  10544. var locationPrototype = {
  10545. /**
  10546. * Are we in html5 mode?
  10547. * @private
  10548. */
  10549. $$html5: false,
  10550. /**
  10551. * Has any change been replacing?
  10552. * @private
  10553. */
  10554. $$replace: false,
  10555. /**
  10556. * @ngdoc method
  10557. * @name $location#absUrl
  10558. *
  10559. * @description
  10560. * This method is getter only.
  10561. *
  10562. * Return full url representation with all segments encoded according to rules specified in
  10563. * [RFC 3986](http://www.ietf.org/rfc/rfc3986.txt).
  10564. *
  10565. *
  10566. * ```js
  10567. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10568. * var absUrl = $location.absUrl();
  10569. * // => "http://example.com/#/some/path?foo=bar&baz=xoxo"
  10570. * ```
  10571. *
  10572. * @return {string} full url
  10573. */
  10574. absUrl: locationGetter('$$absUrl'),
  10575. /**
  10576. * @ngdoc method
  10577. * @name $location#url
  10578. *
  10579. * @description
  10580. * This method is getter / setter.
  10581. *
  10582. * Return url (e.g. `/path?a=b#hash`) when called without any parameter.
  10583. *
  10584. * Change path, search and hash, when called with parameter and return `$location`.
  10585. *
  10586. *
  10587. * ```js
  10588. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10589. * var url = $location.url();
  10590. * // => "/some/path?foo=bar&baz=xoxo"
  10591. * ```
  10592. *
  10593. * @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
  10594. * @return {string} url
  10595. */
  10596. url: function(url) {
  10597. if (isUndefined(url)) {
  10598. return this.$$url;
  10599. }
  10600. var match = PATH_MATCH.exec(url);
  10601. if (match[1] || url === '') this.path(decodeURIComponent(match[1]));
  10602. if (match[2] || match[1] || url === '') this.search(match[3] || '');
  10603. this.hash(match[5] || '');
  10604. return this;
  10605. },
  10606. /**
  10607. * @ngdoc method
  10608. * @name $location#protocol
  10609. *
  10610. * @description
  10611. * This method is getter only.
  10612. *
  10613. * Return protocol of current url.
  10614. *
  10615. *
  10616. * ```js
  10617. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10618. * var protocol = $location.protocol();
  10619. * // => "http"
  10620. * ```
  10621. *
  10622. * @return {string} protocol of current url
  10623. */
  10624. protocol: locationGetter('$$protocol'),
  10625. /**
  10626. * @ngdoc method
  10627. * @name $location#host
  10628. *
  10629. * @description
  10630. * This method is getter only.
  10631. *
  10632. * Return host of current url.
  10633. *
  10634. * Note: compared to the non-angular version `location.host` which returns `hostname:port`, this returns the `hostname` portion only.
  10635. *
  10636. *
  10637. * ```js
  10638. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10639. * var host = $location.host();
  10640. * // => "example.com"
  10641. *
  10642. * // given url http://user:password@example.com:8080/#/some/path?foo=bar&baz=xoxo
  10643. * host = $location.host();
  10644. * // => "example.com"
  10645. * host = location.host;
  10646. * // => "example.com:8080"
  10647. * ```
  10648. *
  10649. * @return {string} host of current url.
  10650. */
  10651. host: locationGetter('$$host'),
  10652. /**
  10653. * @ngdoc method
  10654. * @name $location#port
  10655. *
  10656. * @description
  10657. * This method is getter only.
  10658. *
  10659. * Return port of current url.
  10660. *
  10661. *
  10662. * ```js
  10663. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10664. * var port = $location.port();
  10665. * // => 80
  10666. * ```
  10667. *
  10668. * @return {Number} port
  10669. */
  10670. port: locationGetter('$$port'),
  10671. /**
  10672. * @ngdoc method
  10673. * @name $location#path
  10674. *
  10675. * @description
  10676. * This method is getter / setter.
  10677. *
  10678. * Return path of current url when called without any parameter.
  10679. *
  10680. * Change path when called with parameter and return `$location`.
  10681. *
  10682. * Note: Path should always begin with forward slash (/), this method will add the forward slash
  10683. * if it is missing.
  10684. *
  10685. *
  10686. * ```js
  10687. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10688. * var path = $location.path();
  10689. * // => "/some/path"
  10690. * ```
  10691. *
  10692. * @param {(string|number)=} path New path
  10693. * @return {string} path
  10694. */
  10695. path: locationGetterSetter('$$path', function(path) {
  10696. path = path !== null ? path.toString() : '';
  10697. return path.charAt(0) == '/' ? path : '/' + path;
  10698. }),
  10699. /**
  10700. * @ngdoc method
  10701. * @name $location#search
  10702. *
  10703. * @description
  10704. * This method is getter / setter.
  10705. *
  10706. * Return search part (as object) of current url when called without any parameter.
  10707. *
  10708. * Change search part when called with parameter and return `$location`.
  10709. *
  10710. *
  10711. * ```js
  10712. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo
  10713. * var searchObject = $location.search();
  10714. * // => {foo: 'bar', baz: 'xoxo'}
  10715. *
  10716. * // set foo to 'yipee'
  10717. * $location.search('foo', 'yipee');
  10718. * // $location.search() => {foo: 'yipee', baz: 'xoxo'}
  10719. * ```
  10720. *
  10721. * @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
  10722. * hash object.
  10723. *
  10724. * When called with a single argument the method acts as a setter, setting the `search` component
  10725. * of `$location` to the specified value.
  10726. *
  10727. * If the argument is a hash object containing an array of values, these values will be encoded
  10728. * as duplicate search parameters in the url.
  10729. *
  10730. * @param {(string|Number|Array<string>|boolean)=} paramValue If `search` is a string or number, then `paramValue`
  10731. * will override only a single search property.
  10732. *
  10733. * If `paramValue` is an array, it will override the property of the `search` component of
  10734. * `$location` specified via the first argument.
  10735. *
  10736. * If `paramValue` is `null`, the property specified via the first argument will be deleted.
  10737. *
  10738. * If `paramValue` is `true`, the property specified via the first argument will be added with no
  10739. * value nor trailing equal sign.
  10740. *
  10741. * @return {Object} If called with no arguments returns the parsed `search` object. If called with
  10742. * one or more arguments returns `$location` object itself.
  10743. */
  10744. search: function(search, paramValue) {
  10745. switch (arguments.length) {
  10746. case 0:
  10747. return this.$$search;
  10748. case 1:
  10749. if (isString(search) || isNumber(search)) {
  10750. search = search.toString();
  10751. this.$$search = parseKeyValue(search);
  10752. } else if (isObject(search)) {
  10753. search = copy(search, {});
  10754. // remove object undefined or null properties
  10755. forEach(search, function(value, key) {
  10756. if (value == null) delete search[key];
  10757. });
  10758. this.$$search = search;
  10759. } else {
  10760. throw $locationMinErr('isrcharg',
  10761. 'The first argument of the `$location#search()` call must be a string or an object.');
  10762. }
  10763. break;
  10764. default:
  10765. if (isUndefined(paramValue) || paramValue === null) {
  10766. delete this.$$search[search];
  10767. } else {
  10768. this.$$search[search] = paramValue;
  10769. }
  10770. }
  10771. this.$$compose();
  10772. return this;
  10773. },
  10774. /**
  10775. * @ngdoc method
  10776. * @name $location#hash
  10777. *
  10778. * @description
  10779. * This method is getter / setter.
  10780. *
  10781. * Returns the hash fragment when called without any parameters.
  10782. *
  10783. * Changes the hash fragment when called with a parameter and returns `$location`.
  10784. *
  10785. *
  10786. * ```js
  10787. * // given url http://example.com/#/some/path?foo=bar&baz=xoxo#hashValue
  10788. * var hash = $location.hash();
  10789. * // => "hashValue"
  10790. * ```
  10791. *
  10792. * @param {(string|number)=} hash New hash fragment
  10793. * @return {string} hash
  10794. */
  10795. hash: locationGetterSetter('$$hash', function(hash) {
  10796. return hash !== null ? hash.toString() : '';
  10797. }),
  10798. /**
  10799. * @ngdoc method
  10800. * @name $location#replace
  10801. *
  10802. * @description
  10803. * If called, all changes to $location during the current `$digest` will replace the current history
  10804. * record, instead of adding a new one.
  10805. */
  10806. replace: function() {
  10807. this.$$replace = true;
  10808. return this;
  10809. }
  10810. };
  10811. forEach([LocationHashbangInHtml5Url, LocationHashbangUrl, LocationHtml5Url], function(Location) {
  10812. Location.prototype = Object.create(locationPrototype);
  10813. /**
  10814. * @ngdoc method
  10815. * @name $location#state
  10816. *
  10817. * @description
  10818. * This method is getter / setter.
  10819. *
  10820. * Return the history state object when called without any parameter.
  10821. *
  10822. * Change the history state object when called with one parameter and return `$location`.
  10823. * The state object is later passed to `pushState` or `replaceState`.
  10824. *
  10825. * NOTE: This method is supported only in HTML5 mode and only in browsers supporting
  10826. * the HTML5 History API (i.e. methods `pushState` and `replaceState`). If you need to support
  10827. * older browsers (like IE9 or Android < 4.0), don't use this method.
  10828. *
  10829. * @param {object=} state State object for pushState or replaceState
  10830. * @return {object} state
  10831. */
  10832. Location.prototype.state = function(state) {
  10833. if (!arguments.length) {
  10834. return this.$$state;
  10835. }
  10836. if (Location !== LocationHtml5Url || !this.$$html5) {
  10837. throw $locationMinErr('nostate', 'History API state support is available only ' +
  10838. 'in HTML5 mode and only in browsers supporting HTML5 History API');
  10839. }
  10840. // The user might modify `stateObject` after invoking `$location.state(stateObject)`
  10841. // but we're changing the $$state reference to $browser.state() during the $digest
  10842. // so the modification window is narrow.
  10843. this.$$state = isUndefined(state) ? null : state;
  10844. return this;
  10845. };
  10846. });
  10847. function locationGetter(property) {
  10848. return function() {
  10849. return this[property];
  10850. };
  10851. }
  10852. function locationGetterSetter(property, preprocess) {
  10853. return function(value) {
  10854. if (isUndefined(value)) {
  10855. return this[property];
  10856. }
  10857. this[property] = preprocess(value);
  10858. this.$$compose();
  10859. return this;
  10860. };
  10861. }
  10862. /**
  10863. * @ngdoc service
  10864. * @name $location
  10865. *
  10866. * @requires $rootElement
  10867. *
  10868. * @description
  10869. * The $location service parses the URL in the browser address bar (based on the
  10870. * [window.location](https://developer.mozilla.org/en/window.location)) and makes the URL
  10871. * available to your application. Changes to the URL in the address bar are reflected into
  10872. * $location service and changes to $location are reflected into the browser address bar.
  10873. *
  10874. * **The $location service:**
  10875. *
  10876. * - Exposes the current URL in the browser address bar, so you can
  10877. * - Watch and observe the URL.
  10878. * - Change the URL.
  10879. * - Synchronizes the URL with the browser when the user
  10880. * - Changes the address bar.
  10881. * - Clicks the back or forward button (or clicks a History link).
  10882. * - Clicks on a link.
  10883. * - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
  10884. *
  10885. * For more information see {@link guide/$location Developer Guide: Using $location}
  10886. */
  10887. /**
  10888. * @ngdoc provider
  10889. * @name $locationProvider
  10890. * @description
  10891. * Use the `$locationProvider` to configure how the application deep linking paths are stored.
  10892. */
  10893. function $LocationProvider() {
  10894. var hashPrefix = '',
  10895. html5Mode = {
  10896. enabled: false,
  10897. requireBase: true,
  10898. rewriteLinks: true
  10899. };
  10900. /**
  10901. * @ngdoc method
  10902. * @name $locationProvider#hashPrefix
  10903. * @description
  10904. * @param {string=} prefix Prefix for hash part (containing path and search)
  10905. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  10906. */
  10907. this.hashPrefix = function(prefix) {
  10908. if (isDefined(prefix)) {
  10909. hashPrefix = prefix;
  10910. return this;
  10911. } else {
  10912. return hashPrefix;
  10913. }
  10914. };
  10915. /**
  10916. * @ngdoc method
  10917. * @name $locationProvider#html5Mode
  10918. * @description
  10919. * @param {(boolean|Object)=} mode If boolean, sets `html5Mode.enabled` to value.
  10920. * If object, sets `enabled`, `requireBase` and `rewriteLinks` to respective values. Supported
  10921. * properties:
  10922. * - **enabled** – `{boolean}` – (default: false) If true, will rely on `history.pushState` to
  10923. * change urls where supported. Will fall back to hash-prefixed paths in browsers that do not
  10924. * support `pushState`.
  10925. * - **requireBase** - `{boolean}` - (default: `true`) When html5Mode is enabled, specifies
  10926. * whether or not a <base> tag is required to be present. If `enabled` and `requireBase` are
  10927. * true, and a base tag is not present, an error will be thrown when `$location` is injected.
  10928. * See the {@link guide/$location $location guide for more information}
  10929. * - **rewriteLinks** - `{boolean}` - (default: `true`) When html5Mode is enabled,
  10930. * enables/disables url rewriting for relative links.
  10931. *
  10932. * @returns {Object} html5Mode object if used as getter or itself (chaining) if used as setter
  10933. */
  10934. this.html5Mode = function(mode) {
  10935. if (isBoolean(mode)) {
  10936. html5Mode.enabled = mode;
  10937. return this;
  10938. } else if (isObject(mode)) {
  10939. if (isBoolean(mode.enabled)) {
  10940. html5Mode.enabled = mode.enabled;
  10941. }
  10942. if (isBoolean(mode.requireBase)) {
  10943. html5Mode.requireBase = mode.requireBase;
  10944. }
  10945. if (isBoolean(mode.rewriteLinks)) {
  10946. html5Mode.rewriteLinks = mode.rewriteLinks;
  10947. }
  10948. return this;
  10949. } else {
  10950. return html5Mode;
  10951. }
  10952. };
  10953. /**
  10954. * @ngdoc event
  10955. * @name $location#$locationChangeStart
  10956. * @eventType broadcast on root scope
  10957. * @description
  10958. * Broadcasted before a URL will change.
  10959. *
  10960. * This change can be prevented by calling
  10961. * `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
  10962. * details about event object. Upon successful change
  10963. * {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
  10964. *
  10965. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10966. * the browser supports the HTML5 History API.
  10967. *
  10968. * @param {Object} angularEvent Synthetic event object.
  10969. * @param {string} newUrl New URL
  10970. * @param {string=} oldUrl URL that was before it was changed.
  10971. * @param {string=} newState New history state object
  10972. * @param {string=} oldState History state object that was before it was changed.
  10973. */
  10974. /**
  10975. * @ngdoc event
  10976. * @name $location#$locationChangeSuccess
  10977. * @eventType broadcast on root scope
  10978. * @description
  10979. * Broadcasted after a URL was changed.
  10980. *
  10981. * The `newState` and `oldState` parameters may be defined only in HTML5 mode and when
  10982. * the browser supports the HTML5 History API.
  10983. *
  10984. * @param {Object} angularEvent Synthetic event object.
  10985. * @param {string} newUrl New URL
  10986. * @param {string=} oldUrl URL that was before it was changed.
  10987. * @param {string=} newState New history state object
  10988. * @param {string=} oldState History state object that was before it was changed.
  10989. */
  10990. this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement', '$window',
  10991. function($rootScope, $browser, $sniffer, $rootElement, $window) {
  10992. var $location,
  10993. LocationMode,
  10994. baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
  10995. initialUrl = $browser.url(),
  10996. appBase;
  10997. if (html5Mode.enabled) {
  10998. if (!baseHref && html5Mode.requireBase) {
  10999. throw $locationMinErr('nobase',
  11000. "$location in HTML5 mode requires a <base> tag to be present!");
  11001. }
  11002. appBase = serverBase(initialUrl) + (baseHref || '/');
  11003. LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
  11004. } else {
  11005. appBase = stripHash(initialUrl);
  11006. LocationMode = LocationHashbangUrl;
  11007. }
  11008. var appBaseNoFile = stripFile(appBase);
  11009. $location = new LocationMode(appBase, appBaseNoFile, '#' + hashPrefix);
  11010. $location.$$parseLinkUrl(initialUrl, initialUrl);
  11011. $location.$$state = $browser.state();
  11012. var IGNORE_URI_REGEXP = /^\s*(javascript|mailto):/i;
  11013. function setBrowserUrlWithFallback(url, replace, state) {
  11014. var oldUrl = $location.url();
  11015. var oldState = $location.$$state;
  11016. try {
  11017. $browser.url(url, replace, state);
  11018. // Make sure $location.state() returns referentially identical (not just deeply equal)
  11019. // state object; this makes possible quick checking if the state changed in the digest
  11020. // loop. Checking deep equality would be too expensive.
  11021. $location.$$state = $browser.state();
  11022. } catch (e) {
  11023. // Restore old values if pushState fails
  11024. $location.url(oldUrl);
  11025. $location.$$state = oldState;
  11026. throw e;
  11027. }
  11028. }
  11029. $rootElement.on('click', function(event) {
  11030. // TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
  11031. // currently we open nice url link and redirect then
  11032. if (!html5Mode.rewriteLinks || event.ctrlKey || event.metaKey || event.shiftKey || event.which == 2 || event.button == 2) return;
  11033. var elm = jqLite(event.target);
  11034. // traverse the DOM up to find first A tag
  11035. while (nodeName_(elm[0]) !== 'a') {
  11036. // ignore rewriting if no A tag (reached root element, or no parent - removed from document)
  11037. if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
  11038. }
  11039. var absHref = elm.prop('href');
  11040. // get the actual href attribute - see
  11041. // http://msdn.microsoft.com/en-us/library/ie/dd347148(v=vs.85).aspx
  11042. var relHref = elm.attr('href') || elm.attr('xlink:href');
  11043. if (isObject(absHref) && absHref.toString() === '[object SVGAnimatedString]') {
  11044. // SVGAnimatedString.animVal should be identical to SVGAnimatedString.baseVal, unless during
  11045. // an animation.
  11046. absHref = urlResolve(absHref.animVal).href;
  11047. }
  11048. // Ignore when url is started with javascript: or mailto:
  11049. if (IGNORE_URI_REGEXP.test(absHref)) return;
  11050. if (absHref && !elm.attr('target') && !event.isDefaultPrevented()) {
  11051. if ($location.$$parseLinkUrl(absHref, relHref)) {
  11052. // We do a preventDefault for all urls that are part of the angular application,
  11053. // in html5mode and also without, so that we are able to abort navigation without
  11054. // getting double entries in the location history.
  11055. event.preventDefault();
  11056. // update location manually
  11057. if ($location.absUrl() != $browser.url()) {
  11058. $rootScope.$apply();
  11059. // hack to work around FF6 bug 684208 when scenario runner clicks on links
  11060. $window.angular['ff-684208-preventDefault'] = true;
  11061. }
  11062. }
  11063. }
  11064. });
  11065. // rewrite hashbang url <> html5 url
  11066. if (trimEmptyHash($location.absUrl()) != trimEmptyHash(initialUrl)) {
  11067. $browser.url($location.absUrl(), true);
  11068. }
  11069. var initializing = true;
  11070. // update $location when $browser url changes
  11071. $browser.onUrlChange(function(newUrl, newState) {
  11072. if (isUndefined(beginsWith(appBaseNoFile, newUrl))) {
  11073. // If we are navigating outside of the app then force a reload
  11074. $window.location.href = newUrl;
  11075. return;
  11076. }
  11077. $rootScope.$evalAsync(function() {
  11078. var oldUrl = $location.absUrl();
  11079. var oldState = $location.$$state;
  11080. var defaultPrevented;
  11081. newUrl = trimEmptyHash(newUrl);
  11082. $location.$$parse(newUrl);
  11083. $location.$$state = newState;
  11084. defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11085. newState, oldState).defaultPrevented;
  11086. // if the location was changed by a `$locationChangeStart` handler then stop
  11087. // processing this location change
  11088. if ($location.absUrl() !== newUrl) return;
  11089. if (defaultPrevented) {
  11090. $location.$$parse(oldUrl);
  11091. $location.$$state = oldState;
  11092. setBrowserUrlWithFallback(oldUrl, false, oldState);
  11093. } else {
  11094. initializing = false;
  11095. afterLocationChange(oldUrl, oldState);
  11096. }
  11097. });
  11098. if (!$rootScope.$$phase) $rootScope.$digest();
  11099. });
  11100. // update browser
  11101. $rootScope.$watch(function $locationWatch() {
  11102. var oldUrl = trimEmptyHash($browser.url());
  11103. var newUrl = trimEmptyHash($location.absUrl());
  11104. var oldState = $browser.state();
  11105. var currentReplace = $location.$$replace;
  11106. var urlOrStateChanged = oldUrl !== newUrl ||
  11107. ($location.$$html5 && $sniffer.history && oldState !== $location.$$state);
  11108. if (initializing || urlOrStateChanged) {
  11109. initializing = false;
  11110. $rootScope.$evalAsync(function() {
  11111. var newUrl = $location.absUrl();
  11112. var defaultPrevented = $rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl,
  11113. $location.$$state, oldState).defaultPrevented;
  11114. // if the location was changed by a `$locationChangeStart` handler then stop
  11115. // processing this location change
  11116. if ($location.absUrl() !== newUrl) return;
  11117. if (defaultPrevented) {
  11118. $location.$$parse(oldUrl);
  11119. $location.$$state = oldState;
  11120. } else {
  11121. if (urlOrStateChanged) {
  11122. setBrowserUrlWithFallback(newUrl, currentReplace,
  11123. oldState === $location.$$state ? null : $location.$$state);
  11124. }
  11125. afterLocationChange(oldUrl, oldState);
  11126. }
  11127. });
  11128. }
  11129. $location.$$replace = false;
  11130. // we don't need to return anything because $evalAsync will make the digest loop dirty when
  11131. // there is a change
  11132. });
  11133. return $location;
  11134. function afterLocationChange(oldUrl, oldState) {
  11135. $rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl,
  11136. $location.$$state, oldState);
  11137. }
  11138. }];
  11139. }
  11140. /**
  11141. * @ngdoc service
  11142. * @name $log
  11143. * @requires $window
  11144. *
  11145. * @description
  11146. * Simple service for logging. Default implementation safely writes the message
  11147. * into the browser's console (if present).
  11148. *
  11149. * The main purpose of this service is to simplify debugging and troubleshooting.
  11150. *
  11151. * The default is to log `debug` messages. You can use
  11152. * {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
  11153. *
  11154. * @example
  11155. <example module="logExample">
  11156. <file name="script.js">
  11157. angular.module('logExample', [])
  11158. .controller('LogController', ['$scope', '$log', function($scope, $log) {
  11159. $scope.$log = $log;
  11160. $scope.message = 'Hello World!';
  11161. }]);
  11162. </file>
  11163. <file name="index.html">
  11164. <div ng-controller="LogController">
  11165. <p>Reload this page with open console, enter text and hit the log button...</p>
  11166. <label>Message:
  11167. <input type="text" ng-model="message" /></label>
  11168. <button ng-click="$log.log(message)">log</button>
  11169. <button ng-click="$log.warn(message)">warn</button>
  11170. <button ng-click="$log.info(message)">info</button>
  11171. <button ng-click="$log.error(message)">error</button>
  11172. <button ng-click="$log.debug(message)">debug</button>
  11173. </div>
  11174. </file>
  11175. </example>
  11176. */
  11177. /**
  11178. * @ngdoc provider
  11179. * @name $logProvider
  11180. * @description
  11181. * Use the `$logProvider` to configure how the application logs messages
  11182. */
  11183. function $LogProvider() {
  11184. var debug = true,
  11185. self = this;
  11186. /**
  11187. * @ngdoc method
  11188. * @name $logProvider#debugEnabled
  11189. * @description
  11190. * @param {boolean=} flag enable or disable debug level messages
  11191. * @returns {*} current value if used as getter or itself (chaining) if used as setter
  11192. */
  11193. this.debugEnabled = function(flag) {
  11194. if (isDefined(flag)) {
  11195. debug = flag;
  11196. return this;
  11197. } else {
  11198. return debug;
  11199. }
  11200. };
  11201. this.$get = ['$window', function($window) {
  11202. return {
  11203. /**
  11204. * @ngdoc method
  11205. * @name $log#log
  11206. *
  11207. * @description
  11208. * Write a log message
  11209. */
  11210. log: consoleLog('log'),
  11211. /**
  11212. * @ngdoc method
  11213. * @name $log#info
  11214. *
  11215. * @description
  11216. * Write an information message
  11217. */
  11218. info: consoleLog('info'),
  11219. /**
  11220. * @ngdoc method
  11221. * @name $log#warn
  11222. *
  11223. * @description
  11224. * Write a warning message
  11225. */
  11226. warn: consoleLog('warn'),
  11227. /**
  11228. * @ngdoc method
  11229. * @name $log#error
  11230. *
  11231. * @description
  11232. * Write an error message
  11233. */
  11234. error: consoleLog('error'),
  11235. /**
  11236. * @ngdoc method
  11237. * @name $log#debug
  11238. *
  11239. * @description
  11240. * Write a debug message
  11241. */
  11242. debug: (function() {
  11243. var fn = consoleLog('debug');
  11244. return function() {
  11245. if (debug) {
  11246. fn.apply(self, arguments);
  11247. }
  11248. };
  11249. }())
  11250. };
  11251. function formatError(arg) {
  11252. if (arg instanceof Error) {
  11253. if (arg.stack) {
  11254. arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
  11255. ? 'Error: ' + arg.message + '\n' + arg.stack
  11256. : arg.stack;
  11257. } else if (arg.sourceURL) {
  11258. arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
  11259. }
  11260. }
  11261. return arg;
  11262. }
  11263. function consoleLog(type) {
  11264. var console = $window.console || {},
  11265. logFn = console[type] || console.log || noop,
  11266. hasApply = false;
  11267. // Note: reading logFn.apply throws an error in IE11 in IE8 document mode.
  11268. // The reason behind this is that console.log has type "object" in IE8...
  11269. try {
  11270. hasApply = !!logFn.apply;
  11271. } catch (e) {}
  11272. if (hasApply) {
  11273. return function() {
  11274. var args = [];
  11275. forEach(arguments, function(arg) {
  11276. args.push(formatError(arg));
  11277. });
  11278. return logFn.apply(console, args);
  11279. };
  11280. }
  11281. // we are IE which either doesn't have window.console => this is noop and we do nothing,
  11282. // or we are IE where console.log doesn't have apply so we log at least first 2 args
  11283. return function(arg1, arg2) {
  11284. logFn(arg1, arg2 == null ? '' : arg2);
  11285. };
  11286. }
  11287. }];
  11288. }
  11289. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  11290. * Any commits to this file should be reviewed with security in mind. *
  11291. * Changes to this file can potentially create security vulnerabilities. *
  11292. * An approval from 2 Core members with history of modifying *
  11293. * this file is required. *
  11294. * *
  11295. * Does the change somehow allow for arbitrary javascript to be executed? *
  11296. * Or allows for someone to change the prototype of built-in objects? *
  11297. * Or gives undesired access to variables likes document or window? *
  11298. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  11299. var $parseMinErr = minErr('$parse');
  11300. // Sandboxing Angular Expressions
  11301. // ------------------------------
  11302. // Angular expressions are generally considered safe because these expressions only have direct
  11303. // access to `$scope` and locals. However, one can obtain the ability to execute arbitrary JS code by
  11304. // obtaining a reference to native JS functions such as the Function constructor.
  11305. //
  11306. // As an example, consider the following Angular expression:
  11307. //
  11308. // {}.toString.constructor('alert("evil JS code")')
  11309. //
  11310. // This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
  11311. // against the expression language, but not to prevent exploits that were enabled by exposing
  11312. // sensitive JavaScript or browser APIs on Scope. Exposing such objects on a Scope is never a good
  11313. // practice and therefore we are not even trying to protect against interaction with an object
  11314. // explicitly exposed in this way.
  11315. //
  11316. // In general, it is not possible to access a Window object from an angular expression unless a
  11317. // window or some DOM object that has a reference to window is published onto a Scope.
  11318. // Similarly we prevent invocations of function known to be dangerous, as well as assignments to
  11319. // native objects.
  11320. //
  11321. // See https://docs.angularjs.org/guide/security
  11322. function ensureSafeMemberName(name, fullExpression) {
  11323. if (name === "__defineGetter__" || name === "__defineSetter__"
  11324. || name === "__lookupGetter__" || name === "__lookupSetter__"
  11325. || name === "__proto__") {
  11326. throw $parseMinErr('isecfld',
  11327. 'Attempting to access a disallowed field in Angular expressions! '
  11328. + 'Expression: {0}', fullExpression);
  11329. }
  11330. return name;
  11331. }
  11332. function getStringValue(name, fullExpression) {
  11333. // From the JavaScript docs:
  11334. // Property names must be strings. This means that non-string objects cannot be used
  11335. // as keys in an object. Any non-string object, including a number, is typecasted
  11336. // into a string via the toString method.
  11337. //
  11338. // So, to ensure that we are checking the same `name` that JavaScript would use,
  11339. // we cast it to a string, if possible.
  11340. // Doing `name + ''` can cause a repl error if the result to `toString` is not a string,
  11341. // this is, this will handle objects that misbehave.
  11342. name = name + '';
  11343. if (!isString(name)) {
  11344. throw $parseMinErr('iseccst',
  11345. 'Cannot convert object to primitive value! '
  11346. + 'Expression: {0}', fullExpression);
  11347. }
  11348. return name;
  11349. }
  11350. function ensureSafeObject(obj, fullExpression) {
  11351. // nifty check if obj is Function that is fast and works across iframes and other contexts
  11352. if (obj) {
  11353. if (obj.constructor === obj) {
  11354. throw $parseMinErr('isecfn',
  11355. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11356. fullExpression);
  11357. } else if (// isWindow(obj)
  11358. obj.window === obj) {
  11359. throw $parseMinErr('isecwindow',
  11360. 'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
  11361. fullExpression);
  11362. } else if (// isElement(obj)
  11363. obj.children && (obj.nodeName || (obj.prop && obj.attr && obj.find))) {
  11364. throw $parseMinErr('isecdom',
  11365. 'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
  11366. fullExpression);
  11367. } else if (// block Object so that we can't get hold of dangerous Object.* methods
  11368. obj === Object) {
  11369. throw $parseMinErr('isecobj',
  11370. 'Referencing Object in Angular expressions is disallowed! Expression: {0}',
  11371. fullExpression);
  11372. }
  11373. }
  11374. return obj;
  11375. }
  11376. var CALL = Function.prototype.call;
  11377. var APPLY = Function.prototype.apply;
  11378. var BIND = Function.prototype.bind;
  11379. function ensureSafeFunction(obj, fullExpression) {
  11380. if (obj) {
  11381. if (obj.constructor === obj) {
  11382. throw $parseMinErr('isecfn',
  11383. 'Referencing Function in Angular expressions is disallowed! Expression: {0}',
  11384. fullExpression);
  11385. } else if (obj === CALL || obj === APPLY || obj === BIND) {
  11386. throw $parseMinErr('isecff',
  11387. 'Referencing call, apply or bind in Angular expressions is disallowed! Expression: {0}',
  11388. fullExpression);
  11389. }
  11390. }
  11391. }
  11392. function ensureSafeAssignContext(obj, fullExpression) {
  11393. if (obj) {
  11394. if (obj === (0).constructor || obj === (false).constructor || obj === ''.constructor ||
  11395. obj === {}.constructor || obj === [].constructor || obj === Function.constructor) {
  11396. throw $parseMinErr('isecaf',
  11397. 'Assigning to a constructor is disallowed! Expression: {0}', fullExpression);
  11398. }
  11399. }
  11400. }
  11401. var OPERATORS = createMap();
  11402. forEach('+ - * / % === !== == != < > <= >= && || ! = |'.split(' '), function(operator) { OPERATORS[operator] = true; });
  11403. var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
  11404. /////////////////////////////////////////
  11405. /**
  11406. * @constructor
  11407. */
  11408. var Lexer = function(options) {
  11409. this.options = options;
  11410. };
  11411. Lexer.prototype = {
  11412. constructor: Lexer,
  11413. lex: function(text) {
  11414. this.text = text;
  11415. this.index = 0;
  11416. this.tokens = [];
  11417. while (this.index < this.text.length) {
  11418. var ch = this.text.charAt(this.index);
  11419. if (ch === '"' || ch === "'") {
  11420. this.readString(ch);
  11421. } else if (this.isNumber(ch) || ch === '.' && this.isNumber(this.peek())) {
  11422. this.readNumber();
  11423. } else if (this.isIdent(ch)) {
  11424. this.readIdent();
  11425. } else if (this.is(ch, '(){}[].,;:?')) {
  11426. this.tokens.push({index: this.index, text: ch});
  11427. this.index++;
  11428. } else if (this.isWhitespace(ch)) {
  11429. this.index++;
  11430. } else {
  11431. var ch2 = ch + this.peek();
  11432. var ch3 = ch2 + this.peek(2);
  11433. var op1 = OPERATORS[ch];
  11434. var op2 = OPERATORS[ch2];
  11435. var op3 = OPERATORS[ch3];
  11436. if (op1 || op2 || op3) {
  11437. var token = op3 ? ch3 : (op2 ? ch2 : ch);
  11438. this.tokens.push({index: this.index, text: token, operator: true});
  11439. this.index += token.length;
  11440. } else {
  11441. this.throwError('Unexpected next character ', this.index, this.index + 1);
  11442. }
  11443. }
  11444. }
  11445. return this.tokens;
  11446. },
  11447. is: function(ch, chars) {
  11448. return chars.indexOf(ch) !== -1;
  11449. },
  11450. peek: function(i) {
  11451. var num = i || 1;
  11452. return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
  11453. },
  11454. isNumber: function(ch) {
  11455. return ('0' <= ch && ch <= '9') && typeof ch === "string";
  11456. },
  11457. isWhitespace: function(ch) {
  11458. // IE treats non-breaking space as \u00A0
  11459. return (ch === ' ' || ch === '\r' || ch === '\t' ||
  11460. ch === '\n' || ch === '\v' || ch === '\u00A0');
  11461. },
  11462. isIdent: function(ch) {
  11463. return ('a' <= ch && ch <= 'z' ||
  11464. 'A' <= ch && ch <= 'Z' ||
  11465. '_' === ch || ch === '$');
  11466. },
  11467. isExpOperator: function(ch) {
  11468. return (ch === '-' || ch === '+' || this.isNumber(ch));
  11469. },
  11470. throwError: function(error, start, end) {
  11471. end = end || this.index;
  11472. var colStr = (isDefined(start)
  11473. ? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
  11474. : ' ' + end);
  11475. throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
  11476. error, colStr, this.text);
  11477. },
  11478. readNumber: function() {
  11479. var number = '';
  11480. var start = this.index;
  11481. while (this.index < this.text.length) {
  11482. var ch = lowercase(this.text.charAt(this.index));
  11483. if (ch == '.' || this.isNumber(ch)) {
  11484. number += ch;
  11485. } else {
  11486. var peekCh = this.peek();
  11487. if (ch == 'e' && this.isExpOperator(peekCh)) {
  11488. number += ch;
  11489. } else if (this.isExpOperator(ch) &&
  11490. peekCh && this.isNumber(peekCh) &&
  11491. number.charAt(number.length - 1) == 'e') {
  11492. number += ch;
  11493. } else if (this.isExpOperator(ch) &&
  11494. (!peekCh || !this.isNumber(peekCh)) &&
  11495. number.charAt(number.length - 1) == 'e') {
  11496. this.throwError('Invalid exponent');
  11497. } else {
  11498. break;
  11499. }
  11500. }
  11501. this.index++;
  11502. }
  11503. this.tokens.push({
  11504. index: start,
  11505. text: number,
  11506. constant: true,
  11507. value: Number(number)
  11508. });
  11509. },
  11510. readIdent: function() {
  11511. var start = this.index;
  11512. while (this.index < this.text.length) {
  11513. var ch = this.text.charAt(this.index);
  11514. if (!(this.isIdent(ch) || this.isNumber(ch))) {
  11515. break;
  11516. }
  11517. this.index++;
  11518. }
  11519. this.tokens.push({
  11520. index: start,
  11521. text: this.text.slice(start, this.index),
  11522. identifier: true
  11523. });
  11524. },
  11525. readString: function(quote) {
  11526. var start = this.index;
  11527. this.index++;
  11528. var string = '';
  11529. var rawString = quote;
  11530. var escape = false;
  11531. while (this.index < this.text.length) {
  11532. var ch = this.text.charAt(this.index);
  11533. rawString += ch;
  11534. if (escape) {
  11535. if (ch === 'u') {
  11536. var hex = this.text.substring(this.index + 1, this.index + 5);
  11537. if (!hex.match(/[\da-f]{4}/i)) {
  11538. this.throwError('Invalid unicode escape [\\u' + hex + ']');
  11539. }
  11540. this.index += 4;
  11541. string += String.fromCharCode(parseInt(hex, 16));
  11542. } else {
  11543. var rep = ESCAPE[ch];
  11544. string = string + (rep || ch);
  11545. }
  11546. escape = false;
  11547. } else if (ch === '\\') {
  11548. escape = true;
  11549. } else if (ch === quote) {
  11550. this.index++;
  11551. this.tokens.push({
  11552. index: start,
  11553. text: rawString,
  11554. constant: true,
  11555. value: string
  11556. });
  11557. return;
  11558. } else {
  11559. string += ch;
  11560. }
  11561. this.index++;
  11562. }
  11563. this.throwError('Unterminated quote', start);
  11564. }
  11565. };
  11566. var AST = function(lexer, options) {
  11567. this.lexer = lexer;
  11568. this.options = options;
  11569. };
  11570. AST.Program = 'Program';
  11571. AST.ExpressionStatement = 'ExpressionStatement';
  11572. AST.AssignmentExpression = 'AssignmentExpression';
  11573. AST.ConditionalExpression = 'ConditionalExpression';
  11574. AST.LogicalExpression = 'LogicalExpression';
  11575. AST.BinaryExpression = 'BinaryExpression';
  11576. AST.UnaryExpression = 'UnaryExpression';
  11577. AST.CallExpression = 'CallExpression';
  11578. AST.MemberExpression = 'MemberExpression';
  11579. AST.Identifier = 'Identifier';
  11580. AST.Literal = 'Literal';
  11581. AST.ArrayExpression = 'ArrayExpression';
  11582. AST.Property = 'Property';
  11583. AST.ObjectExpression = 'ObjectExpression';
  11584. AST.ThisExpression = 'ThisExpression';
  11585. // Internal use only
  11586. AST.NGValueParameter = 'NGValueParameter';
  11587. AST.prototype = {
  11588. ast: function(text) {
  11589. this.text = text;
  11590. this.tokens = this.lexer.lex(text);
  11591. var value = this.program();
  11592. if (this.tokens.length !== 0) {
  11593. this.throwError('is an unexpected token', this.tokens[0]);
  11594. }
  11595. return value;
  11596. },
  11597. program: function() {
  11598. var body = [];
  11599. while (true) {
  11600. if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
  11601. body.push(this.expressionStatement());
  11602. if (!this.expect(';')) {
  11603. return { type: AST.Program, body: body};
  11604. }
  11605. }
  11606. },
  11607. expressionStatement: function() {
  11608. return { type: AST.ExpressionStatement, expression: this.filterChain() };
  11609. },
  11610. filterChain: function() {
  11611. var left = this.expression();
  11612. var token;
  11613. while ((token = this.expect('|'))) {
  11614. left = this.filter(left);
  11615. }
  11616. return left;
  11617. },
  11618. expression: function() {
  11619. return this.assignment();
  11620. },
  11621. assignment: function() {
  11622. var result = this.ternary();
  11623. if (this.expect('=')) {
  11624. result = { type: AST.AssignmentExpression, left: result, right: this.assignment(), operator: '='};
  11625. }
  11626. return result;
  11627. },
  11628. ternary: function() {
  11629. var test = this.logicalOR();
  11630. var alternate;
  11631. var consequent;
  11632. if (this.expect('?')) {
  11633. alternate = this.expression();
  11634. if (this.consume(':')) {
  11635. consequent = this.expression();
  11636. return { type: AST.ConditionalExpression, test: test, alternate: alternate, consequent: consequent};
  11637. }
  11638. }
  11639. return test;
  11640. },
  11641. logicalOR: function() {
  11642. var left = this.logicalAND();
  11643. while (this.expect('||')) {
  11644. left = { type: AST.LogicalExpression, operator: '||', left: left, right: this.logicalAND() };
  11645. }
  11646. return left;
  11647. },
  11648. logicalAND: function() {
  11649. var left = this.equality();
  11650. while (this.expect('&&')) {
  11651. left = { type: AST.LogicalExpression, operator: '&&', left: left, right: this.equality()};
  11652. }
  11653. return left;
  11654. },
  11655. equality: function() {
  11656. var left = this.relational();
  11657. var token;
  11658. while ((token = this.expect('==','!=','===','!=='))) {
  11659. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.relational() };
  11660. }
  11661. return left;
  11662. },
  11663. relational: function() {
  11664. var left = this.additive();
  11665. var token;
  11666. while ((token = this.expect('<', '>', '<=', '>='))) {
  11667. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.additive() };
  11668. }
  11669. return left;
  11670. },
  11671. additive: function() {
  11672. var left = this.multiplicative();
  11673. var token;
  11674. while ((token = this.expect('+','-'))) {
  11675. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.multiplicative() };
  11676. }
  11677. return left;
  11678. },
  11679. multiplicative: function() {
  11680. var left = this.unary();
  11681. var token;
  11682. while ((token = this.expect('*','/','%'))) {
  11683. left = { type: AST.BinaryExpression, operator: token.text, left: left, right: this.unary() };
  11684. }
  11685. return left;
  11686. },
  11687. unary: function() {
  11688. var token;
  11689. if ((token = this.expect('+', '-', '!'))) {
  11690. return { type: AST.UnaryExpression, operator: token.text, prefix: true, argument: this.unary() };
  11691. } else {
  11692. return this.primary();
  11693. }
  11694. },
  11695. primary: function() {
  11696. var primary;
  11697. if (this.expect('(')) {
  11698. primary = this.filterChain();
  11699. this.consume(')');
  11700. } else if (this.expect('[')) {
  11701. primary = this.arrayDeclaration();
  11702. } else if (this.expect('{')) {
  11703. primary = this.object();
  11704. } else if (this.constants.hasOwnProperty(this.peek().text)) {
  11705. primary = copy(this.constants[this.consume().text]);
  11706. } else if (this.peek().identifier) {
  11707. primary = this.identifier();
  11708. } else if (this.peek().constant) {
  11709. primary = this.constant();
  11710. } else {
  11711. this.throwError('not a primary expression', this.peek());
  11712. }
  11713. var next;
  11714. while ((next = this.expect('(', '[', '.'))) {
  11715. if (next.text === '(') {
  11716. primary = {type: AST.CallExpression, callee: primary, arguments: this.parseArguments() };
  11717. this.consume(')');
  11718. } else if (next.text === '[') {
  11719. primary = { type: AST.MemberExpression, object: primary, property: this.expression(), computed: true };
  11720. this.consume(']');
  11721. } else if (next.text === '.') {
  11722. primary = { type: AST.MemberExpression, object: primary, property: this.identifier(), computed: false };
  11723. } else {
  11724. this.throwError('IMPOSSIBLE');
  11725. }
  11726. }
  11727. return primary;
  11728. },
  11729. filter: function(baseExpression) {
  11730. var args = [baseExpression];
  11731. var result = {type: AST.CallExpression, callee: this.identifier(), arguments: args, filter: true};
  11732. while (this.expect(':')) {
  11733. args.push(this.expression());
  11734. }
  11735. return result;
  11736. },
  11737. parseArguments: function() {
  11738. var args = [];
  11739. if (this.peekToken().text !== ')') {
  11740. do {
  11741. args.push(this.expression());
  11742. } while (this.expect(','));
  11743. }
  11744. return args;
  11745. },
  11746. identifier: function() {
  11747. var token = this.consume();
  11748. if (!token.identifier) {
  11749. this.throwError('is not a valid identifier', token);
  11750. }
  11751. return { type: AST.Identifier, name: token.text };
  11752. },
  11753. constant: function() {
  11754. // TODO check that it is a constant
  11755. return { type: AST.Literal, value: this.consume().value };
  11756. },
  11757. arrayDeclaration: function() {
  11758. var elements = [];
  11759. if (this.peekToken().text !== ']') {
  11760. do {
  11761. if (this.peek(']')) {
  11762. // Support trailing commas per ES5.1.
  11763. break;
  11764. }
  11765. elements.push(this.expression());
  11766. } while (this.expect(','));
  11767. }
  11768. this.consume(']');
  11769. return { type: AST.ArrayExpression, elements: elements };
  11770. },
  11771. object: function() {
  11772. var properties = [], property;
  11773. if (this.peekToken().text !== '}') {
  11774. do {
  11775. if (this.peek('}')) {
  11776. // Support trailing commas per ES5.1.
  11777. break;
  11778. }
  11779. property = {type: AST.Property, kind: 'init'};
  11780. if (this.peek().constant) {
  11781. property.key = this.constant();
  11782. } else if (this.peek().identifier) {
  11783. property.key = this.identifier();
  11784. } else {
  11785. this.throwError("invalid key", this.peek());
  11786. }
  11787. this.consume(':');
  11788. property.value = this.expression();
  11789. properties.push(property);
  11790. } while (this.expect(','));
  11791. }
  11792. this.consume('}');
  11793. return {type: AST.ObjectExpression, properties: properties };
  11794. },
  11795. throwError: function(msg, token) {
  11796. throw $parseMinErr('syntax',
  11797. 'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
  11798. token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
  11799. },
  11800. consume: function(e1) {
  11801. if (this.tokens.length === 0) {
  11802. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11803. }
  11804. var token = this.expect(e1);
  11805. if (!token) {
  11806. this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
  11807. }
  11808. return token;
  11809. },
  11810. peekToken: function() {
  11811. if (this.tokens.length === 0) {
  11812. throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
  11813. }
  11814. return this.tokens[0];
  11815. },
  11816. peek: function(e1, e2, e3, e4) {
  11817. return this.peekAhead(0, e1, e2, e3, e4);
  11818. },
  11819. peekAhead: function(i, e1, e2, e3, e4) {
  11820. if (this.tokens.length > i) {
  11821. var token = this.tokens[i];
  11822. var t = token.text;
  11823. if (t === e1 || t === e2 || t === e3 || t === e4 ||
  11824. (!e1 && !e2 && !e3 && !e4)) {
  11825. return token;
  11826. }
  11827. }
  11828. return false;
  11829. },
  11830. expect: function(e1, e2, e3, e4) {
  11831. var token = this.peek(e1, e2, e3, e4);
  11832. if (token) {
  11833. this.tokens.shift();
  11834. return token;
  11835. }
  11836. return false;
  11837. },
  11838. /* `undefined` is not a constant, it is an identifier,
  11839. * but using it as an identifier is not supported
  11840. */
  11841. constants: {
  11842. 'true': { type: AST.Literal, value: true },
  11843. 'false': { type: AST.Literal, value: false },
  11844. 'null': { type: AST.Literal, value: null },
  11845. 'undefined': {type: AST.Literal, value: undefined },
  11846. 'this': {type: AST.ThisExpression }
  11847. }
  11848. };
  11849. function ifDefined(v, d) {
  11850. return typeof v !== 'undefined' ? v : d;
  11851. }
  11852. function plusFn(l, r) {
  11853. if (typeof l === 'undefined') return r;
  11854. if (typeof r === 'undefined') return l;
  11855. return l + r;
  11856. }
  11857. function isStateless($filter, filterName) {
  11858. var fn = $filter(filterName);
  11859. return !fn.$stateful;
  11860. }
  11861. function findConstantAndWatchExpressions(ast, $filter) {
  11862. var allConstants;
  11863. var argsToWatch;
  11864. switch (ast.type) {
  11865. case AST.Program:
  11866. allConstants = true;
  11867. forEach(ast.body, function(expr) {
  11868. findConstantAndWatchExpressions(expr.expression, $filter);
  11869. allConstants = allConstants && expr.expression.constant;
  11870. });
  11871. ast.constant = allConstants;
  11872. break;
  11873. case AST.Literal:
  11874. ast.constant = true;
  11875. ast.toWatch = [];
  11876. break;
  11877. case AST.UnaryExpression:
  11878. findConstantAndWatchExpressions(ast.argument, $filter);
  11879. ast.constant = ast.argument.constant;
  11880. ast.toWatch = ast.argument.toWatch;
  11881. break;
  11882. case AST.BinaryExpression:
  11883. findConstantAndWatchExpressions(ast.left, $filter);
  11884. findConstantAndWatchExpressions(ast.right, $filter);
  11885. ast.constant = ast.left.constant && ast.right.constant;
  11886. ast.toWatch = ast.left.toWatch.concat(ast.right.toWatch);
  11887. break;
  11888. case AST.LogicalExpression:
  11889. findConstantAndWatchExpressions(ast.left, $filter);
  11890. findConstantAndWatchExpressions(ast.right, $filter);
  11891. ast.constant = ast.left.constant && ast.right.constant;
  11892. ast.toWatch = ast.constant ? [] : [ast];
  11893. break;
  11894. case AST.ConditionalExpression:
  11895. findConstantAndWatchExpressions(ast.test, $filter);
  11896. findConstantAndWatchExpressions(ast.alternate, $filter);
  11897. findConstantAndWatchExpressions(ast.consequent, $filter);
  11898. ast.constant = ast.test.constant && ast.alternate.constant && ast.consequent.constant;
  11899. ast.toWatch = ast.constant ? [] : [ast];
  11900. break;
  11901. case AST.Identifier:
  11902. ast.constant = false;
  11903. ast.toWatch = [ast];
  11904. break;
  11905. case AST.MemberExpression:
  11906. findConstantAndWatchExpressions(ast.object, $filter);
  11907. if (ast.computed) {
  11908. findConstantAndWatchExpressions(ast.property, $filter);
  11909. }
  11910. ast.constant = ast.object.constant && (!ast.computed || ast.property.constant);
  11911. ast.toWatch = [ast];
  11912. break;
  11913. case AST.CallExpression:
  11914. allConstants = ast.filter ? isStateless($filter, ast.callee.name) : false;
  11915. argsToWatch = [];
  11916. forEach(ast.arguments, function(expr) {
  11917. findConstantAndWatchExpressions(expr, $filter);
  11918. allConstants = allConstants && expr.constant;
  11919. if (!expr.constant) {
  11920. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11921. }
  11922. });
  11923. ast.constant = allConstants;
  11924. ast.toWatch = ast.filter && isStateless($filter, ast.callee.name) ? argsToWatch : [ast];
  11925. break;
  11926. case AST.AssignmentExpression:
  11927. findConstantAndWatchExpressions(ast.left, $filter);
  11928. findConstantAndWatchExpressions(ast.right, $filter);
  11929. ast.constant = ast.left.constant && ast.right.constant;
  11930. ast.toWatch = [ast];
  11931. break;
  11932. case AST.ArrayExpression:
  11933. allConstants = true;
  11934. argsToWatch = [];
  11935. forEach(ast.elements, function(expr) {
  11936. findConstantAndWatchExpressions(expr, $filter);
  11937. allConstants = allConstants && expr.constant;
  11938. if (!expr.constant) {
  11939. argsToWatch.push.apply(argsToWatch, expr.toWatch);
  11940. }
  11941. });
  11942. ast.constant = allConstants;
  11943. ast.toWatch = argsToWatch;
  11944. break;
  11945. case AST.ObjectExpression:
  11946. allConstants = true;
  11947. argsToWatch = [];
  11948. forEach(ast.properties, function(property) {
  11949. findConstantAndWatchExpressions(property.value, $filter);
  11950. allConstants = allConstants && property.value.constant;
  11951. if (!property.value.constant) {
  11952. argsToWatch.push.apply(argsToWatch, property.value.toWatch);
  11953. }
  11954. });
  11955. ast.constant = allConstants;
  11956. ast.toWatch = argsToWatch;
  11957. break;
  11958. case AST.ThisExpression:
  11959. ast.constant = false;
  11960. ast.toWatch = [];
  11961. break;
  11962. }
  11963. }
  11964. function getInputs(body) {
  11965. if (body.length != 1) return;
  11966. var lastExpression = body[0].expression;
  11967. var candidate = lastExpression.toWatch;
  11968. if (candidate.length !== 1) return candidate;
  11969. return candidate[0] !== lastExpression ? candidate : undefined;
  11970. }
  11971. function isAssignable(ast) {
  11972. return ast.type === AST.Identifier || ast.type === AST.MemberExpression;
  11973. }
  11974. function assignableAST(ast) {
  11975. if (ast.body.length === 1 && isAssignable(ast.body[0].expression)) {
  11976. return {type: AST.AssignmentExpression, left: ast.body[0].expression, right: {type: AST.NGValueParameter}, operator: '='};
  11977. }
  11978. }
  11979. function isLiteral(ast) {
  11980. return ast.body.length === 0 ||
  11981. ast.body.length === 1 && (
  11982. ast.body[0].expression.type === AST.Literal ||
  11983. ast.body[0].expression.type === AST.ArrayExpression ||
  11984. ast.body[0].expression.type === AST.ObjectExpression);
  11985. }
  11986. function isConstant(ast) {
  11987. return ast.constant;
  11988. }
  11989. function ASTCompiler(astBuilder, $filter) {
  11990. this.astBuilder = astBuilder;
  11991. this.$filter = $filter;
  11992. }
  11993. ASTCompiler.prototype = {
  11994. compile: function(expression, expensiveChecks) {
  11995. var self = this;
  11996. var ast = this.astBuilder.ast(expression);
  11997. this.state = {
  11998. nextId: 0,
  11999. filters: {},
  12000. expensiveChecks: expensiveChecks,
  12001. fn: {vars: [], body: [], own: {}},
  12002. assign: {vars: [], body: [], own: {}},
  12003. inputs: []
  12004. };
  12005. findConstantAndWatchExpressions(ast, self.$filter);
  12006. var extra = '';
  12007. var assignable;
  12008. this.stage = 'assign';
  12009. if ((assignable = assignableAST(ast))) {
  12010. this.state.computing = 'assign';
  12011. var result = this.nextId();
  12012. this.recurse(assignable, result);
  12013. this.return_(result);
  12014. extra = 'fn.assign=' + this.generateFunction('assign', 's,v,l');
  12015. }
  12016. var toWatch = getInputs(ast.body);
  12017. self.stage = 'inputs';
  12018. forEach(toWatch, function(watch, key) {
  12019. var fnKey = 'fn' + key;
  12020. self.state[fnKey] = {vars: [], body: [], own: {}};
  12021. self.state.computing = fnKey;
  12022. var intoId = self.nextId();
  12023. self.recurse(watch, intoId);
  12024. self.return_(intoId);
  12025. self.state.inputs.push(fnKey);
  12026. watch.watchId = key;
  12027. });
  12028. this.state.computing = 'fn';
  12029. this.stage = 'main';
  12030. this.recurse(ast);
  12031. var fnString =
  12032. // The build and minification steps remove the string "use strict" from the code, but this is done using a regex.
  12033. // This is a workaround for this until we do a better job at only removing the prefix only when we should.
  12034. '"' + this.USE + ' ' + this.STRICT + '";\n' +
  12035. this.filterPrefix() +
  12036. 'var fn=' + this.generateFunction('fn', 's,l,a,i') +
  12037. extra +
  12038. this.watchFns() +
  12039. 'return fn;';
  12040. /* jshint -W054 */
  12041. var fn = (new Function('$filter',
  12042. 'ensureSafeMemberName',
  12043. 'ensureSafeObject',
  12044. 'ensureSafeFunction',
  12045. 'getStringValue',
  12046. 'ensureSafeAssignContext',
  12047. 'ifDefined',
  12048. 'plus',
  12049. 'text',
  12050. fnString))(
  12051. this.$filter,
  12052. ensureSafeMemberName,
  12053. ensureSafeObject,
  12054. ensureSafeFunction,
  12055. getStringValue,
  12056. ensureSafeAssignContext,
  12057. ifDefined,
  12058. plusFn,
  12059. expression);
  12060. /* jshint +W054 */
  12061. this.state = this.stage = undefined;
  12062. fn.literal = isLiteral(ast);
  12063. fn.constant = isConstant(ast);
  12064. return fn;
  12065. },
  12066. USE: 'use',
  12067. STRICT: 'strict',
  12068. watchFns: function() {
  12069. var result = [];
  12070. var fns = this.state.inputs;
  12071. var self = this;
  12072. forEach(fns, function(name) {
  12073. result.push('var ' + name + '=' + self.generateFunction(name, 's'));
  12074. });
  12075. if (fns.length) {
  12076. result.push('fn.inputs=[' + fns.join(',') + '];');
  12077. }
  12078. return result.join('');
  12079. },
  12080. generateFunction: function(name, params) {
  12081. return 'function(' + params + '){' +
  12082. this.varsPrefix(name) +
  12083. this.body(name) +
  12084. '};';
  12085. },
  12086. filterPrefix: function() {
  12087. var parts = [];
  12088. var self = this;
  12089. forEach(this.state.filters, function(id, filter) {
  12090. parts.push(id + '=$filter(' + self.escape(filter) + ')');
  12091. });
  12092. if (parts.length) return 'var ' + parts.join(',') + ';';
  12093. return '';
  12094. },
  12095. varsPrefix: function(section) {
  12096. return this.state[section].vars.length ? 'var ' + this.state[section].vars.join(',') + ';' : '';
  12097. },
  12098. body: function(section) {
  12099. return this.state[section].body.join('');
  12100. },
  12101. recurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12102. var left, right, self = this, args, expression;
  12103. recursionFn = recursionFn || noop;
  12104. if (!skipWatchIdCheck && isDefined(ast.watchId)) {
  12105. intoId = intoId || this.nextId();
  12106. this.if_('i',
  12107. this.lazyAssign(intoId, this.computedMember('i', ast.watchId)),
  12108. this.lazyRecurse(ast, intoId, nameId, recursionFn, create, true)
  12109. );
  12110. return;
  12111. }
  12112. switch (ast.type) {
  12113. case AST.Program:
  12114. forEach(ast.body, function(expression, pos) {
  12115. self.recurse(expression.expression, undefined, undefined, function(expr) { right = expr; });
  12116. if (pos !== ast.body.length - 1) {
  12117. self.current().body.push(right, ';');
  12118. } else {
  12119. self.return_(right);
  12120. }
  12121. });
  12122. break;
  12123. case AST.Literal:
  12124. expression = this.escape(ast.value);
  12125. this.assign(intoId, expression);
  12126. recursionFn(expression);
  12127. break;
  12128. case AST.UnaryExpression:
  12129. this.recurse(ast.argument, undefined, undefined, function(expr) { right = expr; });
  12130. expression = ast.operator + '(' + this.ifDefined(right, 0) + ')';
  12131. this.assign(intoId, expression);
  12132. recursionFn(expression);
  12133. break;
  12134. case AST.BinaryExpression:
  12135. this.recurse(ast.left, undefined, undefined, function(expr) { left = expr; });
  12136. this.recurse(ast.right, undefined, undefined, function(expr) { right = expr; });
  12137. if (ast.operator === '+') {
  12138. expression = this.plus(left, right);
  12139. } else if (ast.operator === '-') {
  12140. expression = this.ifDefined(left, 0) + ast.operator + this.ifDefined(right, 0);
  12141. } else {
  12142. expression = '(' + left + ')' + ast.operator + '(' + right + ')';
  12143. }
  12144. this.assign(intoId, expression);
  12145. recursionFn(expression);
  12146. break;
  12147. case AST.LogicalExpression:
  12148. intoId = intoId || this.nextId();
  12149. self.recurse(ast.left, intoId);
  12150. self.if_(ast.operator === '&&' ? intoId : self.not(intoId), self.lazyRecurse(ast.right, intoId));
  12151. recursionFn(intoId);
  12152. break;
  12153. case AST.ConditionalExpression:
  12154. intoId = intoId || this.nextId();
  12155. self.recurse(ast.test, intoId);
  12156. self.if_(intoId, self.lazyRecurse(ast.alternate, intoId), self.lazyRecurse(ast.consequent, intoId));
  12157. recursionFn(intoId);
  12158. break;
  12159. case AST.Identifier:
  12160. intoId = intoId || this.nextId();
  12161. if (nameId) {
  12162. nameId.context = self.stage === 'inputs' ? 's' : this.assign(this.nextId(), this.getHasOwnProperty('l', ast.name) + '?l:s');
  12163. nameId.computed = false;
  12164. nameId.name = ast.name;
  12165. }
  12166. ensureSafeMemberName(ast.name);
  12167. self.if_(self.stage === 'inputs' || self.not(self.getHasOwnProperty('l', ast.name)),
  12168. function() {
  12169. self.if_(self.stage === 'inputs' || 's', function() {
  12170. if (create && create !== 1) {
  12171. self.if_(
  12172. self.not(self.nonComputedMember('s', ast.name)),
  12173. self.lazyAssign(self.nonComputedMember('s', ast.name), '{}'));
  12174. }
  12175. self.assign(intoId, self.nonComputedMember('s', ast.name));
  12176. });
  12177. }, intoId && self.lazyAssign(intoId, self.nonComputedMember('l', ast.name))
  12178. );
  12179. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.name)) {
  12180. self.addEnsureSafeObject(intoId);
  12181. }
  12182. recursionFn(intoId);
  12183. break;
  12184. case AST.MemberExpression:
  12185. left = nameId && (nameId.context = this.nextId()) || this.nextId();
  12186. intoId = intoId || this.nextId();
  12187. self.recurse(ast.object, left, undefined, function() {
  12188. self.if_(self.notNull(left), function() {
  12189. if (ast.computed) {
  12190. right = self.nextId();
  12191. self.recurse(ast.property, right);
  12192. self.getStringValue(right);
  12193. self.addEnsureSafeMemberName(right);
  12194. if (create && create !== 1) {
  12195. self.if_(self.not(self.computedMember(left, right)), self.lazyAssign(self.computedMember(left, right), '{}'));
  12196. }
  12197. expression = self.ensureSafeObject(self.computedMember(left, right));
  12198. self.assign(intoId, expression);
  12199. if (nameId) {
  12200. nameId.computed = true;
  12201. nameId.name = right;
  12202. }
  12203. } else {
  12204. ensureSafeMemberName(ast.property.name);
  12205. if (create && create !== 1) {
  12206. self.if_(self.not(self.nonComputedMember(left, ast.property.name)), self.lazyAssign(self.nonComputedMember(left, ast.property.name), '{}'));
  12207. }
  12208. expression = self.nonComputedMember(left, ast.property.name);
  12209. if (self.state.expensiveChecks || isPossiblyDangerousMemberName(ast.property.name)) {
  12210. expression = self.ensureSafeObject(expression);
  12211. }
  12212. self.assign(intoId, expression);
  12213. if (nameId) {
  12214. nameId.computed = false;
  12215. nameId.name = ast.property.name;
  12216. }
  12217. }
  12218. }, function() {
  12219. self.assign(intoId, 'undefined');
  12220. });
  12221. recursionFn(intoId);
  12222. }, !!create);
  12223. break;
  12224. case AST.CallExpression:
  12225. intoId = intoId || this.nextId();
  12226. if (ast.filter) {
  12227. right = self.filter(ast.callee.name);
  12228. args = [];
  12229. forEach(ast.arguments, function(expr) {
  12230. var argument = self.nextId();
  12231. self.recurse(expr, argument);
  12232. args.push(argument);
  12233. });
  12234. expression = right + '(' + args.join(',') + ')';
  12235. self.assign(intoId, expression);
  12236. recursionFn(intoId);
  12237. } else {
  12238. right = self.nextId();
  12239. left = {};
  12240. args = [];
  12241. self.recurse(ast.callee, right, left, function() {
  12242. self.if_(self.notNull(right), function() {
  12243. self.addEnsureSafeFunction(right);
  12244. forEach(ast.arguments, function(expr) {
  12245. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12246. args.push(self.ensureSafeObject(argument));
  12247. });
  12248. });
  12249. if (left.name) {
  12250. if (!self.state.expensiveChecks) {
  12251. self.addEnsureSafeObject(left.context);
  12252. }
  12253. expression = self.member(left.context, left.name, left.computed) + '(' + args.join(',') + ')';
  12254. } else {
  12255. expression = right + '(' + args.join(',') + ')';
  12256. }
  12257. expression = self.ensureSafeObject(expression);
  12258. self.assign(intoId, expression);
  12259. }, function() {
  12260. self.assign(intoId, 'undefined');
  12261. });
  12262. recursionFn(intoId);
  12263. });
  12264. }
  12265. break;
  12266. case AST.AssignmentExpression:
  12267. right = this.nextId();
  12268. left = {};
  12269. if (!isAssignable(ast.left)) {
  12270. throw $parseMinErr('lval', 'Trying to assing a value to a non l-value');
  12271. }
  12272. this.recurse(ast.left, undefined, left, function() {
  12273. self.if_(self.notNull(left.context), function() {
  12274. self.recurse(ast.right, right);
  12275. self.addEnsureSafeObject(self.member(left.context, left.name, left.computed));
  12276. self.addEnsureSafeAssignContext(left.context);
  12277. expression = self.member(left.context, left.name, left.computed) + ast.operator + right;
  12278. self.assign(intoId, expression);
  12279. recursionFn(intoId || expression);
  12280. });
  12281. }, 1);
  12282. break;
  12283. case AST.ArrayExpression:
  12284. args = [];
  12285. forEach(ast.elements, function(expr) {
  12286. self.recurse(expr, self.nextId(), undefined, function(argument) {
  12287. args.push(argument);
  12288. });
  12289. });
  12290. expression = '[' + args.join(',') + ']';
  12291. this.assign(intoId, expression);
  12292. recursionFn(expression);
  12293. break;
  12294. case AST.ObjectExpression:
  12295. args = [];
  12296. forEach(ast.properties, function(property) {
  12297. self.recurse(property.value, self.nextId(), undefined, function(expr) {
  12298. args.push(self.escape(
  12299. property.key.type === AST.Identifier ? property.key.name :
  12300. ('' + property.key.value)) +
  12301. ':' + expr);
  12302. });
  12303. });
  12304. expression = '{' + args.join(',') + '}';
  12305. this.assign(intoId, expression);
  12306. recursionFn(expression);
  12307. break;
  12308. case AST.ThisExpression:
  12309. this.assign(intoId, 's');
  12310. recursionFn('s');
  12311. break;
  12312. case AST.NGValueParameter:
  12313. this.assign(intoId, 'v');
  12314. recursionFn('v');
  12315. break;
  12316. }
  12317. },
  12318. getHasOwnProperty: function(element, property) {
  12319. var key = element + '.' + property;
  12320. var own = this.current().own;
  12321. if (!own.hasOwnProperty(key)) {
  12322. own[key] = this.nextId(false, element + '&&(' + this.escape(property) + ' in ' + element + ')');
  12323. }
  12324. return own[key];
  12325. },
  12326. assign: function(id, value) {
  12327. if (!id) return;
  12328. this.current().body.push(id, '=', value, ';');
  12329. return id;
  12330. },
  12331. filter: function(filterName) {
  12332. if (!this.state.filters.hasOwnProperty(filterName)) {
  12333. this.state.filters[filterName] = this.nextId(true);
  12334. }
  12335. return this.state.filters[filterName];
  12336. },
  12337. ifDefined: function(id, defaultValue) {
  12338. return 'ifDefined(' + id + ',' + this.escape(defaultValue) + ')';
  12339. },
  12340. plus: function(left, right) {
  12341. return 'plus(' + left + ',' + right + ')';
  12342. },
  12343. return_: function(id) {
  12344. this.current().body.push('return ', id, ';');
  12345. },
  12346. if_: function(test, alternate, consequent) {
  12347. if (test === true) {
  12348. alternate();
  12349. } else {
  12350. var body = this.current().body;
  12351. body.push('if(', test, '){');
  12352. alternate();
  12353. body.push('}');
  12354. if (consequent) {
  12355. body.push('else{');
  12356. consequent();
  12357. body.push('}');
  12358. }
  12359. }
  12360. },
  12361. not: function(expression) {
  12362. return '!(' + expression + ')';
  12363. },
  12364. notNull: function(expression) {
  12365. return expression + '!=null';
  12366. },
  12367. nonComputedMember: function(left, right) {
  12368. return left + '.' + right;
  12369. },
  12370. computedMember: function(left, right) {
  12371. return left + '[' + right + ']';
  12372. },
  12373. member: function(left, right, computed) {
  12374. if (computed) return this.computedMember(left, right);
  12375. return this.nonComputedMember(left, right);
  12376. },
  12377. addEnsureSafeObject: function(item) {
  12378. this.current().body.push(this.ensureSafeObject(item), ';');
  12379. },
  12380. addEnsureSafeMemberName: function(item) {
  12381. this.current().body.push(this.ensureSafeMemberName(item), ';');
  12382. },
  12383. addEnsureSafeFunction: function(item) {
  12384. this.current().body.push(this.ensureSafeFunction(item), ';');
  12385. },
  12386. addEnsureSafeAssignContext: function(item) {
  12387. this.current().body.push(this.ensureSafeAssignContext(item), ';');
  12388. },
  12389. ensureSafeObject: function(item) {
  12390. return 'ensureSafeObject(' + item + ',text)';
  12391. },
  12392. ensureSafeMemberName: function(item) {
  12393. return 'ensureSafeMemberName(' + item + ',text)';
  12394. },
  12395. ensureSafeFunction: function(item) {
  12396. return 'ensureSafeFunction(' + item + ',text)';
  12397. },
  12398. getStringValue: function(item) {
  12399. this.assign(item, 'getStringValue(' + item + ',text)');
  12400. },
  12401. ensureSafeAssignContext: function(item) {
  12402. return 'ensureSafeAssignContext(' + item + ',text)';
  12403. },
  12404. lazyRecurse: function(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck) {
  12405. var self = this;
  12406. return function() {
  12407. self.recurse(ast, intoId, nameId, recursionFn, create, skipWatchIdCheck);
  12408. };
  12409. },
  12410. lazyAssign: function(id, value) {
  12411. var self = this;
  12412. return function() {
  12413. self.assign(id, value);
  12414. };
  12415. },
  12416. stringEscapeRegex: /[^ a-zA-Z0-9]/g,
  12417. stringEscapeFn: function(c) {
  12418. return '\\u' + ('0000' + c.charCodeAt(0).toString(16)).slice(-4);
  12419. },
  12420. escape: function(value) {
  12421. if (isString(value)) return "'" + value.replace(this.stringEscapeRegex, this.stringEscapeFn) + "'";
  12422. if (isNumber(value)) return value.toString();
  12423. if (value === true) return 'true';
  12424. if (value === false) return 'false';
  12425. if (value === null) return 'null';
  12426. if (typeof value === 'undefined') return 'undefined';
  12427. throw $parseMinErr('esc', 'IMPOSSIBLE');
  12428. },
  12429. nextId: function(skip, init) {
  12430. var id = 'v' + (this.state.nextId++);
  12431. if (!skip) {
  12432. this.current().vars.push(id + (init ? '=' + init : ''));
  12433. }
  12434. return id;
  12435. },
  12436. current: function() {
  12437. return this.state[this.state.computing];
  12438. }
  12439. };
  12440. function ASTInterpreter(astBuilder, $filter) {
  12441. this.astBuilder = astBuilder;
  12442. this.$filter = $filter;
  12443. }
  12444. ASTInterpreter.prototype = {
  12445. compile: function(expression, expensiveChecks) {
  12446. var self = this;
  12447. var ast = this.astBuilder.ast(expression);
  12448. this.expression = expression;
  12449. this.expensiveChecks = expensiveChecks;
  12450. findConstantAndWatchExpressions(ast, self.$filter);
  12451. var assignable;
  12452. var assign;
  12453. if ((assignable = assignableAST(ast))) {
  12454. assign = this.recurse(assignable);
  12455. }
  12456. var toWatch = getInputs(ast.body);
  12457. var inputs;
  12458. if (toWatch) {
  12459. inputs = [];
  12460. forEach(toWatch, function(watch, key) {
  12461. var input = self.recurse(watch);
  12462. watch.input = input;
  12463. inputs.push(input);
  12464. watch.watchId = key;
  12465. });
  12466. }
  12467. var expressions = [];
  12468. forEach(ast.body, function(expression) {
  12469. expressions.push(self.recurse(expression.expression));
  12470. });
  12471. var fn = ast.body.length === 0 ? function() {} :
  12472. ast.body.length === 1 ? expressions[0] :
  12473. function(scope, locals) {
  12474. var lastValue;
  12475. forEach(expressions, function(exp) {
  12476. lastValue = exp(scope, locals);
  12477. });
  12478. return lastValue;
  12479. };
  12480. if (assign) {
  12481. fn.assign = function(scope, value, locals) {
  12482. return assign(scope, locals, value);
  12483. };
  12484. }
  12485. if (inputs) {
  12486. fn.inputs = inputs;
  12487. }
  12488. fn.literal = isLiteral(ast);
  12489. fn.constant = isConstant(ast);
  12490. return fn;
  12491. },
  12492. recurse: function(ast, context, create) {
  12493. var left, right, self = this, args, expression;
  12494. if (ast.input) {
  12495. return this.inputs(ast.input, ast.watchId);
  12496. }
  12497. switch (ast.type) {
  12498. case AST.Literal:
  12499. return this.value(ast.value, context);
  12500. case AST.UnaryExpression:
  12501. right = this.recurse(ast.argument);
  12502. return this['unary' + ast.operator](right, context);
  12503. case AST.BinaryExpression:
  12504. left = this.recurse(ast.left);
  12505. right = this.recurse(ast.right);
  12506. return this['binary' + ast.operator](left, right, context);
  12507. case AST.LogicalExpression:
  12508. left = this.recurse(ast.left);
  12509. right = this.recurse(ast.right);
  12510. return this['binary' + ast.operator](left, right, context);
  12511. case AST.ConditionalExpression:
  12512. return this['ternary?:'](
  12513. this.recurse(ast.test),
  12514. this.recurse(ast.alternate),
  12515. this.recurse(ast.consequent),
  12516. context
  12517. );
  12518. case AST.Identifier:
  12519. ensureSafeMemberName(ast.name, self.expression);
  12520. return self.identifier(ast.name,
  12521. self.expensiveChecks || isPossiblyDangerousMemberName(ast.name),
  12522. context, create, self.expression);
  12523. case AST.MemberExpression:
  12524. left = this.recurse(ast.object, false, !!create);
  12525. if (!ast.computed) {
  12526. ensureSafeMemberName(ast.property.name, self.expression);
  12527. right = ast.property.name;
  12528. }
  12529. if (ast.computed) right = this.recurse(ast.property);
  12530. return ast.computed ?
  12531. this.computedMember(left, right, context, create, self.expression) :
  12532. this.nonComputedMember(left, right, self.expensiveChecks, context, create, self.expression);
  12533. case AST.CallExpression:
  12534. args = [];
  12535. forEach(ast.arguments, function(expr) {
  12536. args.push(self.recurse(expr));
  12537. });
  12538. if (ast.filter) right = this.$filter(ast.callee.name);
  12539. if (!ast.filter) right = this.recurse(ast.callee, true);
  12540. return ast.filter ?
  12541. function(scope, locals, assign, inputs) {
  12542. var values = [];
  12543. for (var i = 0; i < args.length; ++i) {
  12544. values.push(args[i](scope, locals, assign, inputs));
  12545. }
  12546. var value = right.apply(undefined, values, inputs);
  12547. return context ? {context: undefined, name: undefined, value: value} : value;
  12548. } :
  12549. function(scope, locals, assign, inputs) {
  12550. var rhs = right(scope, locals, assign, inputs);
  12551. var value;
  12552. if (rhs.value != null) {
  12553. ensureSafeObject(rhs.context, self.expression);
  12554. ensureSafeFunction(rhs.value, self.expression);
  12555. var values = [];
  12556. for (var i = 0; i < args.length; ++i) {
  12557. values.push(ensureSafeObject(args[i](scope, locals, assign, inputs), self.expression));
  12558. }
  12559. value = ensureSafeObject(rhs.value.apply(rhs.context, values), self.expression);
  12560. }
  12561. return context ? {value: value} : value;
  12562. };
  12563. case AST.AssignmentExpression:
  12564. left = this.recurse(ast.left, true, 1);
  12565. right = this.recurse(ast.right);
  12566. return function(scope, locals, assign, inputs) {
  12567. var lhs = left(scope, locals, assign, inputs);
  12568. var rhs = right(scope, locals, assign, inputs);
  12569. ensureSafeObject(lhs.value, self.expression);
  12570. ensureSafeAssignContext(lhs.context);
  12571. lhs.context[lhs.name] = rhs;
  12572. return context ? {value: rhs} : rhs;
  12573. };
  12574. case AST.ArrayExpression:
  12575. args = [];
  12576. forEach(ast.elements, function(expr) {
  12577. args.push(self.recurse(expr));
  12578. });
  12579. return function(scope, locals, assign, inputs) {
  12580. var value = [];
  12581. for (var i = 0; i < args.length; ++i) {
  12582. value.push(args[i](scope, locals, assign, inputs));
  12583. }
  12584. return context ? {value: value} : value;
  12585. };
  12586. case AST.ObjectExpression:
  12587. args = [];
  12588. forEach(ast.properties, function(property) {
  12589. args.push({key: property.key.type === AST.Identifier ?
  12590. property.key.name :
  12591. ('' + property.key.value),
  12592. value: self.recurse(property.value)
  12593. });
  12594. });
  12595. return function(scope, locals, assign, inputs) {
  12596. var value = {};
  12597. for (var i = 0; i < args.length; ++i) {
  12598. value[args[i].key] = args[i].value(scope, locals, assign, inputs);
  12599. }
  12600. return context ? {value: value} : value;
  12601. };
  12602. case AST.ThisExpression:
  12603. return function(scope) {
  12604. return context ? {value: scope} : scope;
  12605. };
  12606. case AST.NGValueParameter:
  12607. return function(scope, locals, assign, inputs) {
  12608. return context ? {value: assign} : assign;
  12609. };
  12610. }
  12611. },
  12612. 'unary+': function(argument, context) {
  12613. return function(scope, locals, assign, inputs) {
  12614. var arg = argument(scope, locals, assign, inputs);
  12615. if (isDefined(arg)) {
  12616. arg = +arg;
  12617. } else {
  12618. arg = 0;
  12619. }
  12620. return context ? {value: arg} : arg;
  12621. };
  12622. },
  12623. 'unary-': function(argument, context) {
  12624. return function(scope, locals, assign, inputs) {
  12625. var arg = argument(scope, locals, assign, inputs);
  12626. if (isDefined(arg)) {
  12627. arg = -arg;
  12628. } else {
  12629. arg = 0;
  12630. }
  12631. return context ? {value: arg} : arg;
  12632. };
  12633. },
  12634. 'unary!': function(argument, context) {
  12635. return function(scope, locals, assign, inputs) {
  12636. var arg = !argument(scope, locals, assign, inputs);
  12637. return context ? {value: arg} : arg;
  12638. };
  12639. },
  12640. 'binary+': function(left, right, context) {
  12641. return function(scope, locals, assign, inputs) {
  12642. var lhs = left(scope, locals, assign, inputs);
  12643. var rhs = right(scope, locals, assign, inputs);
  12644. var arg = plusFn(lhs, rhs);
  12645. return context ? {value: arg} : arg;
  12646. };
  12647. },
  12648. 'binary-': function(left, right, context) {
  12649. return function(scope, locals, assign, inputs) {
  12650. var lhs = left(scope, locals, assign, inputs);
  12651. var rhs = right(scope, locals, assign, inputs);
  12652. var arg = (isDefined(lhs) ? lhs : 0) - (isDefined(rhs) ? rhs : 0);
  12653. return context ? {value: arg} : arg;
  12654. };
  12655. },
  12656. 'binary*': function(left, right, context) {
  12657. return function(scope, locals, assign, inputs) {
  12658. var arg = left(scope, locals, assign, inputs) * right(scope, locals, assign, inputs);
  12659. return context ? {value: arg} : arg;
  12660. };
  12661. },
  12662. 'binary/': function(left, right, context) {
  12663. return function(scope, locals, assign, inputs) {
  12664. var arg = left(scope, locals, assign, inputs) / right(scope, locals, assign, inputs);
  12665. return context ? {value: arg} : arg;
  12666. };
  12667. },
  12668. 'binary%': function(left, right, context) {
  12669. return function(scope, locals, assign, inputs) {
  12670. var arg = left(scope, locals, assign, inputs) % right(scope, locals, assign, inputs);
  12671. return context ? {value: arg} : arg;
  12672. };
  12673. },
  12674. 'binary===': function(left, right, context) {
  12675. return function(scope, locals, assign, inputs) {
  12676. var arg = left(scope, locals, assign, inputs) === right(scope, locals, assign, inputs);
  12677. return context ? {value: arg} : arg;
  12678. };
  12679. },
  12680. 'binary!==': function(left, right, context) {
  12681. return function(scope, locals, assign, inputs) {
  12682. var arg = left(scope, locals, assign, inputs) !== right(scope, locals, assign, inputs);
  12683. return context ? {value: arg} : arg;
  12684. };
  12685. },
  12686. 'binary==': function(left, right, context) {
  12687. return function(scope, locals, assign, inputs) {
  12688. var arg = left(scope, locals, assign, inputs) == right(scope, locals, assign, inputs);
  12689. return context ? {value: arg} : arg;
  12690. };
  12691. },
  12692. 'binary!=': function(left, right, context) {
  12693. return function(scope, locals, assign, inputs) {
  12694. var arg = left(scope, locals, assign, inputs) != right(scope, locals, assign, inputs);
  12695. return context ? {value: arg} : arg;
  12696. };
  12697. },
  12698. 'binary<': function(left, right, context) {
  12699. return function(scope, locals, assign, inputs) {
  12700. var arg = left(scope, locals, assign, inputs) < right(scope, locals, assign, inputs);
  12701. return context ? {value: arg} : arg;
  12702. };
  12703. },
  12704. 'binary>': function(left, right, context) {
  12705. return function(scope, locals, assign, inputs) {
  12706. var arg = left(scope, locals, assign, inputs) > right(scope, locals, assign, inputs);
  12707. return context ? {value: arg} : arg;
  12708. };
  12709. },
  12710. 'binary<=': function(left, right, context) {
  12711. return function(scope, locals, assign, inputs) {
  12712. var arg = left(scope, locals, assign, inputs) <= right(scope, locals, assign, inputs);
  12713. return context ? {value: arg} : arg;
  12714. };
  12715. },
  12716. 'binary>=': function(left, right, context) {
  12717. return function(scope, locals, assign, inputs) {
  12718. var arg = left(scope, locals, assign, inputs) >= right(scope, locals, assign, inputs);
  12719. return context ? {value: arg} : arg;
  12720. };
  12721. },
  12722. 'binary&&': function(left, right, context) {
  12723. return function(scope, locals, assign, inputs) {
  12724. var arg = left(scope, locals, assign, inputs) && right(scope, locals, assign, inputs);
  12725. return context ? {value: arg} : arg;
  12726. };
  12727. },
  12728. 'binary||': function(left, right, context) {
  12729. return function(scope, locals, assign, inputs) {
  12730. var arg = left(scope, locals, assign, inputs) || right(scope, locals, assign, inputs);
  12731. return context ? {value: arg} : arg;
  12732. };
  12733. },
  12734. 'ternary?:': function(test, alternate, consequent, context) {
  12735. return function(scope, locals, assign, inputs) {
  12736. var arg = test(scope, locals, assign, inputs) ? alternate(scope, locals, assign, inputs) : consequent(scope, locals, assign, inputs);
  12737. return context ? {value: arg} : arg;
  12738. };
  12739. },
  12740. value: function(value, context) {
  12741. return function() { return context ? {context: undefined, name: undefined, value: value} : value; };
  12742. },
  12743. identifier: function(name, expensiveChecks, context, create, expression) {
  12744. return function(scope, locals, assign, inputs) {
  12745. var base = locals && (name in locals) ? locals : scope;
  12746. if (create && create !== 1 && base && !(base[name])) {
  12747. base[name] = {};
  12748. }
  12749. var value = base ? base[name] : undefined;
  12750. if (expensiveChecks) {
  12751. ensureSafeObject(value, expression);
  12752. }
  12753. if (context) {
  12754. return {context: base, name: name, value: value};
  12755. } else {
  12756. return value;
  12757. }
  12758. };
  12759. },
  12760. computedMember: function(left, right, context, create, expression) {
  12761. return function(scope, locals, assign, inputs) {
  12762. var lhs = left(scope, locals, assign, inputs);
  12763. var rhs;
  12764. var value;
  12765. if (lhs != null) {
  12766. rhs = right(scope, locals, assign, inputs);
  12767. rhs = getStringValue(rhs);
  12768. ensureSafeMemberName(rhs, expression);
  12769. if (create && create !== 1 && lhs && !(lhs[rhs])) {
  12770. lhs[rhs] = {};
  12771. }
  12772. value = lhs[rhs];
  12773. ensureSafeObject(value, expression);
  12774. }
  12775. if (context) {
  12776. return {context: lhs, name: rhs, value: value};
  12777. } else {
  12778. return value;
  12779. }
  12780. };
  12781. },
  12782. nonComputedMember: function(left, right, expensiveChecks, context, create, expression) {
  12783. return function(scope, locals, assign, inputs) {
  12784. var lhs = left(scope, locals, assign, inputs);
  12785. if (create && create !== 1 && lhs && !(lhs[right])) {
  12786. lhs[right] = {};
  12787. }
  12788. var value = lhs != null ? lhs[right] : undefined;
  12789. if (expensiveChecks || isPossiblyDangerousMemberName(right)) {
  12790. ensureSafeObject(value, expression);
  12791. }
  12792. if (context) {
  12793. return {context: lhs, name: right, value: value};
  12794. } else {
  12795. return value;
  12796. }
  12797. };
  12798. },
  12799. inputs: function(input, watchId) {
  12800. return function(scope, value, locals, inputs) {
  12801. if (inputs) return inputs[watchId];
  12802. return input(scope, value, locals);
  12803. };
  12804. }
  12805. };
  12806. /**
  12807. * @constructor
  12808. */
  12809. var Parser = function(lexer, $filter, options) {
  12810. this.lexer = lexer;
  12811. this.$filter = $filter;
  12812. this.options = options;
  12813. this.ast = new AST(this.lexer);
  12814. this.astCompiler = options.csp ? new ASTInterpreter(this.ast, $filter) :
  12815. new ASTCompiler(this.ast, $filter);
  12816. };
  12817. Parser.prototype = {
  12818. constructor: Parser,
  12819. parse: function(text) {
  12820. return this.astCompiler.compile(text, this.options.expensiveChecks);
  12821. }
  12822. };
  12823. var getterFnCacheDefault = createMap();
  12824. var getterFnCacheExpensive = createMap();
  12825. function isPossiblyDangerousMemberName(name) {
  12826. return name == 'constructor';
  12827. }
  12828. var objectValueOf = Object.prototype.valueOf;
  12829. function getValueOf(value) {
  12830. return isFunction(value.valueOf) ? value.valueOf() : objectValueOf.call(value);
  12831. }
  12832. ///////////////////////////////////
  12833. /**
  12834. * @ngdoc service
  12835. * @name $parse
  12836. * @kind function
  12837. *
  12838. * @description
  12839. *
  12840. * Converts Angular {@link guide/expression expression} into a function.
  12841. *
  12842. * ```js
  12843. * var getter = $parse('user.name');
  12844. * var setter = getter.assign;
  12845. * var context = {user:{name:'angular'}};
  12846. * var locals = {user:{name:'local'}};
  12847. *
  12848. * expect(getter(context)).toEqual('angular');
  12849. * setter(context, 'newValue');
  12850. * expect(context.user.name).toEqual('newValue');
  12851. * expect(getter(context, locals)).toEqual('local');
  12852. * ```
  12853. *
  12854. *
  12855. * @param {string} expression String expression to compile.
  12856. * @returns {function(context, locals)} a function which represents the compiled expression:
  12857. *
  12858. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  12859. * are evaluated against (typically a scope object).
  12860. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  12861. * `context`.
  12862. *
  12863. * The returned function also has the following properties:
  12864. * * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
  12865. * literal.
  12866. * * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
  12867. * constant literals.
  12868. * * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
  12869. * set to a function to change its value on the given context.
  12870. *
  12871. */
  12872. /**
  12873. * @ngdoc provider
  12874. * @name $parseProvider
  12875. *
  12876. * @description
  12877. * `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
  12878. * service.
  12879. */
  12880. function $ParseProvider() {
  12881. var cacheDefault = createMap();
  12882. var cacheExpensive = createMap();
  12883. this.$get = ['$filter', function($filter) {
  12884. var noUnsafeEval = csp().noUnsafeEval;
  12885. var $parseOptions = {
  12886. csp: noUnsafeEval,
  12887. expensiveChecks: false
  12888. },
  12889. $parseOptionsExpensive = {
  12890. csp: noUnsafeEval,
  12891. expensiveChecks: true
  12892. };
  12893. return function $parse(exp, interceptorFn, expensiveChecks) {
  12894. var parsedExpression, oneTime, cacheKey;
  12895. switch (typeof exp) {
  12896. case 'string':
  12897. exp = exp.trim();
  12898. cacheKey = exp;
  12899. var cache = (expensiveChecks ? cacheExpensive : cacheDefault);
  12900. parsedExpression = cache[cacheKey];
  12901. if (!parsedExpression) {
  12902. if (exp.charAt(0) === ':' && exp.charAt(1) === ':') {
  12903. oneTime = true;
  12904. exp = exp.substring(2);
  12905. }
  12906. var parseOptions = expensiveChecks ? $parseOptionsExpensive : $parseOptions;
  12907. var lexer = new Lexer(parseOptions);
  12908. var parser = new Parser(lexer, $filter, parseOptions);
  12909. parsedExpression = parser.parse(exp);
  12910. if (parsedExpression.constant) {
  12911. parsedExpression.$$watchDelegate = constantWatchDelegate;
  12912. } else if (oneTime) {
  12913. parsedExpression.$$watchDelegate = parsedExpression.literal ?
  12914. oneTimeLiteralWatchDelegate : oneTimeWatchDelegate;
  12915. } else if (parsedExpression.inputs) {
  12916. parsedExpression.$$watchDelegate = inputsWatchDelegate;
  12917. }
  12918. cache[cacheKey] = parsedExpression;
  12919. }
  12920. return addInterceptor(parsedExpression, interceptorFn);
  12921. case 'function':
  12922. return addInterceptor(exp, interceptorFn);
  12923. default:
  12924. return noop;
  12925. }
  12926. };
  12927. function expressionInputDirtyCheck(newValue, oldValueOfValue) {
  12928. if (newValue == null || oldValueOfValue == null) { // null/undefined
  12929. return newValue === oldValueOfValue;
  12930. }
  12931. if (typeof newValue === 'object') {
  12932. // attempt to convert the value to a primitive type
  12933. // TODO(docs): add a note to docs that by implementing valueOf even objects and arrays can
  12934. // be cheaply dirty-checked
  12935. newValue = getValueOf(newValue);
  12936. if (typeof newValue === 'object') {
  12937. // objects/arrays are not supported - deep-watching them would be too expensive
  12938. return false;
  12939. }
  12940. // fall-through to the primitive equality check
  12941. }
  12942. //Primitive or NaN
  12943. return newValue === oldValueOfValue || (newValue !== newValue && oldValueOfValue !== oldValueOfValue);
  12944. }
  12945. function inputsWatchDelegate(scope, listener, objectEquality, parsedExpression, prettyPrintExpression) {
  12946. var inputExpressions = parsedExpression.inputs;
  12947. var lastResult;
  12948. if (inputExpressions.length === 1) {
  12949. var oldInputValueOf = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12950. inputExpressions = inputExpressions[0];
  12951. return scope.$watch(function expressionInputWatch(scope) {
  12952. var newInputValue = inputExpressions(scope);
  12953. if (!expressionInputDirtyCheck(newInputValue, oldInputValueOf)) {
  12954. lastResult = parsedExpression(scope, undefined, undefined, [newInputValue]);
  12955. oldInputValueOf = newInputValue && getValueOf(newInputValue);
  12956. }
  12957. return lastResult;
  12958. }, listener, objectEquality, prettyPrintExpression);
  12959. }
  12960. var oldInputValueOfValues = [];
  12961. var oldInputValues = [];
  12962. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12963. oldInputValueOfValues[i] = expressionInputDirtyCheck; // init to something unique so that equals check fails
  12964. oldInputValues[i] = null;
  12965. }
  12966. return scope.$watch(function expressionInputsWatch(scope) {
  12967. var changed = false;
  12968. for (var i = 0, ii = inputExpressions.length; i < ii; i++) {
  12969. var newInputValue = inputExpressions[i](scope);
  12970. if (changed || (changed = !expressionInputDirtyCheck(newInputValue, oldInputValueOfValues[i]))) {
  12971. oldInputValues[i] = newInputValue;
  12972. oldInputValueOfValues[i] = newInputValue && getValueOf(newInputValue);
  12973. }
  12974. }
  12975. if (changed) {
  12976. lastResult = parsedExpression(scope, undefined, undefined, oldInputValues);
  12977. }
  12978. return lastResult;
  12979. }, listener, objectEquality, prettyPrintExpression);
  12980. }
  12981. function oneTimeWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  12982. var unwatch, lastValue;
  12983. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  12984. return parsedExpression(scope);
  12985. }, function oneTimeListener(value, old, scope) {
  12986. lastValue = value;
  12987. if (isFunction(listener)) {
  12988. listener.apply(this, arguments);
  12989. }
  12990. if (isDefined(value)) {
  12991. scope.$$postDigest(function() {
  12992. if (isDefined(lastValue)) {
  12993. unwatch();
  12994. }
  12995. });
  12996. }
  12997. }, objectEquality);
  12998. }
  12999. function oneTimeLiteralWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13000. var unwatch, lastValue;
  13001. return unwatch = scope.$watch(function oneTimeWatch(scope) {
  13002. return parsedExpression(scope);
  13003. }, function oneTimeListener(value, old, scope) {
  13004. lastValue = value;
  13005. if (isFunction(listener)) {
  13006. listener.call(this, value, old, scope);
  13007. }
  13008. if (isAllDefined(value)) {
  13009. scope.$$postDigest(function() {
  13010. if (isAllDefined(lastValue)) unwatch();
  13011. });
  13012. }
  13013. }, objectEquality);
  13014. function isAllDefined(value) {
  13015. var allDefined = true;
  13016. forEach(value, function(val) {
  13017. if (!isDefined(val)) allDefined = false;
  13018. });
  13019. return allDefined;
  13020. }
  13021. }
  13022. function constantWatchDelegate(scope, listener, objectEquality, parsedExpression) {
  13023. var unwatch;
  13024. return unwatch = scope.$watch(function constantWatch(scope) {
  13025. return parsedExpression(scope);
  13026. }, function constantListener(value, old, scope) {
  13027. if (isFunction(listener)) {
  13028. listener.apply(this, arguments);
  13029. }
  13030. unwatch();
  13031. }, objectEquality);
  13032. }
  13033. function addInterceptor(parsedExpression, interceptorFn) {
  13034. if (!interceptorFn) return parsedExpression;
  13035. var watchDelegate = parsedExpression.$$watchDelegate;
  13036. var useInputs = false;
  13037. var regularWatch =
  13038. watchDelegate !== oneTimeLiteralWatchDelegate &&
  13039. watchDelegate !== oneTimeWatchDelegate;
  13040. var fn = regularWatch ? function regularInterceptedExpression(scope, locals, assign, inputs) {
  13041. var value = useInputs && inputs ? inputs[0] : parsedExpression(scope, locals, assign, inputs);
  13042. return interceptorFn(value, scope, locals);
  13043. } : function oneTimeInterceptedExpression(scope, locals, assign, inputs) {
  13044. var value = parsedExpression(scope, locals, assign, inputs);
  13045. var result = interceptorFn(value, scope, locals);
  13046. // we only return the interceptor's result if the
  13047. // initial value is defined (for bind-once)
  13048. return isDefined(value) ? result : value;
  13049. };
  13050. // Propagate $$watchDelegates other then inputsWatchDelegate
  13051. if (parsedExpression.$$watchDelegate &&
  13052. parsedExpression.$$watchDelegate !== inputsWatchDelegate) {
  13053. fn.$$watchDelegate = parsedExpression.$$watchDelegate;
  13054. } else if (!interceptorFn.$stateful) {
  13055. // If there is an interceptor, but no watchDelegate then treat the interceptor like
  13056. // we treat filters - it is assumed to be a pure function unless flagged with $stateful
  13057. fn.$$watchDelegate = inputsWatchDelegate;
  13058. useInputs = !parsedExpression.inputs;
  13059. fn.inputs = parsedExpression.inputs ? parsedExpression.inputs : [parsedExpression];
  13060. }
  13061. return fn;
  13062. }
  13063. }];
  13064. }
  13065. /**
  13066. * @ngdoc service
  13067. * @name $q
  13068. * @requires $rootScope
  13069. *
  13070. * @description
  13071. * A service that helps you run functions asynchronously, and use their return values (or exceptions)
  13072. * when they are done processing.
  13073. *
  13074. * This is an implementation of promises/deferred objects inspired by
  13075. * [Kris Kowal's Q](https://github.com/kriskowal/q).
  13076. *
  13077. * $q can be used in two fashions --- one which is more similar to Kris Kowal's Q or jQuery's Deferred
  13078. * implementations, and the other which resembles ES6 promises to some degree.
  13079. *
  13080. * # $q constructor
  13081. *
  13082. * The streamlined ES6 style promise is essentially just using $q as a constructor which takes a `resolver`
  13083. * function as the first argument. This is similar to the native Promise implementation from ES6 Harmony,
  13084. * see [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise).
  13085. *
  13086. * While the constructor-style use is supported, not all of the supporting methods from ES6 Harmony promises are
  13087. * available yet.
  13088. *
  13089. * It can be used like so:
  13090. *
  13091. * ```js
  13092. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13093. * // are available in the current lexical scope (they could have been injected or passed in).
  13094. *
  13095. * function asyncGreet(name) {
  13096. * // perform some asynchronous operation, resolve or reject the promise when appropriate.
  13097. * return $q(function(resolve, reject) {
  13098. * setTimeout(function() {
  13099. * if (okToGreet(name)) {
  13100. * resolve('Hello, ' + name + '!');
  13101. * } else {
  13102. * reject('Greeting ' + name + ' is not allowed.');
  13103. * }
  13104. * }, 1000);
  13105. * });
  13106. * }
  13107. *
  13108. * var promise = asyncGreet('Robin Hood');
  13109. * promise.then(function(greeting) {
  13110. * alert('Success: ' + greeting);
  13111. * }, function(reason) {
  13112. * alert('Failed: ' + reason);
  13113. * });
  13114. * ```
  13115. *
  13116. * Note: progress/notify callbacks are not currently supported via the ES6-style interface.
  13117. *
  13118. * Note: unlike ES6 behaviour, an exception thrown in the constructor function will NOT implicitly reject the promise.
  13119. *
  13120. * However, the more traditional CommonJS-style usage is still available, and documented below.
  13121. *
  13122. * [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
  13123. * interface for interacting with an object that represents the result of an action that is
  13124. * performed asynchronously, and may or may not be finished at any given point in time.
  13125. *
  13126. * From the perspective of dealing with error handling, deferred and promise APIs are to
  13127. * asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
  13128. *
  13129. * ```js
  13130. * // for the purpose of this example let's assume that variables `$q` and `okToGreet`
  13131. * // are available in the current lexical scope (they could have been injected or passed in).
  13132. *
  13133. * function asyncGreet(name) {
  13134. * var deferred = $q.defer();
  13135. *
  13136. * setTimeout(function() {
  13137. * deferred.notify('About to greet ' + name + '.');
  13138. *
  13139. * if (okToGreet(name)) {
  13140. * deferred.resolve('Hello, ' + name + '!');
  13141. * } else {
  13142. * deferred.reject('Greeting ' + name + ' is not allowed.');
  13143. * }
  13144. * }, 1000);
  13145. *
  13146. * return deferred.promise;
  13147. * }
  13148. *
  13149. * var promise = asyncGreet('Robin Hood');
  13150. * promise.then(function(greeting) {
  13151. * alert('Success: ' + greeting);
  13152. * }, function(reason) {
  13153. * alert('Failed: ' + reason);
  13154. * }, function(update) {
  13155. * alert('Got notification: ' + update);
  13156. * });
  13157. * ```
  13158. *
  13159. * At first it might not be obvious why this extra complexity is worth the trouble. The payoff
  13160. * comes in the way of guarantees that promise and deferred APIs make, see
  13161. * https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
  13162. *
  13163. * Additionally the promise api allows for composition that is very hard to do with the
  13164. * traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
  13165. * For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
  13166. * section on serial or parallel joining of promises.
  13167. *
  13168. * # The Deferred API
  13169. *
  13170. * A new instance of deferred is constructed by calling `$q.defer()`.
  13171. *
  13172. * The purpose of the deferred object is to expose the associated Promise instance as well as APIs
  13173. * that can be used for signaling the successful or unsuccessful completion, as well as the status
  13174. * of the task.
  13175. *
  13176. * **Methods**
  13177. *
  13178. * - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
  13179. * constructed via `$q.reject`, the promise will be rejected instead.
  13180. * - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
  13181. * resolving it with a rejection constructed via `$q.reject`.
  13182. * - `notify(value)` - provides updates on the status of the promise's execution. This may be called
  13183. * multiple times before the promise is either resolved or rejected.
  13184. *
  13185. * **Properties**
  13186. *
  13187. * - promise – `{Promise}` – promise object associated with this deferred.
  13188. *
  13189. *
  13190. * # The Promise API
  13191. *
  13192. * A new promise instance is created when a deferred instance is created and can be retrieved by
  13193. * calling `deferred.promise`.
  13194. *
  13195. * The purpose of the promise object is to allow for interested parties to get access to the result
  13196. * of the deferred task when it completes.
  13197. *
  13198. * **Methods**
  13199. *
  13200. * - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
  13201. * will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
  13202. * as soon as the result is available. The callbacks are called with a single argument: the result
  13203. * or rejection reason. Additionally, the notify callback may be called zero or more times to
  13204. * provide a progress indication, before the promise is resolved or rejected.
  13205. *
  13206. * This method *returns a new promise* which is resolved or rejected via the return value of the
  13207. * `successCallback`, `errorCallback` (unless that value is a promise, in which case it is resolved
  13208. * with the value which is resolved in that promise using
  13209. * [promise chaining](http://www.html5rocks.com/en/tutorials/es6/promises/#toc-promises-queues)).
  13210. * It also notifies via the return value of the `notifyCallback` method. The promise cannot be
  13211. * resolved or rejected from the notifyCallback method.
  13212. *
  13213. * - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
  13214. *
  13215. * - `finally(callback, notifyCallback)` – allows you to observe either the fulfillment or rejection of a promise,
  13216. * but to do so without modifying the final value. This is useful to release resources or do some
  13217. * clean-up that needs to be done whether the promise was rejected or resolved. See the [full
  13218. * specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
  13219. * more information.
  13220. *
  13221. * # Chaining promises
  13222. *
  13223. * Because calling the `then` method of a promise returns a new derived promise, it is easily
  13224. * possible to create a chain of promises:
  13225. *
  13226. * ```js
  13227. * promiseB = promiseA.then(function(result) {
  13228. * return result + 1;
  13229. * });
  13230. *
  13231. * // promiseB will be resolved immediately after promiseA is resolved and its value
  13232. * // will be the result of promiseA incremented by 1
  13233. * ```
  13234. *
  13235. * It is possible to create chains of any length and since a promise can be resolved with another
  13236. * promise (which will defer its resolution further), it is possible to pause/defer resolution of
  13237. * the promises at any point in the chain. This makes it possible to implement powerful APIs like
  13238. * $http's response interceptors.
  13239. *
  13240. *
  13241. * # Differences between Kris Kowal's Q and $q
  13242. *
  13243. * There are two main differences:
  13244. *
  13245. * - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
  13246. * mechanism in angular, which means faster propagation of resolution or rejection into your
  13247. * models and avoiding unnecessary browser repaints, which would result in flickering UI.
  13248. * - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
  13249. * all the important functionality needed for common async tasks.
  13250. *
  13251. * # Testing
  13252. *
  13253. * ```js
  13254. * it('should simulate promise', inject(function($q, $rootScope) {
  13255. * var deferred = $q.defer();
  13256. * var promise = deferred.promise;
  13257. * var resolvedValue;
  13258. *
  13259. * promise.then(function(value) { resolvedValue = value; });
  13260. * expect(resolvedValue).toBeUndefined();
  13261. *
  13262. * // Simulate resolving of promise
  13263. * deferred.resolve(123);
  13264. * // Note that the 'then' function does not get called synchronously.
  13265. * // This is because we want the promise API to always be async, whether or not
  13266. * // it got called synchronously or asynchronously.
  13267. * expect(resolvedValue).toBeUndefined();
  13268. *
  13269. * // Propagate promise resolution to 'then' functions using $apply().
  13270. * $rootScope.$apply();
  13271. * expect(resolvedValue).toEqual(123);
  13272. * }));
  13273. * ```
  13274. *
  13275. * @param {function(function, function)} resolver Function which is responsible for resolving or
  13276. * rejecting the newly created promise. The first parameter is a function which resolves the
  13277. * promise, the second parameter is a function which rejects the promise.
  13278. *
  13279. * @returns {Promise} The newly created promise.
  13280. */
  13281. function $QProvider() {
  13282. this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
  13283. return qFactory(function(callback) {
  13284. $rootScope.$evalAsync(callback);
  13285. }, $exceptionHandler);
  13286. }];
  13287. }
  13288. function $$QProvider() {
  13289. this.$get = ['$browser', '$exceptionHandler', function($browser, $exceptionHandler) {
  13290. return qFactory(function(callback) {
  13291. $browser.defer(callback);
  13292. }, $exceptionHandler);
  13293. }];
  13294. }
  13295. /**
  13296. * Constructs a promise manager.
  13297. *
  13298. * @param {function(function)} nextTick Function for executing functions in the next turn.
  13299. * @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
  13300. * debugging purposes.
  13301. * @returns {object} Promise manager.
  13302. */
  13303. function qFactory(nextTick, exceptionHandler) {
  13304. var $qMinErr = minErr('$q', TypeError);
  13305. function callOnce(self, resolveFn, rejectFn) {
  13306. var called = false;
  13307. function wrap(fn) {
  13308. return function(value) {
  13309. if (called) return;
  13310. called = true;
  13311. fn.call(self, value);
  13312. };
  13313. }
  13314. return [wrap(resolveFn), wrap(rejectFn)];
  13315. }
  13316. /**
  13317. * @ngdoc method
  13318. * @name ng.$q#defer
  13319. * @kind function
  13320. *
  13321. * @description
  13322. * Creates a `Deferred` object which represents a task which will finish in the future.
  13323. *
  13324. * @returns {Deferred} Returns a new instance of deferred.
  13325. */
  13326. var defer = function() {
  13327. return new Deferred();
  13328. };
  13329. function Promise() {
  13330. this.$$state = { status: 0 };
  13331. }
  13332. extend(Promise.prototype, {
  13333. then: function(onFulfilled, onRejected, progressBack) {
  13334. if (isUndefined(onFulfilled) && isUndefined(onRejected) && isUndefined(progressBack)) {
  13335. return this;
  13336. }
  13337. var result = new Deferred();
  13338. this.$$state.pending = this.$$state.pending || [];
  13339. this.$$state.pending.push([result, onFulfilled, onRejected, progressBack]);
  13340. if (this.$$state.status > 0) scheduleProcessQueue(this.$$state);
  13341. return result.promise;
  13342. },
  13343. "catch": function(callback) {
  13344. return this.then(null, callback);
  13345. },
  13346. "finally": function(callback, progressBack) {
  13347. return this.then(function(value) {
  13348. return handleCallback(value, true, callback);
  13349. }, function(error) {
  13350. return handleCallback(error, false, callback);
  13351. }, progressBack);
  13352. }
  13353. });
  13354. //Faster, more basic than angular.bind http://jsperf.com/angular-bind-vs-custom-vs-native
  13355. function simpleBind(context, fn) {
  13356. return function(value) {
  13357. fn.call(context, value);
  13358. };
  13359. }
  13360. function processQueue(state) {
  13361. var fn, deferred, pending;
  13362. pending = state.pending;
  13363. state.processScheduled = false;
  13364. state.pending = undefined;
  13365. for (var i = 0, ii = pending.length; i < ii; ++i) {
  13366. deferred = pending[i][0];
  13367. fn = pending[i][state.status];
  13368. try {
  13369. if (isFunction(fn)) {
  13370. deferred.resolve(fn(state.value));
  13371. } else if (state.status === 1) {
  13372. deferred.resolve(state.value);
  13373. } else {
  13374. deferred.reject(state.value);
  13375. }
  13376. } catch (e) {
  13377. deferred.reject(e);
  13378. exceptionHandler(e);
  13379. }
  13380. }
  13381. }
  13382. function scheduleProcessQueue(state) {
  13383. if (state.processScheduled || !state.pending) return;
  13384. state.processScheduled = true;
  13385. nextTick(function() { processQueue(state); });
  13386. }
  13387. function Deferred() {
  13388. this.promise = new Promise();
  13389. //Necessary to support unbound execution :/
  13390. this.resolve = simpleBind(this, this.resolve);
  13391. this.reject = simpleBind(this, this.reject);
  13392. this.notify = simpleBind(this, this.notify);
  13393. }
  13394. extend(Deferred.prototype, {
  13395. resolve: function(val) {
  13396. if (this.promise.$$state.status) return;
  13397. if (val === this.promise) {
  13398. this.$$reject($qMinErr(
  13399. 'qcycle',
  13400. "Expected promise to be resolved with value other than itself '{0}'",
  13401. val));
  13402. } else {
  13403. this.$$resolve(val);
  13404. }
  13405. },
  13406. $$resolve: function(val) {
  13407. var then, fns;
  13408. fns = callOnce(this, this.$$resolve, this.$$reject);
  13409. try {
  13410. if ((isObject(val) || isFunction(val))) then = val && val.then;
  13411. if (isFunction(then)) {
  13412. this.promise.$$state.status = -1;
  13413. then.call(val, fns[0], fns[1], this.notify);
  13414. } else {
  13415. this.promise.$$state.value = val;
  13416. this.promise.$$state.status = 1;
  13417. scheduleProcessQueue(this.promise.$$state);
  13418. }
  13419. } catch (e) {
  13420. fns[1](e);
  13421. exceptionHandler(e);
  13422. }
  13423. },
  13424. reject: function(reason) {
  13425. if (this.promise.$$state.status) return;
  13426. this.$$reject(reason);
  13427. },
  13428. $$reject: function(reason) {
  13429. this.promise.$$state.value = reason;
  13430. this.promise.$$state.status = 2;
  13431. scheduleProcessQueue(this.promise.$$state);
  13432. },
  13433. notify: function(progress) {
  13434. var callbacks = this.promise.$$state.pending;
  13435. if ((this.promise.$$state.status <= 0) && callbacks && callbacks.length) {
  13436. nextTick(function() {
  13437. var callback, result;
  13438. for (var i = 0, ii = callbacks.length; i < ii; i++) {
  13439. result = callbacks[i][0];
  13440. callback = callbacks[i][3];
  13441. try {
  13442. result.notify(isFunction(callback) ? callback(progress) : progress);
  13443. } catch (e) {
  13444. exceptionHandler(e);
  13445. }
  13446. }
  13447. });
  13448. }
  13449. }
  13450. });
  13451. /**
  13452. * @ngdoc method
  13453. * @name $q#reject
  13454. * @kind function
  13455. *
  13456. * @description
  13457. * Creates a promise that is resolved as rejected with the specified `reason`. This api should be
  13458. * used to forward rejection in a chain of promises. If you are dealing with the last promise in
  13459. * a promise chain, you don't need to worry about it.
  13460. *
  13461. * When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
  13462. * `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
  13463. * a promise error callback and you want to forward the error to the promise derived from the
  13464. * current promise, you have to "rethrow" the error by returning a rejection constructed via
  13465. * `reject`.
  13466. *
  13467. * ```js
  13468. * promiseB = promiseA.then(function(result) {
  13469. * // success: do something and resolve promiseB
  13470. * // with the old or a new result
  13471. * return result;
  13472. * }, function(reason) {
  13473. * // error: handle the error if possible and
  13474. * // resolve promiseB with newPromiseOrValue,
  13475. * // otherwise forward the rejection to promiseB
  13476. * if (canHandle(reason)) {
  13477. * // handle the error and recover
  13478. * return newPromiseOrValue;
  13479. * }
  13480. * return $q.reject(reason);
  13481. * });
  13482. * ```
  13483. *
  13484. * @param {*} reason Constant, message, exception or an object representing the rejection reason.
  13485. * @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
  13486. */
  13487. var reject = function(reason) {
  13488. var result = new Deferred();
  13489. result.reject(reason);
  13490. return result.promise;
  13491. };
  13492. var makePromise = function makePromise(value, resolved) {
  13493. var result = new Deferred();
  13494. if (resolved) {
  13495. result.resolve(value);
  13496. } else {
  13497. result.reject(value);
  13498. }
  13499. return result.promise;
  13500. };
  13501. var handleCallback = function handleCallback(value, isResolved, callback) {
  13502. var callbackOutput = null;
  13503. try {
  13504. if (isFunction(callback)) callbackOutput = callback();
  13505. } catch (e) {
  13506. return makePromise(e, false);
  13507. }
  13508. if (isPromiseLike(callbackOutput)) {
  13509. return callbackOutput.then(function() {
  13510. return makePromise(value, isResolved);
  13511. }, function(error) {
  13512. return makePromise(error, false);
  13513. });
  13514. } else {
  13515. return makePromise(value, isResolved);
  13516. }
  13517. };
  13518. /**
  13519. * @ngdoc method
  13520. * @name $q#when
  13521. * @kind function
  13522. *
  13523. * @description
  13524. * Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
  13525. * This is useful when you are dealing with an object that might or might not be a promise, or if
  13526. * the promise comes from a source that can't be trusted.
  13527. *
  13528. * @param {*} value Value or a promise
  13529. * @param {Function=} successCallback
  13530. * @param {Function=} errorCallback
  13531. * @param {Function=} progressCallback
  13532. * @returns {Promise} Returns a promise of the passed value or promise
  13533. */
  13534. var when = function(value, callback, errback, progressBack) {
  13535. var result = new Deferred();
  13536. result.resolve(value);
  13537. return result.promise.then(callback, errback, progressBack);
  13538. };
  13539. /**
  13540. * @ngdoc method
  13541. * @name $q#resolve
  13542. * @kind function
  13543. *
  13544. * @description
  13545. * Alias of {@link ng.$q#when when} to maintain naming consistency with ES6.
  13546. *
  13547. * @param {*} value Value or a promise
  13548. * @param {Function=} successCallback
  13549. * @param {Function=} errorCallback
  13550. * @param {Function=} progressCallback
  13551. * @returns {Promise} Returns a promise of the passed value or promise
  13552. */
  13553. var resolve = when;
  13554. /**
  13555. * @ngdoc method
  13556. * @name $q#all
  13557. * @kind function
  13558. *
  13559. * @description
  13560. * Combines multiple promises into a single promise that is resolved when all of the input
  13561. * promises are resolved.
  13562. *
  13563. * @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
  13564. * @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
  13565. * each value corresponding to the promise at the same index/key in the `promises` array/hash.
  13566. * If any of the promises is resolved with a rejection, this resulting promise will be rejected
  13567. * with the same rejection value.
  13568. */
  13569. function all(promises) {
  13570. var deferred = new Deferred(),
  13571. counter = 0,
  13572. results = isArray(promises) ? [] : {};
  13573. forEach(promises, function(promise, key) {
  13574. counter++;
  13575. when(promise).then(function(value) {
  13576. if (results.hasOwnProperty(key)) return;
  13577. results[key] = value;
  13578. if (!(--counter)) deferred.resolve(results);
  13579. }, function(reason) {
  13580. if (results.hasOwnProperty(key)) return;
  13581. deferred.reject(reason);
  13582. });
  13583. });
  13584. if (counter === 0) {
  13585. deferred.resolve(results);
  13586. }
  13587. return deferred.promise;
  13588. }
  13589. var $Q = function Q(resolver) {
  13590. if (!isFunction(resolver)) {
  13591. throw $qMinErr('norslvr', "Expected resolverFn, got '{0}'", resolver);
  13592. }
  13593. if (!(this instanceof Q)) {
  13594. // More useful when $Q is the Promise itself.
  13595. return new Q(resolver);
  13596. }
  13597. var deferred = new Deferred();
  13598. function resolveFn(value) {
  13599. deferred.resolve(value);
  13600. }
  13601. function rejectFn(reason) {
  13602. deferred.reject(reason);
  13603. }
  13604. resolver(resolveFn, rejectFn);
  13605. return deferred.promise;
  13606. };
  13607. $Q.defer = defer;
  13608. $Q.reject = reject;
  13609. $Q.when = when;
  13610. $Q.resolve = resolve;
  13611. $Q.all = all;
  13612. return $Q;
  13613. }
  13614. function $$RAFProvider() { //rAF
  13615. this.$get = ['$window', '$timeout', function($window, $timeout) {
  13616. var requestAnimationFrame = $window.requestAnimationFrame ||
  13617. $window.webkitRequestAnimationFrame;
  13618. var cancelAnimationFrame = $window.cancelAnimationFrame ||
  13619. $window.webkitCancelAnimationFrame ||
  13620. $window.webkitCancelRequestAnimationFrame;
  13621. var rafSupported = !!requestAnimationFrame;
  13622. var raf = rafSupported
  13623. ? function(fn) {
  13624. var id = requestAnimationFrame(fn);
  13625. return function() {
  13626. cancelAnimationFrame(id);
  13627. };
  13628. }
  13629. : function(fn) {
  13630. var timer = $timeout(fn, 16.66, false); // 1000 / 60 = 16.666
  13631. return function() {
  13632. $timeout.cancel(timer);
  13633. };
  13634. };
  13635. raf.supported = rafSupported;
  13636. return raf;
  13637. }];
  13638. }
  13639. /**
  13640. * DESIGN NOTES
  13641. *
  13642. * The design decisions behind the scope are heavily favored for speed and memory consumption.
  13643. *
  13644. * The typical use of scope is to watch the expressions, which most of the time return the same
  13645. * value as last time so we optimize the operation.
  13646. *
  13647. * Closures construction is expensive in terms of speed as well as memory:
  13648. * - No closures, instead use prototypical inheritance for API
  13649. * - Internal state needs to be stored on scope directly, which means that private state is
  13650. * exposed as $$____ properties
  13651. *
  13652. * Loop operations are optimized by using while(count--) { ... }
  13653. * - This means that in order to keep the same order of execution as addition we have to add
  13654. * items to the array at the beginning (unshift) instead of at the end (push)
  13655. *
  13656. * Child scopes are created and removed often
  13657. * - Using an array would be slow since inserts in the middle are expensive; so we use linked lists
  13658. *
  13659. * There are fewer watches than observers. This is why you don't want the observer to be implemented
  13660. * in the same way as watch. Watch requires return of the initialization function which is expensive
  13661. * to construct.
  13662. */
  13663. /**
  13664. * @ngdoc provider
  13665. * @name $rootScopeProvider
  13666. * @description
  13667. *
  13668. * Provider for the $rootScope service.
  13669. */
  13670. /**
  13671. * @ngdoc method
  13672. * @name $rootScopeProvider#digestTtl
  13673. * @description
  13674. *
  13675. * Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
  13676. * assuming that the model is unstable.
  13677. *
  13678. * The current default is 10 iterations.
  13679. *
  13680. * In complex applications it's possible that the dependencies between `$watch`s will result in
  13681. * several digest iterations. However if an application needs more than the default 10 digest
  13682. * iterations for its model to stabilize then you should investigate what is causing the model to
  13683. * continuously change during the digest.
  13684. *
  13685. * Increasing the TTL could have performance implications, so you should not change it without
  13686. * proper justification.
  13687. *
  13688. * @param {number} limit The number of digest iterations.
  13689. */
  13690. /**
  13691. * @ngdoc service
  13692. * @name $rootScope
  13693. * @description
  13694. *
  13695. * Every application has a single root {@link ng.$rootScope.Scope scope}.
  13696. * All other scopes are descendant scopes of the root scope. Scopes provide separation
  13697. * between the model and the view, via a mechanism for watching the model for changes.
  13698. * They also provide event emission/broadcast and subscription facility. See the
  13699. * {@link guide/scope developer guide on scopes}.
  13700. */
  13701. function $RootScopeProvider() {
  13702. var TTL = 10;
  13703. var $rootScopeMinErr = minErr('$rootScope');
  13704. var lastDirtyWatch = null;
  13705. var applyAsyncId = null;
  13706. this.digestTtl = function(value) {
  13707. if (arguments.length) {
  13708. TTL = value;
  13709. }
  13710. return TTL;
  13711. };
  13712. function createChildScopeClass(parent) {
  13713. function ChildScope() {
  13714. this.$$watchers = this.$$nextSibling =
  13715. this.$$childHead = this.$$childTail = null;
  13716. this.$$listeners = {};
  13717. this.$$listenerCount = {};
  13718. this.$$watchersCount = 0;
  13719. this.$id = nextUid();
  13720. this.$$ChildScope = null;
  13721. }
  13722. ChildScope.prototype = parent;
  13723. return ChildScope;
  13724. }
  13725. this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
  13726. function($injector, $exceptionHandler, $parse, $browser) {
  13727. function destroyChildScope($event) {
  13728. $event.currentScope.$$destroyed = true;
  13729. }
  13730. function cleanUpScope($scope) {
  13731. if (msie === 9) {
  13732. // There is a memory leak in IE9 if all child scopes are not disconnected
  13733. // completely when a scope is destroyed. So this code will recurse up through
  13734. // all this scopes children
  13735. //
  13736. // See issue https://github.com/angular/angular.js/issues/10706
  13737. $scope.$$childHead && cleanUpScope($scope.$$childHead);
  13738. $scope.$$nextSibling && cleanUpScope($scope.$$nextSibling);
  13739. }
  13740. // The code below works around IE9 and V8's memory leaks
  13741. //
  13742. // See:
  13743. // - https://code.google.com/p/v8/issues/detail?id=2073#c26
  13744. // - https://github.com/angular/angular.js/issues/6794#issuecomment-38648909
  13745. // - https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
  13746. $scope.$parent = $scope.$$nextSibling = $scope.$$prevSibling = $scope.$$childHead =
  13747. $scope.$$childTail = $scope.$root = $scope.$$watchers = null;
  13748. }
  13749. /**
  13750. * @ngdoc type
  13751. * @name $rootScope.Scope
  13752. *
  13753. * @description
  13754. * A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
  13755. * {@link auto.$injector $injector}. Child scopes are created using the
  13756. * {@link ng.$rootScope.Scope#$new $new()} method. (Most scopes are created automatically when
  13757. * compiled HTML template is executed.) See also the {@link guide/scope Scopes guide} for
  13758. * an in-depth introduction and usage examples.
  13759. *
  13760. *
  13761. * # Inheritance
  13762. * A scope can inherit from a parent scope, as in this example:
  13763. * ```js
  13764. var parent = $rootScope;
  13765. var child = parent.$new();
  13766. parent.salutation = "Hello";
  13767. expect(child.salutation).toEqual('Hello');
  13768. child.salutation = "Welcome";
  13769. expect(child.salutation).toEqual('Welcome');
  13770. expect(parent.salutation).toEqual('Hello');
  13771. * ```
  13772. *
  13773. * When interacting with `Scope` in tests, additional helper methods are available on the
  13774. * instances of `Scope` type. See {@link ngMock.$rootScope.Scope ngMock Scope} for additional
  13775. * details.
  13776. *
  13777. *
  13778. * @param {Object.<string, function()>=} providers Map of service factory which need to be
  13779. * provided for the current scope. Defaults to {@link ng}.
  13780. * @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
  13781. * append/override services provided by `providers`. This is handy
  13782. * when unit-testing and having the need to override a default
  13783. * service.
  13784. * @returns {Object} Newly created scope.
  13785. *
  13786. */
  13787. function Scope() {
  13788. this.$id = nextUid();
  13789. this.$$phase = this.$parent = this.$$watchers =
  13790. this.$$nextSibling = this.$$prevSibling =
  13791. this.$$childHead = this.$$childTail = null;
  13792. this.$root = this;
  13793. this.$$destroyed = false;
  13794. this.$$listeners = {};
  13795. this.$$listenerCount = {};
  13796. this.$$watchersCount = 0;
  13797. this.$$isolateBindings = null;
  13798. }
  13799. /**
  13800. * @ngdoc property
  13801. * @name $rootScope.Scope#$id
  13802. *
  13803. * @description
  13804. * Unique scope ID (monotonically increasing) useful for debugging.
  13805. */
  13806. /**
  13807. * @ngdoc property
  13808. * @name $rootScope.Scope#$parent
  13809. *
  13810. * @description
  13811. * Reference to the parent scope.
  13812. */
  13813. /**
  13814. * @ngdoc property
  13815. * @name $rootScope.Scope#$root
  13816. *
  13817. * @description
  13818. * Reference to the root scope.
  13819. */
  13820. Scope.prototype = {
  13821. constructor: Scope,
  13822. /**
  13823. * @ngdoc method
  13824. * @name $rootScope.Scope#$new
  13825. * @kind function
  13826. *
  13827. * @description
  13828. * Creates a new child {@link ng.$rootScope.Scope scope}.
  13829. *
  13830. * The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} event.
  13831. * The scope can be removed from the scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
  13832. *
  13833. * {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
  13834. * desired for the scope and its child scopes to be permanently detached from the parent and
  13835. * thus stop participating in model change detection and listener notification by invoking.
  13836. *
  13837. * @param {boolean} isolate If true, then the scope does not prototypically inherit from the
  13838. * parent scope. The scope is isolated, as it can not see parent scope properties.
  13839. * When creating widgets, it is useful for the widget to not accidentally read parent
  13840. * state.
  13841. *
  13842. * @param {Scope} [parent=this] The {@link ng.$rootScope.Scope `Scope`} that will be the `$parent`
  13843. * of the newly created scope. Defaults to `this` scope if not provided.
  13844. * This is used when creating a transclude scope to correctly place it
  13845. * in the scope hierarchy while maintaining the correct prototypical
  13846. * inheritance.
  13847. *
  13848. * @returns {Object} The newly created child scope.
  13849. *
  13850. */
  13851. $new: function(isolate, parent) {
  13852. var child;
  13853. parent = parent || this;
  13854. if (isolate) {
  13855. child = new Scope();
  13856. child.$root = this.$root;
  13857. } else {
  13858. // Only create a child scope class if somebody asks for one,
  13859. // but cache it to allow the VM to optimize lookups.
  13860. if (!this.$$ChildScope) {
  13861. this.$$ChildScope = createChildScopeClass(this);
  13862. }
  13863. child = new this.$$ChildScope();
  13864. }
  13865. child.$parent = parent;
  13866. child.$$prevSibling = parent.$$childTail;
  13867. if (parent.$$childHead) {
  13868. parent.$$childTail.$$nextSibling = child;
  13869. parent.$$childTail = child;
  13870. } else {
  13871. parent.$$childHead = parent.$$childTail = child;
  13872. }
  13873. // When the new scope is not isolated or we inherit from `this`, and
  13874. // the parent scope is destroyed, the property `$$destroyed` is inherited
  13875. // prototypically. In all other cases, this property needs to be set
  13876. // when the parent scope is destroyed.
  13877. // The listener needs to be added after the parent is set
  13878. if (isolate || parent != this) child.$on('$destroy', destroyChildScope);
  13879. return child;
  13880. },
  13881. /**
  13882. * @ngdoc method
  13883. * @name $rootScope.Scope#$watch
  13884. * @kind function
  13885. *
  13886. * @description
  13887. * Registers a `listener` callback to be executed whenever the `watchExpression` changes.
  13888. *
  13889. * - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
  13890. * $digest()} and should return the value that will be watched. (`watchExpression` should not change
  13891. * its value when executed multiple times with the same input because it may be executed multiple
  13892. * times by {@link ng.$rootScope.Scope#$digest $digest()}. That is, `watchExpression` should be
  13893. * [idempotent](http://en.wikipedia.org/wiki/Idempotence).
  13894. * - The `listener` is called only when the value from the current `watchExpression` and the
  13895. * previous call to `watchExpression` are not equal (with the exception of the initial run,
  13896. * see below). Inequality is determined according to reference inequality,
  13897. * [strict comparison](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
  13898. * via the `!==` Javascript operator, unless `objectEquality == true`
  13899. * (see next point)
  13900. * - When `objectEquality == true`, inequality of the `watchExpression` is determined
  13901. * according to the {@link angular.equals} function. To save the value of the object for
  13902. * later comparison, the {@link angular.copy} function is used. This therefore means that
  13903. * watching complex objects will have adverse memory and performance implications.
  13904. * - The watch `listener` may change the model, which may trigger other `listener`s to fire.
  13905. * This is achieved by rerunning the watchers until no changes are detected. The rerun
  13906. * iteration limit is 10 to prevent an infinite loop deadlock.
  13907. *
  13908. *
  13909. * If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
  13910. * you can register a `watchExpression` function with no `listener`. (Be prepared for
  13911. * multiple calls to your `watchExpression` because it will execute multiple times in a
  13912. * single {@link ng.$rootScope.Scope#$digest $digest} cycle if a change is detected.)
  13913. *
  13914. * After a watcher is registered with the scope, the `listener` fn is called asynchronously
  13915. * (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
  13916. * watcher. In rare cases, this is undesirable because the listener is called when the result
  13917. * of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
  13918. * can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
  13919. * listener was called due to initialization.
  13920. *
  13921. *
  13922. *
  13923. * # Example
  13924. * ```js
  13925. // let's assume that scope was dependency injected as the $rootScope
  13926. var scope = $rootScope;
  13927. scope.name = 'misko';
  13928. scope.counter = 0;
  13929. expect(scope.counter).toEqual(0);
  13930. scope.$watch('name', function(newValue, oldValue) {
  13931. scope.counter = scope.counter + 1;
  13932. });
  13933. expect(scope.counter).toEqual(0);
  13934. scope.$digest();
  13935. // the listener is always called during the first $digest loop after it was registered
  13936. expect(scope.counter).toEqual(1);
  13937. scope.$digest();
  13938. // but now it will not be called unless the value changes
  13939. expect(scope.counter).toEqual(1);
  13940. scope.name = 'adam';
  13941. scope.$digest();
  13942. expect(scope.counter).toEqual(2);
  13943. // Using a function as a watchExpression
  13944. var food;
  13945. scope.foodCounter = 0;
  13946. expect(scope.foodCounter).toEqual(0);
  13947. scope.$watch(
  13948. // This function returns the value being watched. It is called for each turn of the $digest loop
  13949. function() { return food; },
  13950. // This is the change listener, called when the value returned from the above function changes
  13951. function(newValue, oldValue) {
  13952. if ( newValue !== oldValue ) {
  13953. // Only increment the counter if the value changed
  13954. scope.foodCounter = scope.foodCounter + 1;
  13955. }
  13956. }
  13957. );
  13958. // No digest has been run so the counter will be zero
  13959. expect(scope.foodCounter).toEqual(0);
  13960. // Run the digest but since food has not changed count will still be zero
  13961. scope.$digest();
  13962. expect(scope.foodCounter).toEqual(0);
  13963. // Update food and run digest. Now the counter will increment
  13964. food = 'cheeseburger';
  13965. scope.$digest();
  13966. expect(scope.foodCounter).toEqual(1);
  13967. * ```
  13968. *
  13969. *
  13970. *
  13971. * @param {(function()|string)} watchExpression Expression that is evaluated on each
  13972. * {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
  13973. * a call to the `listener`.
  13974. *
  13975. * - `string`: Evaluated as {@link guide/expression expression}
  13976. * - `function(scope)`: called with current `scope` as a parameter.
  13977. * @param {function(newVal, oldVal, scope)} listener Callback called whenever the value
  13978. * of `watchExpression` changes.
  13979. *
  13980. * - `newVal` contains the current value of the `watchExpression`
  13981. * - `oldVal` contains the previous value of the `watchExpression`
  13982. * - `scope` refers to the current scope
  13983. * @param {boolean=} objectEquality Compare for object equality using {@link angular.equals} instead of
  13984. * comparing for reference equality.
  13985. * @returns {function()} Returns a deregistration function for this listener.
  13986. */
  13987. $watch: function(watchExp, listener, objectEquality, prettyPrintExpression) {
  13988. var get = $parse(watchExp);
  13989. if (get.$$watchDelegate) {
  13990. return get.$$watchDelegate(this, listener, objectEquality, get, watchExp);
  13991. }
  13992. var scope = this,
  13993. array = scope.$$watchers,
  13994. watcher = {
  13995. fn: listener,
  13996. last: initWatchVal,
  13997. get: get,
  13998. exp: prettyPrintExpression || watchExp,
  13999. eq: !!objectEquality
  14000. };
  14001. lastDirtyWatch = null;
  14002. if (!isFunction(listener)) {
  14003. watcher.fn = noop;
  14004. }
  14005. if (!array) {
  14006. array = scope.$$watchers = [];
  14007. }
  14008. // we use unshift since we use a while loop in $digest for speed.
  14009. // the while loop reads in reverse order.
  14010. array.unshift(watcher);
  14011. incrementWatchersCount(this, 1);
  14012. return function deregisterWatch() {
  14013. if (arrayRemove(array, watcher) >= 0) {
  14014. incrementWatchersCount(scope, -1);
  14015. }
  14016. lastDirtyWatch = null;
  14017. };
  14018. },
  14019. /**
  14020. * @ngdoc method
  14021. * @name $rootScope.Scope#$watchGroup
  14022. * @kind function
  14023. *
  14024. * @description
  14025. * A variant of {@link ng.$rootScope.Scope#$watch $watch()} where it watches an array of `watchExpressions`.
  14026. * If any one expression in the collection changes the `listener` is executed.
  14027. *
  14028. * - The items in the `watchExpressions` array are observed via standard $watch operation and are examined on every
  14029. * call to $digest() to see if any items changes.
  14030. * - The `listener` is called whenever any expression in the `watchExpressions` array changes.
  14031. *
  14032. * @param {Array.<string|Function(scope)>} watchExpressions Array of expressions that will be individually
  14033. * watched using {@link ng.$rootScope.Scope#$watch $watch()}
  14034. *
  14035. * @param {function(newValues, oldValues, scope)} listener Callback called whenever the return value of any
  14036. * expression in `watchExpressions` changes
  14037. * The `newValues` array contains the current values of the `watchExpressions`, with the indexes matching
  14038. * those of `watchExpression`
  14039. * and the `oldValues` array contains the previous values of the `watchExpressions`, with the indexes matching
  14040. * those of `watchExpression`
  14041. * The `scope` refers to the current scope.
  14042. * @returns {function()} Returns a de-registration function for all listeners.
  14043. */
  14044. $watchGroup: function(watchExpressions, listener) {
  14045. var oldValues = new Array(watchExpressions.length);
  14046. var newValues = new Array(watchExpressions.length);
  14047. var deregisterFns = [];
  14048. var self = this;
  14049. var changeReactionScheduled = false;
  14050. var firstRun = true;
  14051. if (!watchExpressions.length) {
  14052. // No expressions means we call the listener ASAP
  14053. var shouldCall = true;
  14054. self.$evalAsync(function() {
  14055. if (shouldCall) listener(newValues, newValues, self);
  14056. });
  14057. return function deregisterWatchGroup() {
  14058. shouldCall = false;
  14059. };
  14060. }
  14061. if (watchExpressions.length === 1) {
  14062. // Special case size of one
  14063. return this.$watch(watchExpressions[0], function watchGroupAction(value, oldValue, scope) {
  14064. newValues[0] = value;
  14065. oldValues[0] = oldValue;
  14066. listener(newValues, (value === oldValue) ? newValues : oldValues, scope);
  14067. });
  14068. }
  14069. forEach(watchExpressions, function(expr, i) {
  14070. var unwatchFn = self.$watch(expr, function watchGroupSubAction(value, oldValue) {
  14071. newValues[i] = value;
  14072. oldValues[i] = oldValue;
  14073. if (!changeReactionScheduled) {
  14074. changeReactionScheduled = true;
  14075. self.$evalAsync(watchGroupAction);
  14076. }
  14077. });
  14078. deregisterFns.push(unwatchFn);
  14079. });
  14080. function watchGroupAction() {
  14081. changeReactionScheduled = false;
  14082. if (firstRun) {
  14083. firstRun = false;
  14084. listener(newValues, newValues, self);
  14085. } else {
  14086. listener(newValues, oldValues, self);
  14087. }
  14088. }
  14089. return function deregisterWatchGroup() {
  14090. while (deregisterFns.length) {
  14091. deregisterFns.shift()();
  14092. }
  14093. };
  14094. },
  14095. /**
  14096. * @ngdoc method
  14097. * @name $rootScope.Scope#$watchCollection
  14098. * @kind function
  14099. *
  14100. * @description
  14101. * Shallow watches the properties of an object and fires whenever any of the properties change
  14102. * (for arrays, this implies watching the array items; for object maps, this implies watching
  14103. * the properties). If a change is detected, the `listener` callback is fired.
  14104. *
  14105. * - The `obj` collection is observed via standard $watch operation and is examined on every
  14106. * call to $digest() to see if any items have been added, removed, or moved.
  14107. * - The `listener` is called whenever anything within the `obj` has changed. Examples include
  14108. * adding, removing, and moving items belonging to an object or array.
  14109. *
  14110. *
  14111. * # Example
  14112. * ```js
  14113. $scope.names = ['igor', 'matias', 'misko', 'james'];
  14114. $scope.dataCount = 4;
  14115. $scope.$watchCollection('names', function(newNames, oldNames) {
  14116. $scope.dataCount = newNames.length;
  14117. });
  14118. expect($scope.dataCount).toEqual(4);
  14119. $scope.$digest();
  14120. //still at 4 ... no changes
  14121. expect($scope.dataCount).toEqual(4);
  14122. $scope.names.pop();
  14123. $scope.$digest();
  14124. //now there's been a change
  14125. expect($scope.dataCount).toEqual(3);
  14126. * ```
  14127. *
  14128. *
  14129. * @param {string|function(scope)} obj Evaluated as {@link guide/expression expression}. The
  14130. * expression value should evaluate to an object or an array which is observed on each
  14131. * {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
  14132. * collection will trigger a call to the `listener`.
  14133. *
  14134. * @param {function(newCollection, oldCollection, scope)} listener a callback function called
  14135. * when a change is detected.
  14136. * - The `newCollection` object is the newly modified data obtained from the `obj` expression
  14137. * - The `oldCollection` object is a copy of the former collection data.
  14138. * Due to performance considerations, the`oldCollection` value is computed only if the
  14139. * `listener` function declares two or more arguments.
  14140. * - The `scope` argument refers to the current scope.
  14141. *
  14142. * @returns {function()} Returns a de-registration function for this listener. When the
  14143. * de-registration function is executed, the internal watch operation is terminated.
  14144. */
  14145. $watchCollection: function(obj, listener) {
  14146. $watchCollectionInterceptor.$stateful = true;
  14147. var self = this;
  14148. // the current value, updated on each dirty-check run
  14149. var newValue;
  14150. // a shallow copy of the newValue from the last dirty-check run,
  14151. // updated to match newValue during dirty-check run
  14152. var oldValue;
  14153. // a shallow copy of the newValue from when the last change happened
  14154. var veryOldValue;
  14155. // only track veryOldValue if the listener is asking for it
  14156. var trackVeryOldValue = (listener.length > 1);
  14157. var changeDetected = 0;
  14158. var changeDetector = $parse(obj, $watchCollectionInterceptor);
  14159. var internalArray = [];
  14160. var internalObject = {};
  14161. var initRun = true;
  14162. var oldLength = 0;
  14163. function $watchCollectionInterceptor(_value) {
  14164. newValue = _value;
  14165. var newLength, key, bothNaN, newItem, oldItem;
  14166. // If the new value is undefined, then return undefined as the watch may be a one-time watch
  14167. if (isUndefined(newValue)) return;
  14168. if (!isObject(newValue)) { // if primitive
  14169. if (oldValue !== newValue) {
  14170. oldValue = newValue;
  14171. changeDetected++;
  14172. }
  14173. } else if (isArrayLike(newValue)) {
  14174. if (oldValue !== internalArray) {
  14175. // we are transitioning from something which was not an array into array.
  14176. oldValue = internalArray;
  14177. oldLength = oldValue.length = 0;
  14178. changeDetected++;
  14179. }
  14180. newLength = newValue.length;
  14181. if (oldLength !== newLength) {
  14182. // if lengths do not match we need to trigger change notification
  14183. changeDetected++;
  14184. oldValue.length = oldLength = newLength;
  14185. }
  14186. // copy the items to oldValue and look for changes.
  14187. for (var i = 0; i < newLength; i++) {
  14188. oldItem = oldValue[i];
  14189. newItem = newValue[i];
  14190. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14191. if (!bothNaN && (oldItem !== newItem)) {
  14192. changeDetected++;
  14193. oldValue[i] = newItem;
  14194. }
  14195. }
  14196. } else {
  14197. if (oldValue !== internalObject) {
  14198. // we are transitioning from something which was not an object into object.
  14199. oldValue = internalObject = {};
  14200. oldLength = 0;
  14201. changeDetected++;
  14202. }
  14203. // copy the items to oldValue and look for changes.
  14204. newLength = 0;
  14205. for (key in newValue) {
  14206. if (hasOwnProperty.call(newValue, key)) {
  14207. newLength++;
  14208. newItem = newValue[key];
  14209. oldItem = oldValue[key];
  14210. if (key in oldValue) {
  14211. bothNaN = (oldItem !== oldItem) && (newItem !== newItem);
  14212. if (!bothNaN && (oldItem !== newItem)) {
  14213. changeDetected++;
  14214. oldValue[key] = newItem;
  14215. }
  14216. } else {
  14217. oldLength++;
  14218. oldValue[key] = newItem;
  14219. changeDetected++;
  14220. }
  14221. }
  14222. }
  14223. if (oldLength > newLength) {
  14224. // we used to have more keys, need to find them and destroy them.
  14225. changeDetected++;
  14226. for (key in oldValue) {
  14227. if (!hasOwnProperty.call(newValue, key)) {
  14228. oldLength--;
  14229. delete oldValue[key];
  14230. }
  14231. }
  14232. }
  14233. }
  14234. return changeDetected;
  14235. }
  14236. function $watchCollectionAction() {
  14237. if (initRun) {
  14238. initRun = false;
  14239. listener(newValue, newValue, self);
  14240. } else {
  14241. listener(newValue, veryOldValue, self);
  14242. }
  14243. // make a copy for the next time a collection is changed
  14244. if (trackVeryOldValue) {
  14245. if (!isObject(newValue)) {
  14246. //primitive
  14247. veryOldValue = newValue;
  14248. } else if (isArrayLike(newValue)) {
  14249. veryOldValue = new Array(newValue.length);
  14250. for (var i = 0; i < newValue.length; i++) {
  14251. veryOldValue[i] = newValue[i];
  14252. }
  14253. } else { // if object
  14254. veryOldValue = {};
  14255. for (var key in newValue) {
  14256. if (hasOwnProperty.call(newValue, key)) {
  14257. veryOldValue[key] = newValue[key];
  14258. }
  14259. }
  14260. }
  14261. }
  14262. }
  14263. return this.$watch(changeDetector, $watchCollectionAction);
  14264. },
  14265. /**
  14266. * @ngdoc method
  14267. * @name $rootScope.Scope#$digest
  14268. * @kind function
  14269. *
  14270. * @description
  14271. * Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
  14272. * its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
  14273. * the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
  14274. * until no more listeners are firing. This means that it is possible to get into an infinite
  14275. * loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
  14276. * iterations exceeds 10.
  14277. *
  14278. * Usually, you don't call `$digest()` directly in
  14279. * {@link ng.directive:ngController controllers} or in
  14280. * {@link ng.$compileProvider#directive directives}.
  14281. * Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
  14282. * a {@link ng.$compileProvider#directive directive}), which will force a `$digest()`.
  14283. *
  14284. * If you want to be notified whenever `$digest()` is called,
  14285. * you can register a `watchExpression` function with
  14286. * {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
  14287. *
  14288. * In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
  14289. *
  14290. * # Example
  14291. * ```js
  14292. var scope = ...;
  14293. scope.name = 'misko';
  14294. scope.counter = 0;
  14295. expect(scope.counter).toEqual(0);
  14296. scope.$watch('name', function(newValue, oldValue) {
  14297. scope.counter = scope.counter + 1;
  14298. });
  14299. expect(scope.counter).toEqual(0);
  14300. scope.$digest();
  14301. // the listener is always called during the first $digest loop after it was registered
  14302. expect(scope.counter).toEqual(1);
  14303. scope.$digest();
  14304. // but now it will not be called unless the value changes
  14305. expect(scope.counter).toEqual(1);
  14306. scope.name = 'adam';
  14307. scope.$digest();
  14308. expect(scope.counter).toEqual(2);
  14309. * ```
  14310. *
  14311. */
  14312. $digest: function() {
  14313. var watch, value, last,
  14314. watchers,
  14315. length,
  14316. dirty, ttl = TTL,
  14317. next, current, target = this,
  14318. watchLog = [],
  14319. logIdx, logMsg, asyncTask;
  14320. beginPhase('$digest');
  14321. // Check for changes to browser url that happened in sync before the call to $digest
  14322. $browser.$$checkUrlChange();
  14323. if (this === $rootScope && applyAsyncId !== null) {
  14324. // If this is the root scope, and $applyAsync has scheduled a deferred $apply(), then
  14325. // cancel the scheduled $apply and flush the queue of expressions to be evaluated.
  14326. $browser.defer.cancel(applyAsyncId);
  14327. flushApplyAsync();
  14328. }
  14329. lastDirtyWatch = null;
  14330. do { // "while dirty" loop
  14331. dirty = false;
  14332. current = target;
  14333. while (asyncQueue.length) {
  14334. try {
  14335. asyncTask = asyncQueue.shift();
  14336. asyncTask.scope.$eval(asyncTask.expression, asyncTask.locals);
  14337. } catch (e) {
  14338. $exceptionHandler(e);
  14339. }
  14340. lastDirtyWatch = null;
  14341. }
  14342. traverseScopesLoop:
  14343. do { // "traverse the scopes" loop
  14344. if ((watchers = current.$$watchers)) {
  14345. // process our watches
  14346. length = watchers.length;
  14347. while (length--) {
  14348. try {
  14349. watch = watchers[length];
  14350. // Most common watches are on primitives, in which case we can short
  14351. // circuit it with === operator, only when === fails do we use .equals
  14352. if (watch) {
  14353. if ((value = watch.get(current)) !== (last = watch.last) &&
  14354. !(watch.eq
  14355. ? equals(value, last)
  14356. : (typeof value === 'number' && typeof last === 'number'
  14357. && isNaN(value) && isNaN(last)))) {
  14358. dirty = true;
  14359. lastDirtyWatch = watch;
  14360. watch.last = watch.eq ? copy(value, null) : value;
  14361. watch.fn(value, ((last === initWatchVal) ? value : last), current);
  14362. if (ttl < 5) {
  14363. logIdx = 4 - ttl;
  14364. if (!watchLog[logIdx]) watchLog[logIdx] = [];
  14365. watchLog[logIdx].push({
  14366. msg: isFunction(watch.exp) ? 'fn: ' + (watch.exp.name || watch.exp.toString()) : watch.exp,
  14367. newVal: value,
  14368. oldVal: last
  14369. });
  14370. }
  14371. } else if (watch === lastDirtyWatch) {
  14372. // If the most recently dirty watcher is now clean, short circuit since the remaining watchers
  14373. // have already been tested.
  14374. dirty = false;
  14375. break traverseScopesLoop;
  14376. }
  14377. }
  14378. } catch (e) {
  14379. $exceptionHandler(e);
  14380. }
  14381. }
  14382. }
  14383. // Insanity Warning: scope depth-first traversal
  14384. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14385. // this piece should be kept in sync with the traversal in $broadcast
  14386. if (!(next = ((current.$$watchersCount && current.$$childHead) ||
  14387. (current !== target && current.$$nextSibling)))) {
  14388. while (current !== target && !(next = current.$$nextSibling)) {
  14389. current = current.$parent;
  14390. }
  14391. }
  14392. } while ((current = next));
  14393. // `break traverseScopesLoop;` takes us to here
  14394. if ((dirty || asyncQueue.length) && !(ttl--)) {
  14395. clearPhase();
  14396. throw $rootScopeMinErr('infdig',
  14397. '{0} $digest() iterations reached. Aborting!\n' +
  14398. 'Watchers fired in the last 5 iterations: {1}',
  14399. TTL, watchLog);
  14400. }
  14401. } while (dirty || asyncQueue.length);
  14402. clearPhase();
  14403. while (postDigestQueue.length) {
  14404. try {
  14405. postDigestQueue.shift()();
  14406. } catch (e) {
  14407. $exceptionHandler(e);
  14408. }
  14409. }
  14410. },
  14411. /**
  14412. * @ngdoc event
  14413. * @name $rootScope.Scope#$destroy
  14414. * @eventType broadcast on scope being destroyed
  14415. *
  14416. * @description
  14417. * Broadcasted when a scope and its children are being destroyed.
  14418. *
  14419. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14420. * clean up DOM bindings before an element is removed from the DOM.
  14421. */
  14422. /**
  14423. * @ngdoc method
  14424. * @name $rootScope.Scope#$destroy
  14425. * @kind function
  14426. *
  14427. * @description
  14428. * Removes the current scope (and all of its children) from the parent scope. Removal implies
  14429. * that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
  14430. * propagate to the current scope and its children. Removal also implies that the current
  14431. * scope is eligible for garbage collection.
  14432. *
  14433. * The `$destroy()` is usually used by directives such as
  14434. * {@link ng.directive:ngRepeat ngRepeat} for managing the
  14435. * unrolling of the loop.
  14436. *
  14437. * Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
  14438. * Application code can register a `$destroy` event handler that will give it a chance to
  14439. * perform any necessary cleanup.
  14440. *
  14441. * Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
  14442. * clean up DOM bindings before an element is removed from the DOM.
  14443. */
  14444. $destroy: function() {
  14445. // We can't destroy a scope that has been already destroyed.
  14446. if (this.$$destroyed) return;
  14447. var parent = this.$parent;
  14448. this.$broadcast('$destroy');
  14449. this.$$destroyed = true;
  14450. if (this === $rootScope) {
  14451. //Remove handlers attached to window when $rootScope is removed
  14452. $browser.$$applicationDestroyed();
  14453. }
  14454. incrementWatchersCount(this, -this.$$watchersCount);
  14455. for (var eventName in this.$$listenerCount) {
  14456. decrementListenerCount(this, this.$$listenerCount[eventName], eventName);
  14457. }
  14458. // sever all the references to parent scopes (after this cleanup, the current scope should
  14459. // not be retained by any of our references and should be eligible for garbage collection)
  14460. if (parent && parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
  14461. if (parent && parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
  14462. if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
  14463. if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
  14464. // Disable listeners, watchers and apply/digest methods
  14465. this.$destroy = this.$digest = this.$apply = this.$evalAsync = this.$applyAsync = noop;
  14466. this.$on = this.$watch = this.$watchGroup = function() { return noop; };
  14467. this.$$listeners = {};
  14468. // Disconnect the next sibling to prevent `cleanUpScope` destroying those too
  14469. this.$$nextSibling = null;
  14470. cleanUpScope(this);
  14471. },
  14472. /**
  14473. * @ngdoc method
  14474. * @name $rootScope.Scope#$eval
  14475. * @kind function
  14476. *
  14477. * @description
  14478. * Executes the `expression` on the current scope and returns the result. Any exceptions in
  14479. * the expression are propagated (uncaught). This is useful when evaluating Angular
  14480. * expressions.
  14481. *
  14482. * # Example
  14483. * ```js
  14484. var scope = ng.$rootScope.Scope();
  14485. scope.a = 1;
  14486. scope.b = 2;
  14487. expect(scope.$eval('a+b')).toEqual(3);
  14488. expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
  14489. * ```
  14490. *
  14491. * @param {(string|function())=} expression An angular expression to be executed.
  14492. *
  14493. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14494. * - `function(scope)`: execute the function with the current `scope` parameter.
  14495. *
  14496. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14497. * @returns {*} The result of evaluating the expression.
  14498. */
  14499. $eval: function(expr, locals) {
  14500. return $parse(expr)(this, locals);
  14501. },
  14502. /**
  14503. * @ngdoc method
  14504. * @name $rootScope.Scope#$evalAsync
  14505. * @kind function
  14506. *
  14507. * @description
  14508. * Executes the expression on the current scope at a later point in time.
  14509. *
  14510. * The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
  14511. * that:
  14512. *
  14513. * - it will execute after the function that scheduled the evaluation (preferably before DOM
  14514. * rendering).
  14515. * - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
  14516. * `expression` execution.
  14517. *
  14518. * Any exceptions from the execution of the expression are forwarded to the
  14519. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14520. *
  14521. * __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
  14522. * will be scheduled. However, it is encouraged to always call code that changes the model
  14523. * from within an `$apply` call. That includes code evaluated via `$evalAsync`.
  14524. *
  14525. * @param {(string|function())=} expression An angular expression to be executed.
  14526. *
  14527. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14528. * - `function(scope)`: execute the function with the current `scope` parameter.
  14529. *
  14530. * @param {(object)=} locals Local variables object, useful for overriding values in scope.
  14531. */
  14532. $evalAsync: function(expr, locals) {
  14533. // if we are outside of an $digest loop and this is the first time we are scheduling async
  14534. // task also schedule async auto-flush
  14535. if (!$rootScope.$$phase && !asyncQueue.length) {
  14536. $browser.defer(function() {
  14537. if (asyncQueue.length) {
  14538. $rootScope.$digest();
  14539. }
  14540. });
  14541. }
  14542. asyncQueue.push({scope: this, expression: expr, locals: locals});
  14543. },
  14544. $$postDigest: function(fn) {
  14545. postDigestQueue.push(fn);
  14546. },
  14547. /**
  14548. * @ngdoc method
  14549. * @name $rootScope.Scope#$apply
  14550. * @kind function
  14551. *
  14552. * @description
  14553. * `$apply()` is used to execute an expression in angular from outside of the angular
  14554. * framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
  14555. * Because we are calling into the angular framework we need to perform proper scope life
  14556. * cycle of {@link ng.$exceptionHandler exception handling},
  14557. * {@link ng.$rootScope.Scope#$digest executing watches}.
  14558. *
  14559. * ## Life cycle
  14560. *
  14561. * # Pseudo-Code of `$apply()`
  14562. * ```js
  14563. function $apply(expr) {
  14564. try {
  14565. return $eval(expr);
  14566. } catch (e) {
  14567. $exceptionHandler(e);
  14568. } finally {
  14569. $root.$digest();
  14570. }
  14571. }
  14572. * ```
  14573. *
  14574. *
  14575. * Scope's `$apply()` method transitions through the following stages:
  14576. *
  14577. * 1. The {@link guide/expression expression} is executed using the
  14578. * {@link ng.$rootScope.Scope#$eval $eval()} method.
  14579. * 2. Any exceptions from the execution of the expression are forwarded to the
  14580. * {@link ng.$exceptionHandler $exceptionHandler} service.
  14581. * 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
  14582. * expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
  14583. *
  14584. *
  14585. * @param {(string|function())=} exp An angular expression to be executed.
  14586. *
  14587. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14588. * - `function(scope)`: execute the function with current `scope` parameter.
  14589. *
  14590. * @returns {*} The result of evaluating the expression.
  14591. */
  14592. $apply: function(expr) {
  14593. try {
  14594. beginPhase('$apply');
  14595. try {
  14596. return this.$eval(expr);
  14597. } finally {
  14598. clearPhase();
  14599. }
  14600. } catch (e) {
  14601. $exceptionHandler(e);
  14602. } finally {
  14603. try {
  14604. $rootScope.$digest();
  14605. } catch (e) {
  14606. $exceptionHandler(e);
  14607. throw e;
  14608. }
  14609. }
  14610. },
  14611. /**
  14612. * @ngdoc method
  14613. * @name $rootScope.Scope#$applyAsync
  14614. * @kind function
  14615. *
  14616. * @description
  14617. * Schedule the invocation of $apply to occur at a later time. The actual time difference
  14618. * varies across browsers, but is typically around ~10 milliseconds.
  14619. *
  14620. * This can be used to queue up multiple expressions which need to be evaluated in the same
  14621. * digest.
  14622. *
  14623. * @param {(string|function())=} exp An angular expression to be executed.
  14624. *
  14625. * - `string`: execute using the rules as defined in {@link guide/expression expression}.
  14626. * - `function(scope)`: execute the function with current `scope` parameter.
  14627. */
  14628. $applyAsync: function(expr) {
  14629. var scope = this;
  14630. expr && applyAsyncQueue.push($applyAsyncExpression);
  14631. scheduleApplyAsync();
  14632. function $applyAsyncExpression() {
  14633. scope.$eval(expr);
  14634. }
  14635. },
  14636. /**
  14637. * @ngdoc method
  14638. * @name $rootScope.Scope#$on
  14639. * @kind function
  14640. *
  14641. * @description
  14642. * Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
  14643. * discussion of event life cycle.
  14644. *
  14645. * The event listener function format is: `function(event, args...)`. The `event` object
  14646. * passed into the listener has the following attributes:
  14647. *
  14648. * - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
  14649. * `$broadcast`-ed.
  14650. * - `currentScope` - `{Scope}`: the scope that is currently handling the event. Once the
  14651. * event propagates through the scope hierarchy, this property is set to null.
  14652. * - `name` - `{string}`: name of the event.
  14653. * - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
  14654. * further event propagation (available only for events that were `$emit`-ed).
  14655. * - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
  14656. * to true.
  14657. * - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
  14658. *
  14659. * @param {string} name Event name to listen on.
  14660. * @param {function(event, ...args)} listener Function to call when the event is emitted.
  14661. * @returns {function()} Returns a deregistration function for this listener.
  14662. */
  14663. $on: function(name, listener) {
  14664. var namedListeners = this.$$listeners[name];
  14665. if (!namedListeners) {
  14666. this.$$listeners[name] = namedListeners = [];
  14667. }
  14668. namedListeners.push(listener);
  14669. var current = this;
  14670. do {
  14671. if (!current.$$listenerCount[name]) {
  14672. current.$$listenerCount[name] = 0;
  14673. }
  14674. current.$$listenerCount[name]++;
  14675. } while ((current = current.$parent));
  14676. var self = this;
  14677. return function() {
  14678. var indexOfListener = namedListeners.indexOf(listener);
  14679. if (indexOfListener !== -1) {
  14680. namedListeners[indexOfListener] = null;
  14681. decrementListenerCount(self, 1, name);
  14682. }
  14683. };
  14684. },
  14685. /**
  14686. * @ngdoc method
  14687. * @name $rootScope.Scope#$emit
  14688. * @kind function
  14689. *
  14690. * @description
  14691. * Dispatches an event `name` upwards through the scope hierarchy notifying the
  14692. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14693. *
  14694. * The event life cycle starts at the scope on which `$emit` was called. All
  14695. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14696. * notified. Afterwards, the event traverses upwards toward the root scope and calls all
  14697. * registered listeners along the way. The event will stop propagating if one of the listeners
  14698. * cancels it.
  14699. *
  14700. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14701. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14702. *
  14703. * @param {string} name Event name to emit.
  14704. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14705. * @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
  14706. */
  14707. $emit: function(name, args) {
  14708. var empty = [],
  14709. namedListeners,
  14710. scope = this,
  14711. stopPropagation = false,
  14712. event = {
  14713. name: name,
  14714. targetScope: scope,
  14715. stopPropagation: function() {stopPropagation = true;},
  14716. preventDefault: function() {
  14717. event.defaultPrevented = true;
  14718. },
  14719. defaultPrevented: false
  14720. },
  14721. listenerArgs = concat([event], arguments, 1),
  14722. i, length;
  14723. do {
  14724. namedListeners = scope.$$listeners[name] || empty;
  14725. event.currentScope = scope;
  14726. for (i = 0, length = namedListeners.length; i < length; i++) {
  14727. // if listeners were deregistered, defragment the array
  14728. if (!namedListeners[i]) {
  14729. namedListeners.splice(i, 1);
  14730. i--;
  14731. length--;
  14732. continue;
  14733. }
  14734. try {
  14735. //allow all listeners attached to the current scope to run
  14736. namedListeners[i].apply(null, listenerArgs);
  14737. } catch (e) {
  14738. $exceptionHandler(e);
  14739. }
  14740. }
  14741. //if any listener on the current scope stops propagation, prevent bubbling
  14742. if (stopPropagation) {
  14743. event.currentScope = null;
  14744. return event;
  14745. }
  14746. //traverse upwards
  14747. scope = scope.$parent;
  14748. } while (scope);
  14749. event.currentScope = null;
  14750. return event;
  14751. },
  14752. /**
  14753. * @ngdoc method
  14754. * @name $rootScope.Scope#$broadcast
  14755. * @kind function
  14756. *
  14757. * @description
  14758. * Dispatches an event `name` downwards to all child scopes (and their children) notifying the
  14759. * registered {@link ng.$rootScope.Scope#$on} listeners.
  14760. *
  14761. * The event life cycle starts at the scope on which `$broadcast` was called. All
  14762. * {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
  14763. * notified. Afterwards, the event propagates to all direct and indirect scopes of the current
  14764. * scope and calls all registered listeners along the way. The event cannot be canceled.
  14765. *
  14766. * Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
  14767. * onto the {@link ng.$exceptionHandler $exceptionHandler} service.
  14768. *
  14769. * @param {string} name Event name to broadcast.
  14770. * @param {...*} args Optional one or more arguments which will be passed onto the event listeners.
  14771. * @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
  14772. */
  14773. $broadcast: function(name, args) {
  14774. var target = this,
  14775. current = target,
  14776. next = target,
  14777. event = {
  14778. name: name,
  14779. targetScope: target,
  14780. preventDefault: function() {
  14781. event.defaultPrevented = true;
  14782. },
  14783. defaultPrevented: false
  14784. };
  14785. if (!target.$$listenerCount[name]) return event;
  14786. var listenerArgs = concat([event], arguments, 1),
  14787. listeners, i, length;
  14788. //down while you can, then up and next sibling or up and next sibling until back at root
  14789. while ((current = next)) {
  14790. event.currentScope = current;
  14791. listeners = current.$$listeners[name] || [];
  14792. for (i = 0, length = listeners.length; i < length; i++) {
  14793. // if listeners were deregistered, defragment the array
  14794. if (!listeners[i]) {
  14795. listeners.splice(i, 1);
  14796. i--;
  14797. length--;
  14798. continue;
  14799. }
  14800. try {
  14801. listeners[i].apply(null, listenerArgs);
  14802. } catch (e) {
  14803. $exceptionHandler(e);
  14804. }
  14805. }
  14806. // Insanity Warning: scope depth-first traversal
  14807. // yes, this code is a bit crazy, but it works and we have tests to prove it!
  14808. // this piece should be kept in sync with the traversal in $digest
  14809. // (though it differs due to having the extra check for $$listenerCount)
  14810. if (!(next = ((current.$$listenerCount[name] && current.$$childHead) ||
  14811. (current !== target && current.$$nextSibling)))) {
  14812. while (current !== target && !(next = current.$$nextSibling)) {
  14813. current = current.$parent;
  14814. }
  14815. }
  14816. }
  14817. event.currentScope = null;
  14818. return event;
  14819. }
  14820. };
  14821. var $rootScope = new Scope();
  14822. //The internal queues. Expose them on the $rootScope for debugging/testing purposes.
  14823. var asyncQueue = $rootScope.$$asyncQueue = [];
  14824. var postDigestQueue = $rootScope.$$postDigestQueue = [];
  14825. var applyAsyncQueue = $rootScope.$$applyAsyncQueue = [];
  14826. return $rootScope;
  14827. function beginPhase(phase) {
  14828. if ($rootScope.$$phase) {
  14829. throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
  14830. }
  14831. $rootScope.$$phase = phase;
  14832. }
  14833. function clearPhase() {
  14834. $rootScope.$$phase = null;
  14835. }
  14836. function incrementWatchersCount(current, count) {
  14837. do {
  14838. current.$$watchersCount += count;
  14839. } while ((current = current.$parent));
  14840. }
  14841. function decrementListenerCount(current, count, name) {
  14842. do {
  14843. current.$$listenerCount[name] -= count;
  14844. if (current.$$listenerCount[name] === 0) {
  14845. delete current.$$listenerCount[name];
  14846. }
  14847. } while ((current = current.$parent));
  14848. }
  14849. /**
  14850. * function used as an initial value for watchers.
  14851. * because it's unique we can easily tell it apart from other values
  14852. */
  14853. function initWatchVal() {}
  14854. function flushApplyAsync() {
  14855. while (applyAsyncQueue.length) {
  14856. try {
  14857. applyAsyncQueue.shift()();
  14858. } catch (e) {
  14859. $exceptionHandler(e);
  14860. }
  14861. }
  14862. applyAsyncId = null;
  14863. }
  14864. function scheduleApplyAsync() {
  14865. if (applyAsyncId === null) {
  14866. applyAsyncId = $browser.defer(function() {
  14867. $rootScope.$apply(flushApplyAsync);
  14868. });
  14869. }
  14870. }
  14871. }];
  14872. }
  14873. /**
  14874. * @description
  14875. * Private service to sanitize uris for links and images. Used by $compile and $sanitize.
  14876. */
  14877. function $$SanitizeUriProvider() {
  14878. var aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
  14879. imgSrcSanitizationWhitelist = /^\s*((https?|ftp|file|blob):|data:image\/)/;
  14880. /**
  14881. * @description
  14882. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14883. * urls during a[href] sanitization.
  14884. *
  14885. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14886. *
  14887. * Any url about to be assigned to a[href] via data-binding is first normalized and turned into
  14888. * an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
  14889. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14890. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14891. *
  14892. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14893. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14894. * chaining otherwise.
  14895. */
  14896. this.aHrefSanitizationWhitelist = function(regexp) {
  14897. if (isDefined(regexp)) {
  14898. aHrefSanitizationWhitelist = regexp;
  14899. return this;
  14900. }
  14901. return aHrefSanitizationWhitelist;
  14902. };
  14903. /**
  14904. * @description
  14905. * Retrieves or overrides the default regular expression that is used for whitelisting of safe
  14906. * urls during img[src] sanitization.
  14907. *
  14908. * The sanitization is a security measure aimed at prevent XSS attacks via html links.
  14909. *
  14910. * Any url about to be assigned to img[src] via data-binding is first normalized and turned into
  14911. * an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
  14912. * regular expression. If a match is found, the original url is written into the dom. Otherwise,
  14913. * the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
  14914. *
  14915. * @param {RegExp=} regexp New regexp to whitelist urls with.
  14916. * @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
  14917. * chaining otherwise.
  14918. */
  14919. this.imgSrcSanitizationWhitelist = function(regexp) {
  14920. if (isDefined(regexp)) {
  14921. imgSrcSanitizationWhitelist = regexp;
  14922. return this;
  14923. }
  14924. return imgSrcSanitizationWhitelist;
  14925. };
  14926. this.$get = function() {
  14927. return function sanitizeUri(uri, isImage) {
  14928. var regex = isImage ? imgSrcSanitizationWhitelist : aHrefSanitizationWhitelist;
  14929. var normalizedVal;
  14930. normalizedVal = urlResolve(uri).href;
  14931. if (normalizedVal !== '' && !normalizedVal.match(regex)) {
  14932. return 'unsafe:' + normalizedVal;
  14933. }
  14934. return uri;
  14935. };
  14936. };
  14937. }
  14938. /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
  14939. * Any commits to this file should be reviewed with security in mind. *
  14940. * Changes to this file can potentially create security vulnerabilities. *
  14941. * An approval from 2 Core members with history of modifying *
  14942. * this file is required. *
  14943. * *
  14944. * Does the change somehow allow for arbitrary javascript to be executed? *
  14945. * Or allows for someone to change the prototype of built-in objects? *
  14946. * Or gives undesired access to variables likes document or window? *
  14947. * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
  14948. var $sceMinErr = minErr('$sce');
  14949. var SCE_CONTEXTS = {
  14950. HTML: 'html',
  14951. CSS: 'css',
  14952. URL: 'url',
  14953. // RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
  14954. // url. (e.g. ng-include, script src, templateUrl)
  14955. RESOURCE_URL: 'resourceUrl',
  14956. JS: 'js'
  14957. };
  14958. // Helper functions follow.
  14959. function adjustMatcher(matcher) {
  14960. if (matcher === 'self') {
  14961. return matcher;
  14962. } else if (isString(matcher)) {
  14963. // Strings match exactly except for 2 wildcards - '*' and '**'.
  14964. // '*' matches any character except those from the set ':/.?&'.
  14965. // '**' matches any character (like .* in a RegExp).
  14966. // More than 2 *'s raises an error as it's ill defined.
  14967. if (matcher.indexOf('***') > -1) {
  14968. throw $sceMinErr('iwcard',
  14969. 'Illegal sequence *** in string matcher. String: {0}', matcher);
  14970. }
  14971. matcher = escapeForRegexp(matcher).
  14972. replace('\\*\\*', '.*').
  14973. replace('\\*', '[^:/.?&;]*');
  14974. return new RegExp('^' + matcher + '$');
  14975. } else if (isRegExp(matcher)) {
  14976. // The only other type of matcher allowed is a Regexp.
  14977. // Match entire URL / disallow partial matches.
  14978. // Flags are reset (i.e. no global, ignoreCase or multiline)
  14979. return new RegExp('^' + matcher.source + '$');
  14980. } else {
  14981. throw $sceMinErr('imatcher',
  14982. 'Matchers may only be "self", string patterns or RegExp objects');
  14983. }
  14984. }
  14985. function adjustMatchers(matchers) {
  14986. var adjustedMatchers = [];
  14987. if (isDefined(matchers)) {
  14988. forEach(matchers, function(matcher) {
  14989. adjustedMatchers.push(adjustMatcher(matcher));
  14990. });
  14991. }
  14992. return adjustedMatchers;
  14993. }
  14994. /**
  14995. * @ngdoc service
  14996. * @name $sceDelegate
  14997. * @kind function
  14998. *
  14999. * @description
  15000. *
  15001. * `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
  15002. * Contextual Escaping (SCE)} services to AngularJS.
  15003. *
  15004. * Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
  15005. * the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
  15006. * because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
  15007. * override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
  15008. * work because `$sce` delegates to `$sceDelegate` for these operations.
  15009. *
  15010. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
  15011. *
  15012. * The default instance of `$sceDelegate` should work out of the box with little pain. While you
  15013. * can override it completely to change the behavior of `$sce`, the common case would
  15014. * involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
  15015. * your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
  15016. * templates. Refer {@link ng.$sceDelegateProvider#resourceUrlWhitelist
  15017. * $sceDelegateProvider.resourceUrlWhitelist} and {@link
  15018. * ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  15019. */
  15020. /**
  15021. * @ngdoc provider
  15022. * @name $sceDelegateProvider
  15023. * @description
  15024. *
  15025. * The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
  15026. * $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
  15027. * that the URLs used for sourcing Angular templates are safe. Refer {@link
  15028. * ng.$sceDelegateProvider#resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
  15029. * {@link ng.$sceDelegateProvider#resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
  15030. *
  15031. * For the general details about this service in Angular, read the main page for {@link ng.$sce
  15032. * Strict Contextual Escaping (SCE)}.
  15033. *
  15034. * **Example**: Consider the following case. <a name="example"></a>
  15035. *
  15036. * - your app is hosted at url `http://myapp.example.com/`
  15037. * - but some of your templates are hosted on other domains you control such as
  15038. * `http://srv01.assets.example.com/`,  `http://srv02.assets.example.com/`, etc.
  15039. * - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
  15040. *
  15041. * Here is what a secure configuration for this scenario might look like:
  15042. *
  15043. * ```
  15044. * angular.module('myApp', []).config(function($sceDelegateProvider) {
  15045. * $sceDelegateProvider.resourceUrlWhitelist([
  15046. * // Allow same origin resource loads.
  15047. * 'self',
  15048. * // Allow loading from our assets domain. Notice the difference between * and **.
  15049. * 'http://srv*.assets.example.com/**'
  15050. * ]);
  15051. *
  15052. * // The blacklist overrides the whitelist so the open redirect here is blocked.
  15053. * $sceDelegateProvider.resourceUrlBlacklist([
  15054. * 'http://myapp.example.com/clickThru**'
  15055. * ]);
  15056. * });
  15057. * ```
  15058. */
  15059. function $SceDelegateProvider() {
  15060. this.SCE_CONTEXTS = SCE_CONTEXTS;
  15061. // Resource URLs can also be trusted by policy.
  15062. var resourceUrlWhitelist = ['self'],
  15063. resourceUrlBlacklist = [];
  15064. /**
  15065. * @ngdoc method
  15066. * @name $sceDelegateProvider#resourceUrlWhitelist
  15067. * @kind function
  15068. *
  15069. * @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
  15070. * provided. This must be an array or null. A snapshot of this array is used so further
  15071. * changes to the array are ignored.
  15072. *
  15073. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  15074. * allowed in this array.
  15075. *
  15076. * Note: **an empty whitelist array will block all URLs**!
  15077. *
  15078. * @return {Array} the currently set whitelist array.
  15079. *
  15080. * The **default value** when no whitelist has been explicitly set is `['self']` allowing only
  15081. * same origin resource requests.
  15082. *
  15083. * @description
  15084. * Sets/Gets the whitelist of trusted resource URLs.
  15085. */
  15086. this.resourceUrlWhitelist = function(value) {
  15087. if (arguments.length) {
  15088. resourceUrlWhitelist = adjustMatchers(value);
  15089. }
  15090. return resourceUrlWhitelist;
  15091. };
  15092. /**
  15093. * @ngdoc method
  15094. * @name $sceDelegateProvider#resourceUrlBlacklist
  15095. * @kind function
  15096. *
  15097. * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
  15098. * provided. This must be an array or null. A snapshot of this array is used so further
  15099. * changes to the array are ignored.
  15100. *
  15101. * Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
  15102. * allowed in this array.
  15103. *
  15104. * The typical usage for the blacklist is to **block
  15105. * [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
  15106. * these would otherwise be trusted but actually return content from the redirected domain.
  15107. *
  15108. * Finally, **the blacklist overrides the whitelist** and has the final say.
  15109. *
  15110. * @return {Array} the currently set blacklist array.
  15111. *
  15112. * The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
  15113. * is no blacklist.)
  15114. *
  15115. * @description
  15116. * Sets/Gets the blacklist of trusted resource URLs.
  15117. */
  15118. this.resourceUrlBlacklist = function(value) {
  15119. if (arguments.length) {
  15120. resourceUrlBlacklist = adjustMatchers(value);
  15121. }
  15122. return resourceUrlBlacklist;
  15123. };
  15124. this.$get = ['$injector', function($injector) {
  15125. var htmlSanitizer = function htmlSanitizer(html) {
  15126. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15127. };
  15128. if ($injector.has('$sanitize')) {
  15129. htmlSanitizer = $injector.get('$sanitize');
  15130. }
  15131. function matchUrl(matcher, parsedUrl) {
  15132. if (matcher === 'self') {
  15133. return urlIsSameOrigin(parsedUrl);
  15134. } else {
  15135. // definitely a regex. See adjustMatchers()
  15136. return !!matcher.exec(parsedUrl.href);
  15137. }
  15138. }
  15139. function isResourceUrlAllowedByPolicy(url) {
  15140. var parsedUrl = urlResolve(url.toString());
  15141. var i, n, allowed = false;
  15142. // Ensure that at least one item from the whitelist allows this url.
  15143. for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
  15144. if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
  15145. allowed = true;
  15146. break;
  15147. }
  15148. }
  15149. if (allowed) {
  15150. // Ensure that no item from the blacklist blocked this url.
  15151. for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
  15152. if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
  15153. allowed = false;
  15154. break;
  15155. }
  15156. }
  15157. }
  15158. return allowed;
  15159. }
  15160. function generateHolderType(Base) {
  15161. var holderType = function TrustedValueHolderType(trustedValue) {
  15162. this.$$unwrapTrustedValue = function() {
  15163. return trustedValue;
  15164. };
  15165. };
  15166. if (Base) {
  15167. holderType.prototype = new Base();
  15168. }
  15169. holderType.prototype.valueOf = function sceValueOf() {
  15170. return this.$$unwrapTrustedValue();
  15171. };
  15172. holderType.prototype.toString = function sceToString() {
  15173. return this.$$unwrapTrustedValue().toString();
  15174. };
  15175. return holderType;
  15176. }
  15177. var trustedValueHolderBase = generateHolderType(),
  15178. byType = {};
  15179. byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
  15180. byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
  15181. byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
  15182. byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
  15183. byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
  15184. /**
  15185. * @ngdoc method
  15186. * @name $sceDelegate#trustAs
  15187. *
  15188. * @description
  15189. * Returns an object that is trusted by angular for use in specified strict
  15190. * contextual escaping contexts (such as ng-bind-html, ng-include, any src
  15191. * attribute interpolation, any dom event binding attribute interpolation
  15192. * such as for onclick, etc.) that uses the provided value.
  15193. * See {@link ng.$sce $sce} for enabling strict contextual escaping.
  15194. *
  15195. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15196. * resourceUrl, html, js and css.
  15197. * @param {*} value The value that that should be considered trusted/safe.
  15198. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15199. * where Angular expects a $sce.trustAs() return value.
  15200. */
  15201. function trustAs(type, trustedValue) {
  15202. var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15203. if (!Constructor) {
  15204. throw $sceMinErr('icontext',
  15205. 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
  15206. type, trustedValue);
  15207. }
  15208. if (trustedValue === null || isUndefined(trustedValue) || trustedValue === '') {
  15209. return trustedValue;
  15210. }
  15211. // All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
  15212. // mutable objects, we ensure here that the value passed in is actually a string.
  15213. if (typeof trustedValue !== 'string') {
  15214. throw $sceMinErr('itype',
  15215. 'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
  15216. type);
  15217. }
  15218. return new Constructor(trustedValue);
  15219. }
  15220. /**
  15221. * @ngdoc method
  15222. * @name $sceDelegate#valueOf
  15223. *
  15224. * @description
  15225. * If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#trustAs
  15226. * `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
  15227. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}.
  15228. *
  15229. * If the passed parameter is not a value that had been returned by {@link
  15230. * ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}, returns it as-is.
  15231. *
  15232. * @param {*} value The result of a prior {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}
  15233. * call or anything else.
  15234. * @returns {*} The `value` that was originally provided to {@link ng.$sceDelegate#trustAs
  15235. * `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
  15236. * `value` unchanged.
  15237. */
  15238. function valueOf(maybeTrusted) {
  15239. if (maybeTrusted instanceof trustedValueHolderBase) {
  15240. return maybeTrusted.$$unwrapTrustedValue();
  15241. } else {
  15242. return maybeTrusted;
  15243. }
  15244. }
  15245. /**
  15246. * @ngdoc method
  15247. * @name $sceDelegate#getTrusted
  15248. *
  15249. * @description
  15250. * Takes the result of a {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`} call and
  15251. * returns the originally supplied value if the queried context type is a supertype of the
  15252. * created type. If this condition isn't satisfied, throws an exception.
  15253. *
  15254. * @param {string} type The kind of context in which this value is to be used.
  15255. * @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#trustAs
  15256. * `$sceDelegate.trustAs`} call.
  15257. * @returns {*} The value the was originally provided to {@link ng.$sceDelegate#trustAs
  15258. * `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
  15259. */
  15260. function getTrusted(type, maybeTrusted) {
  15261. if (maybeTrusted === null || isUndefined(maybeTrusted) || maybeTrusted === '') {
  15262. return maybeTrusted;
  15263. }
  15264. var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
  15265. if (constructor && maybeTrusted instanceof constructor) {
  15266. return maybeTrusted.$$unwrapTrustedValue();
  15267. }
  15268. // If we get here, then we may only take one of two actions.
  15269. // 1. sanitize the value for the requested type, or
  15270. // 2. throw an exception.
  15271. if (type === SCE_CONTEXTS.RESOURCE_URL) {
  15272. if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
  15273. return maybeTrusted;
  15274. } else {
  15275. throw $sceMinErr('insecurl',
  15276. 'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
  15277. maybeTrusted.toString());
  15278. }
  15279. } else if (type === SCE_CONTEXTS.HTML) {
  15280. return htmlSanitizer(maybeTrusted);
  15281. }
  15282. throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
  15283. }
  15284. return { trustAs: trustAs,
  15285. getTrusted: getTrusted,
  15286. valueOf: valueOf };
  15287. }];
  15288. }
  15289. /**
  15290. * @ngdoc provider
  15291. * @name $sceProvider
  15292. * @description
  15293. *
  15294. * The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
  15295. * - enable/disable Strict Contextual Escaping (SCE) in a module
  15296. * - override the default implementation with a custom delegate
  15297. *
  15298. * Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
  15299. */
  15300. /* jshint maxlen: false*/
  15301. /**
  15302. * @ngdoc service
  15303. * @name $sce
  15304. * @kind function
  15305. *
  15306. * @description
  15307. *
  15308. * `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
  15309. *
  15310. * # Strict Contextual Escaping
  15311. *
  15312. * Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
  15313. * contexts to result in a value that is marked as safe to use for that context. One example of
  15314. * such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
  15315. * to these contexts as privileged or SCE contexts.
  15316. *
  15317. * As of version 1.2, Angular ships with SCE enabled by default.
  15318. *
  15319. * Note: When enabled (the default), IE<11 in quirks mode is not supported. In this mode, IE<11 allow
  15320. * one to execute arbitrary javascript by the use of the expression() syntax. Refer
  15321. * <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
  15322. * You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
  15323. * to the top of your HTML document.
  15324. *
  15325. * SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
  15326. * security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
  15327. *
  15328. * Here's an example of a binding in a privileged context:
  15329. *
  15330. * ```
  15331. * <input ng-model="userHtml" aria-label="User input">
  15332. * <div ng-bind-html="userHtml"></div>
  15333. * ```
  15334. *
  15335. * Notice that `ng-bind-html` is bound to `userHtml` controlled by the user. With SCE
  15336. * disabled, this application allows the user to render arbitrary HTML into the DIV.
  15337. * In a more realistic example, one may be rendering user comments, blog articles, etc. via
  15338. * bindings. (HTML is just one example of a context where rendering user controlled input creates
  15339. * security vulnerabilities.)
  15340. *
  15341. * For the case of HTML, you might use a library, either on the client side, or on the server side,
  15342. * to sanitize unsafe HTML before binding to the value and rendering it in the document.
  15343. *
  15344. * How would you ensure that every place that used these types of bindings was bound to a value that
  15345. * was sanitized by your library (or returned as safe for rendering by your server?) How can you
  15346. * ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
  15347. * properties/fields and forgot to update the binding to the sanitized value?
  15348. *
  15349. * To be secure by default, you want to ensure that any such bindings are disallowed unless you can
  15350. * determine that something explicitly says it's safe to use a value for binding in that
  15351. * context. You can then audit your code (a simple grep would do) to ensure that this is only done
  15352. * for those values that you can easily tell are safe - because they were received from your server,
  15353. * sanitized by your library, etc. You can organize your codebase to help with this - perhaps
  15354. * allowing only the files in a specific directory to do this. Ensuring that the internal API
  15355. * exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
  15356. *
  15357. * In the case of AngularJS' SCE service, one uses {@link ng.$sce#trustAs $sce.trustAs}
  15358. * (and shorthand methods such as {@link ng.$sce#trustAsHtml $sce.trustAsHtml}, etc.) to
  15359. * obtain values that will be accepted by SCE / privileged contexts.
  15360. *
  15361. *
  15362. * ## How does it work?
  15363. *
  15364. * In privileged contexts, directives and code will bind to the result of {@link ng.$sce#getTrusted
  15365. * $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
  15366. * ng.$sce#parseAs $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
  15367. * {@link ng.$sce#getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
  15368. *
  15369. * As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
  15370. * ng.$sce#parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
  15371. * simplified):
  15372. *
  15373. * ```
  15374. * var ngBindHtmlDirective = ['$sce', function($sce) {
  15375. * return function(scope, element, attr) {
  15376. * scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
  15377. * element.html(value || '');
  15378. * });
  15379. * };
  15380. * }];
  15381. * ```
  15382. *
  15383. * ## Impact on loading templates
  15384. *
  15385. * This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
  15386. * `templateUrl`'s specified by {@link guide/directive directives}.
  15387. *
  15388. * By default, Angular only loads templates from the same domain and protocol as the application
  15389. * document. This is done by calling {@link ng.$sce#getTrustedResourceUrl
  15390. * $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
  15391. * protocols, you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist
  15392. * them} or {@link ng.$sce#trustAsResourceUrl wrap it} into a trusted value.
  15393. *
  15394. * *Please note*:
  15395. * The browser's
  15396. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  15397. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  15398. * policy apply in addition to this and may further restrict whether the template is successfully
  15399. * loaded. This means that without the right CORS policy, loading templates from a different domain
  15400. * won't work on all browsers. Also, loading templates from `file://` URL does not work on some
  15401. * browsers.
  15402. *
  15403. * ## This feels like too much overhead
  15404. *
  15405. * It's important to remember that SCE only applies to interpolation expressions.
  15406. *
  15407. * If your expressions are constant literals, they're automatically trusted and you don't need to
  15408. * call `$sce.trustAs` on them (remember to include the `ngSanitize` module) (e.g.
  15409. * `<div ng-bind-html="'<b>implicitly trusted</b>'"></div>`) just works.
  15410. *
  15411. * Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
  15412. * through {@link ng.$sce#getTrusted $sce.getTrusted}. SCE doesn't play a role here.
  15413. *
  15414. * The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
  15415. * templates in `ng-include` from your application's domain without having to even know about SCE.
  15416. * It blocks loading templates from other domains or loading templates over http from an https
  15417. * served document. You can change these by setting your own custom {@link
  15418. * ng.$sceDelegateProvider#resourceUrlWhitelist whitelists} and {@link
  15419. * ng.$sceDelegateProvider#resourceUrlBlacklist blacklists} for matching such URLs.
  15420. *
  15421. * This significantly reduces the overhead. It is far easier to pay the small overhead and have an
  15422. * application that's secure and can be audited to verify that with much more ease than bolting
  15423. * security onto an application later.
  15424. *
  15425. * <a name="contexts"></a>
  15426. * ## What trusted context types are supported?
  15427. *
  15428. * | Context | Notes |
  15429. * |---------------------|----------------|
  15430. * | `$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. |
  15431. * | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
  15432. * | `$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. |
  15433. * | `$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. |
  15434. * | `$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. |
  15435. *
  15436. * ## Format of items in {@link ng.$sceDelegateProvider#resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
  15437. *
  15438. * Each element in these arrays must be one of the following:
  15439. *
  15440. * - **'self'**
  15441. * - The special **string**, `'self'`, can be used to match against all URLs of the **same
  15442. * domain** as the application document using the **same protocol**.
  15443. * - **String** (except the special value `'self'`)
  15444. * - The string is matched against the full *normalized / absolute URL* of the resource
  15445. * being tested (substring matches are not good enough.)
  15446. * - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
  15447. * match themselves.
  15448. * - `*`: matches zero or more occurrences of any character other than one of the following 6
  15449. * characters: '`:`', '`/`', '`.`', '`?`', '`&`' and '`;`'. It's a useful wildcard for use
  15450. * in a whitelist.
  15451. * - `**`: matches zero or more occurrences of *any* character. As such, it's not
  15452. * appropriate for use in a scheme, domain, etc. as it would match too much. (e.g.
  15453. * http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
  15454. * not have been the intention.) Its usage at the very end of the path is ok. (e.g.
  15455. * http://foo.example.com/templates/**).
  15456. * - **RegExp** (*see caveat below*)
  15457. * - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
  15458. * (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
  15459. * accidentally introduce a bug when one updates a complex expression (imho, all regexes should
  15460. * have good test coverage). For instance, the use of `.` in the regex is correct only in a
  15461. * small number of cases. A `.` character in the regex used when matching the scheme or a
  15462. * subdomain could be matched against a `:` or literal `.` that was likely not intended. It
  15463. * is highly recommended to use the string patterns and only fall back to regular expressions
  15464. * as a last resort.
  15465. * - The regular expression must be an instance of RegExp (i.e. not a string.) It is
  15466. * matched against the **entire** *normalized / absolute URL* of the resource being tested
  15467. * (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
  15468. * present on the RegExp (such as multiline, global, ignoreCase) are ignored.
  15469. * - If you are generating your JavaScript from some other templating engine (not
  15470. * recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
  15471. * remember to escape your regular expression (and be aware that you might need more than
  15472. * one level of escaping depending on your templating engine and the way you interpolated
  15473. * the value.) Do make use of your platform's escaping mechanism as it might be good
  15474. * enough before coding your own. E.g. Ruby has
  15475. * [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
  15476. * and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
  15477. * Javascript lacks a similar built in function for escaping. Take a look at Google
  15478. * Closure library's [goog.string.regExpEscape(s)](
  15479. * http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
  15480. *
  15481. * Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
  15482. *
  15483. * ## Show me an example using SCE.
  15484. *
  15485. * <example module="mySceApp" deps="angular-sanitize.js">
  15486. * <file name="index.html">
  15487. * <div ng-controller="AppController as myCtrl">
  15488. * <i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
  15489. * <b>User comments</b><br>
  15490. * By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
  15491. * $sanitize is available. If $sanitize isn't available, this results in an error instead of an
  15492. * exploit.
  15493. * <div class="well">
  15494. * <div ng-repeat="userComment in myCtrl.userComments">
  15495. * <b>{{userComment.name}}</b>:
  15496. * <span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
  15497. * <br>
  15498. * </div>
  15499. * </div>
  15500. * </div>
  15501. * </file>
  15502. *
  15503. * <file name="script.js">
  15504. * angular.module('mySceApp', ['ngSanitize'])
  15505. * .controller('AppController', ['$http', '$templateCache', '$sce',
  15506. * function($http, $templateCache, $sce) {
  15507. * var self = this;
  15508. * $http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
  15509. * self.userComments = userComments;
  15510. * });
  15511. * self.explicitlyTrustedHtml = $sce.trustAsHtml(
  15512. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15513. * 'sanitization.&quot;">Hover over this text.</span>');
  15514. * }]);
  15515. * </file>
  15516. *
  15517. * <file name="test_data.json">
  15518. * [
  15519. * { "name": "Alice",
  15520. * "htmlComment":
  15521. * "<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
  15522. * },
  15523. * { "name": "Bob",
  15524. * "htmlComment": "<i>Yes!</i> Am I the only other one?"
  15525. * }
  15526. * ]
  15527. * </file>
  15528. *
  15529. * <file name="protractor.js" type="protractor">
  15530. * describe('SCE doc demo', function() {
  15531. * it('should sanitize untrusted values', function() {
  15532. * expect(element.all(by.css('.htmlComment')).first().getInnerHtml())
  15533. * .toBe('<span>Is <i>anyone</i> reading this?</span>');
  15534. * });
  15535. *
  15536. * it('should NOT sanitize explicitly trusted values', function() {
  15537. * expect(element(by.id('explicitlyTrustedHtml')).getInnerHtml()).toBe(
  15538. * '<span onmouseover="this.textContent=&quot;Explicitly trusted HTML bypasses ' +
  15539. * 'sanitization.&quot;">Hover over this text.</span>');
  15540. * });
  15541. * });
  15542. * </file>
  15543. * </example>
  15544. *
  15545. *
  15546. *
  15547. * ## Can I disable SCE completely?
  15548. *
  15549. * Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
  15550. * for little coding overhead. It will be much harder to take an SCE disabled application and
  15551. * either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
  15552. * for cases where you have a lot of existing code that was written before SCE was introduced and
  15553. * you're migrating them a module at a time.
  15554. *
  15555. * That said, here's how you can completely disable SCE:
  15556. *
  15557. * ```
  15558. * angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  15559. * // Completely disable SCE. For demonstration purposes only!
  15560. * // Do not use in new projects.
  15561. * $sceProvider.enabled(false);
  15562. * });
  15563. * ```
  15564. *
  15565. */
  15566. /* jshint maxlen: 100 */
  15567. function $SceProvider() {
  15568. var enabled = true;
  15569. /**
  15570. * @ngdoc method
  15571. * @name $sceProvider#enabled
  15572. * @kind function
  15573. *
  15574. * @param {boolean=} value If provided, then enables/disables SCE.
  15575. * @return {boolean} true if SCE is enabled, false otherwise.
  15576. *
  15577. * @description
  15578. * Enables/disables SCE and returns the current value.
  15579. */
  15580. this.enabled = function(value) {
  15581. if (arguments.length) {
  15582. enabled = !!value;
  15583. }
  15584. return enabled;
  15585. };
  15586. /* Design notes on the default implementation for SCE.
  15587. *
  15588. * The API contract for the SCE delegate
  15589. * -------------------------------------
  15590. * The SCE delegate object must provide the following 3 methods:
  15591. *
  15592. * - trustAs(contextEnum, value)
  15593. * This method is used to tell the SCE service that the provided value is OK to use in the
  15594. * contexts specified by contextEnum. It must return an object that will be accepted by
  15595. * getTrusted() for a compatible contextEnum and return this value.
  15596. *
  15597. * - valueOf(value)
  15598. * For values that were not produced by trustAs(), return them as is. For values that were
  15599. * produced by trustAs(), return the corresponding input value to trustAs. Basically, if
  15600. * trustAs is wrapping the given values into some type, this operation unwraps it when given
  15601. * such a value.
  15602. *
  15603. * - getTrusted(contextEnum, value)
  15604. * This function should return the a value that is safe to use in the context specified by
  15605. * contextEnum or throw and exception otherwise.
  15606. *
  15607. * NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
  15608. * opaque or wrapped in some holder object. That happens to be an implementation detail. For
  15609. * instance, an implementation could maintain a registry of all trusted objects by context. In
  15610. * such a case, trustAs() would return the same object that was passed in. getTrusted() would
  15611. * return the same object passed in if it was found in the registry under a compatible context or
  15612. * throw an exception otherwise. An implementation might only wrap values some of the time based
  15613. * on some criteria. getTrusted() might return a value and not throw an exception for special
  15614. * constants or objects even if not wrapped. All such implementations fulfill this contract.
  15615. *
  15616. *
  15617. * A note on the inheritance model for SCE contexts
  15618. * ------------------------------------------------
  15619. * I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
  15620. * is purely an implementation details.
  15621. *
  15622. * The contract is simply this:
  15623. *
  15624. * getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
  15625. * will also succeed.
  15626. *
  15627. * Inheritance happens to capture this in a natural way. In some future, we
  15628. * may not use inheritance anymore. That is OK because no code outside of
  15629. * sce.js and sceSpecs.js would need to be aware of this detail.
  15630. */
  15631. this.$get = ['$parse', '$sceDelegate', function(
  15632. $parse, $sceDelegate) {
  15633. // Prereq: Ensure that we're not running in IE<11 quirks mode. In that mode, IE < 11 allow
  15634. // the "expression(javascript expression)" syntax which is insecure.
  15635. if (enabled && msie < 8) {
  15636. throw $sceMinErr('iequirks',
  15637. 'Strict Contextual Escaping does not support Internet Explorer version < 11 in quirks ' +
  15638. 'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
  15639. 'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
  15640. }
  15641. var sce = shallowCopy(SCE_CONTEXTS);
  15642. /**
  15643. * @ngdoc method
  15644. * @name $sce#isEnabled
  15645. * @kind function
  15646. *
  15647. * @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
  15648. * have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
  15649. *
  15650. * @description
  15651. * Returns a boolean indicating if SCE is enabled.
  15652. */
  15653. sce.isEnabled = function() {
  15654. return enabled;
  15655. };
  15656. sce.trustAs = $sceDelegate.trustAs;
  15657. sce.getTrusted = $sceDelegate.getTrusted;
  15658. sce.valueOf = $sceDelegate.valueOf;
  15659. if (!enabled) {
  15660. sce.trustAs = sce.getTrusted = function(type, value) { return value; };
  15661. sce.valueOf = identity;
  15662. }
  15663. /**
  15664. * @ngdoc method
  15665. * @name $sce#parseAs
  15666. *
  15667. * @description
  15668. * Converts Angular {@link guide/expression expression} into a function. This is like {@link
  15669. * ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
  15670. * wraps the expression in a call to {@link ng.$sce#getTrusted $sce.getTrusted(*type*,
  15671. * *result*)}
  15672. *
  15673. * @param {string} type The kind of SCE context in which this result will be used.
  15674. * @param {string} expression String expression to compile.
  15675. * @returns {function(context, locals)} a function which represents the compiled expression:
  15676. *
  15677. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15678. * are evaluated against (typically a scope object).
  15679. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15680. * `context`.
  15681. */
  15682. sce.parseAs = function sceParseAs(type, expr) {
  15683. var parsed = $parse(expr);
  15684. if (parsed.literal && parsed.constant) {
  15685. return parsed;
  15686. } else {
  15687. return $parse(expr, function(value) {
  15688. return sce.getTrusted(type, value);
  15689. });
  15690. }
  15691. };
  15692. /**
  15693. * @ngdoc method
  15694. * @name $sce#trustAs
  15695. *
  15696. * @description
  15697. * Delegates to {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs`}. As such,
  15698. * returns an object that is trusted by angular for use in specified strict contextual
  15699. * escaping contexts (such as ng-bind-html, ng-include, any src attribute
  15700. * interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
  15701. * that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
  15702. * escaping.
  15703. *
  15704. * @param {string} type The kind of context in which this value is safe for use. e.g. url,
  15705. * resourceUrl, html, js and css.
  15706. * @param {*} value The value that that should be considered trusted/safe.
  15707. * @returns {*} A value that can be used to stand in for the provided `value` in places
  15708. * where Angular expects a $sce.trustAs() return value.
  15709. */
  15710. /**
  15711. * @ngdoc method
  15712. * @name $sce#trustAsHtml
  15713. *
  15714. * @description
  15715. * Shorthand method. `$sce.trustAsHtml(value)` →
  15716. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
  15717. *
  15718. * @param {*} value The value to trustAs.
  15719. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedHtml
  15720. * $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
  15721. * only accept expressions that are either literal constants or are the
  15722. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15723. */
  15724. /**
  15725. * @ngdoc method
  15726. * @name $sce#trustAsUrl
  15727. *
  15728. * @description
  15729. * Shorthand method. `$sce.trustAsUrl(value)` →
  15730. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.URL, value)`}
  15731. *
  15732. * @param {*} value The value to trustAs.
  15733. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedUrl
  15734. * $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
  15735. * only accept expressions that are either literal constants or are the
  15736. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15737. */
  15738. /**
  15739. * @ngdoc method
  15740. * @name $sce#trustAsResourceUrl
  15741. *
  15742. * @description
  15743. * Shorthand method. `$sce.trustAsResourceUrl(value)` →
  15744. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
  15745. *
  15746. * @param {*} value The value to trustAs.
  15747. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedResourceUrl
  15748. * $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
  15749. * only accept expressions that are either literal constants or are the return
  15750. * value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15751. */
  15752. /**
  15753. * @ngdoc method
  15754. * @name $sce#trustAsJs
  15755. *
  15756. * @description
  15757. * Shorthand method. `$sce.trustAsJs(value)` →
  15758. * {@link ng.$sceDelegate#trustAs `$sceDelegate.trustAs($sce.JS, value)`}
  15759. *
  15760. * @param {*} value The value to trustAs.
  15761. * @returns {*} An object that can be passed to {@link ng.$sce#getTrustedJs
  15762. * $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
  15763. * only accept expressions that are either literal constants or are the
  15764. * return value of {@link ng.$sce#trustAs $sce.trustAs}.)
  15765. */
  15766. /**
  15767. * @ngdoc method
  15768. * @name $sce#getTrusted
  15769. *
  15770. * @description
  15771. * Delegates to {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted`}. As such,
  15772. * takes the result of a {@link ng.$sce#trustAs `$sce.trustAs`}() call and returns the
  15773. * originally supplied value if the queried context type is a supertype of the created type.
  15774. * If this condition isn't satisfied, throws an exception.
  15775. *
  15776. * @param {string} type The kind of context in which this value is to be used.
  15777. * @param {*} maybeTrusted The result of a prior {@link ng.$sce#trustAs `$sce.trustAs`}
  15778. * call.
  15779. * @returns {*} The value the was originally provided to
  15780. * {@link ng.$sce#trustAs `$sce.trustAs`} if valid in this context.
  15781. * Otherwise, throws an exception.
  15782. */
  15783. /**
  15784. * @ngdoc method
  15785. * @name $sce#getTrustedHtml
  15786. *
  15787. * @description
  15788. * Shorthand method. `$sce.getTrustedHtml(value)` →
  15789. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
  15790. *
  15791. * @param {*} value The value to pass to `$sce.getTrusted`.
  15792. * @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
  15793. */
  15794. /**
  15795. * @ngdoc method
  15796. * @name $sce#getTrustedCss
  15797. *
  15798. * @description
  15799. * Shorthand method. `$sce.getTrustedCss(value)` →
  15800. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
  15801. *
  15802. * @param {*} value The value to pass to `$sce.getTrusted`.
  15803. * @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
  15804. */
  15805. /**
  15806. * @ngdoc method
  15807. * @name $sce#getTrustedUrl
  15808. *
  15809. * @description
  15810. * Shorthand method. `$sce.getTrustedUrl(value)` →
  15811. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
  15812. *
  15813. * @param {*} value The value to pass to `$sce.getTrusted`.
  15814. * @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
  15815. */
  15816. /**
  15817. * @ngdoc method
  15818. * @name $sce#getTrustedResourceUrl
  15819. *
  15820. * @description
  15821. * Shorthand method. `$sce.getTrustedResourceUrl(value)` →
  15822. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
  15823. *
  15824. * @param {*} value The value to pass to `$sceDelegate.getTrusted`.
  15825. * @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
  15826. */
  15827. /**
  15828. * @ngdoc method
  15829. * @name $sce#getTrustedJs
  15830. *
  15831. * @description
  15832. * Shorthand method. `$sce.getTrustedJs(value)` →
  15833. * {@link ng.$sceDelegate#getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
  15834. *
  15835. * @param {*} value The value to pass to `$sce.getTrusted`.
  15836. * @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
  15837. */
  15838. /**
  15839. * @ngdoc method
  15840. * @name $sce#parseAsHtml
  15841. *
  15842. * @description
  15843. * Shorthand method. `$sce.parseAsHtml(expression string)` →
  15844. * {@link ng.$sce#parseAs `$sce.parseAs($sce.HTML, value)`}
  15845. *
  15846. * @param {string} expression String expression to compile.
  15847. * @returns {function(context, locals)} a function which represents the compiled expression:
  15848. *
  15849. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15850. * are evaluated against (typically a scope object).
  15851. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15852. * `context`.
  15853. */
  15854. /**
  15855. * @ngdoc method
  15856. * @name $sce#parseAsCss
  15857. *
  15858. * @description
  15859. * Shorthand method. `$sce.parseAsCss(value)` →
  15860. * {@link ng.$sce#parseAs `$sce.parseAs($sce.CSS, value)`}
  15861. *
  15862. * @param {string} expression String expression to compile.
  15863. * @returns {function(context, locals)} a function which represents the compiled expression:
  15864. *
  15865. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15866. * are evaluated against (typically a scope object).
  15867. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15868. * `context`.
  15869. */
  15870. /**
  15871. * @ngdoc method
  15872. * @name $sce#parseAsUrl
  15873. *
  15874. * @description
  15875. * Shorthand method. `$sce.parseAsUrl(value)` →
  15876. * {@link ng.$sce#parseAs `$sce.parseAs($sce.URL, value)`}
  15877. *
  15878. * @param {string} expression String expression to compile.
  15879. * @returns {function(context, locals)} a function which represents the compiled expression:
  15880. *
  15881. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15882. * are evaluated against (typically a scope object).
  15883. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15884. * `context`.
  15885. */
  15886. /**
  15887. * @ngdoc method
  15888. * @name $sce#parseAsResourceUrl
  15889. *
  15890. * @description
  15891. * Shorthand method. `$sce.parseAsResourceUrl(value)` →
  15892. * {@link ng.$sce#parseAs `$sce.parseAs($sce.RESOURCE_URL, value)`}
  15893. *
  15894. * @param {string} expression String expression to compile.
  15895. * @returns {function(context, locals)} a function which represents the compiled expression:
  15896. *
  15897. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15898. * are evaluated against (typically a scope object).
  15899. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15900. * `context`.
  15901. */
  15902. /**
  15903. * @ngdoc method
  15904. * @name $sce#parseAsJs
  15905. *
  15906. * @description
  15907. * Shorthand method. `$sce.parseAsJs(value)` →
  15908. * {@link ng.$sce#parseAs `$sce.parseAs($sce.JS, value)`}
  15909. *
  15910. * @param {string} expression String expression to compile.
  15911. * @returns {function(context, locals)} a function which represents the compiled expression:
  15912. *
  15913. * * `context` – `{object}` – an object against which any expressions embedded in the strings
  15914. * are evaluated against (typically a scope object).
  15915. * * `locals` – `{object=}` – local variables context object, useful for overriding values in
  15916. * `context`.
  15917. */
  15918. // Shorthand delegations.
  15919. var parse = sce.parseAs,
  15920. getTrusted = sce.getTrusted,
  15921. trustAs = sce.trustAs;
  15922. forEach(SCE_CONTEXTS, function(enumValue, name) {
  15923. var lName = lowercase(name);
  15924. sce[camelCase("parse_as_" + lName)] = function(expr) {
  15925. return parse(enumValue, expr);
  15926. };
  15927. sce[camelCase("get_trusted_" + lName)] = function(value) {
  15928. return getTrusted(enumValue, value);
  15929. };
  15930. sce[camelCase("trust_as_" + lName)] = function(value) {
  15931. return trustAs(enumValue, value);
  15932. };
  15933. });
  15934. return sce;
  15935. }];
  15936. }
  15937. /**
  15938. * !!! This is an undocumented "private" service !!!
  15939. *
  15940. * @name $sniffer
  15941. * @requires $window
  15942. * @requires $document
  15943. *
  15944. * @property {boolean} history Does the browser support html5 history api ?
  15945. * @property {boolean} transitions Does the browser support CSS transition events ?
  15946. * @property {boolean} animations Does the browser support CSS animation events ?
  15947. *
  15948. * @description
  15949. * This is very simple implementation of testing browser's features.
  15950. */
  15951. function $SnifferProvider() {
  15952. this.$get = ['$window', '$document', function($window, $document) {
  15953. var eventSupport = {},
  15954. android =
  15955. toInt((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
  15956. boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
  15957. document = $document[0] || {},
  15958. vendorPrefix,
  15959. vendorRegex = /^(Moz|webkit|ms)(?=[A-Z])/,
  15960. bodyStyle = document.body && document.body.style,
  15961. transitions = false,
  15962. animations = false,
  15963. match;
  15964. if (bodyStyle) {
  15965. for (var prop in bodyStyle) {
  15966. if (match = vendorRegex.exec(prop)) {
  15967. vendorPrefix = match[0];
  15968. vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
  15969. break;
  15970. }
  15971. }
  15972. if (!vendorPrefix) {
  15973. vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
  15974. }
  15975. transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
  15976. animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
  15977. if (android && (!transitions || !animations)) {
  15978. transitions = isString(bodyStyle.webkitTransition);
  15979. animations = isString(bodyStyle.webkitAnimation);
  15980. }
  15981. }
  15982. return {
  15983. // Android has history.pushState, but it does not update location correctly
  15984. // so let's not use the history API at all.
  15985. // http://code.google.com/p/android/issues/detail?id=17471
  15986. // https://github.com/angular/angular.js/issues/904
  15987. // older webkit browser (533.9) on Boxee box has exactly the same problem as Android has
  15988. // so let's not use the history API also
  15989. // We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
  15990. // jshint -W018
  15991. history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
  15992. // jshint +W018
  15993. hasEvent: function(event) {
  15994. // IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
  15995. // it. In particular the event is not fired when backspace or delete key are pressed or
  15996. // when cut operation is performed.
  15997. // IE10+ implements 'input' event but it erroneously fires under various situations,
  15998. // e.g. when placeholder changes, or a form is focused.
  15999. if (event === 'input' && msie <= 11) return false;
  16000. if (isUndefined(eventSupport[event])) {
  16001. var divElm = document.createElement('div');
  16002. eventSupport[event] = 'on' + event in divElm;
  16003. }
  16004. return eventSupport[event];
  16005. },
  16006. csp: csp(),
  16007. vendorPrefix: vendorPrefix,
  16008. transitions: transitions,
  16009. animations: animations,
  16010. android: android
  16011. };
  16012. }];
  16013. }
  16014. var $compileMinErr = minErr('$compile');
  16015. /**
  16016. * @ngdoc service
  16017. * @name $templateRequest
  16018. *
  16019. * @description
  16020. * The `$templateRequest` service runs security checks then downloads the provided template using
  16021. * `$http` and, upon success, stores the contents inside of `$templateCache`. If the HTTP request
  16022. * fails or the response data of the HTTP request is empty, a `$compile` error will be thrown (the
  16023. * exception can be thwarted by setting the 2nd parameter of the function to true). Note that the
  16024. * contents of `$templateCache` are trusted, so the call to `$sce.getTrustedUrl(tpl)` is omitted
  16025. * when `tpl` is of type string and `$templateCache` has the matching entry.
  16026. *
  16027. * @param {string|TrustedResourceUrl} tpl The HTTP request template URL
  16028. * @param {boolean=} ignoreRequestError Whether or not to ignore the exception when the request fails or the template is empty
  16029. *
  16030. * @return {Promise} a promise for the HTTP response data of the given URL.
  16031. *
  16032. * @property {number} totalPendingRequests total amount of pending template requests being downloaded.
  16033. */
  16034. function $TemplateRequestProvider() {
  16035. this.$get = ['$templateCache', '$http', '$q', '$sce', function($templateCache, $http, $q, $sce) {
  16036. function handleRequestFn(tpl, ignoreRequestError) {
  16037. handleRequestFn.totalPendingRequests++;
  16038. // We consider the template cache holds only trusted templates, so
  16039. // there's no need to go through whitelisting again for keys that already
  16040. // are included in there. This also makes Angular accept any script
  16041. // directive, no matter its name. However, we still need to unwrap trusted
  16042. // types.
  16043. if (!isString(tpl) || !$templateCache.get(tpl)) {
  16044. tpl = $sce.getTrustedResourceUrl(tpl);
  16045. }
  16046. var transformResponse = $http.defaults && $http.defaults.transformResponse;
  16047. if (isArray(transformResponse)) {
  16048. transformResponse = transformResponse.filter(function(transformer) {
  16049. return transformer !== defaultHttpResponseTransform;
  16050. });
  16051. } else if (transformResponse === defaultHttpResponseTransform) {
  16052. transformResponse = null;
  16053. }
  16054. var httpOptions = {
  16055. cache: $templateCache,
  16056. transformResponse: transformResponse
  16057. };
  16058. return $http.get(tpl, httpOptions)
  16059. ['finally'](function() {
  16060. handleRequestFn.totalPendingRequests--;
  16061. })
  16062. .then(function(response) {
  16063. $templateCache.put(tpl, response.data);
  16064. return response.data;
  16065. }, handleError);
  16066. function handleError(resp) {
  16067. if (!ignoreRequestError) {
  16068. throw $compileMinErr('tpload', 'Failed to load template: {0} (HTTP status: {1} {2})',
  16069. tpl, resp.status, resp.statusText);
  16070. }
  16071. return $q.reject(resp);
  16072. }
  16073. }
  16074. handleRequestFn.totalPendingRequests = 0;
  16075. return handleRequestFn;
  16076. }];
  16077. }
  16078. function $$TestabilityProvider() {
  16079. this.$get = ['$rootScope', '$browser', '$location',
  16080. function($rootScope, $browser, $location) {
  16081. /**
  16082. * @name $testability
  16083. *
  16084. * @description
  16085. * The private $$testability service provides a collection of methods for use when debugging
  16086. * or by automated test and debugging tools.
  16087. */
  16088. var testability = {};
  16089. /**
  16090. * @name $$testability#findBindings
  16091. *
  16092. * @description
  16093. * Returns an array of elements that are bound (via ng-bind or {{}})
  16094. * to expressions matching the input.
  16095. *
  16096. * @param {Element} element The element root to search from.
  16097. * @param {string} expression The binding expression to match.
  16098. * @param {boolean} opt_exactMatch If true, only returns exact matches
  16099. * for the expression. Filters and whitespace are ignored.
  16100. */
  16101. testability.findBindings = function(element, expression, opt_exactMatch) {
  16102. var bindings = element.getElementsByClassName('ng-binding');
  16103. var matches = [];
  16104. forEach(bindings, function(binding) {
  16105. var dataBinding = angular.element(binding).data('$binding');
  16106. if (dataBinding) {
  16107. forEach(dataBinding, function(bindingName) {
  16108. if (opt_exactMatch) {
  16109. var matcher = new RegExp('(^|\\s)' + escapeForRegexp(expression) + '(\\s|\\||$)');
  16110. if (matcher.test(bindingName)) {
  16111. matches.push(binding);
  16112. }
  16113. } else {
  16114. if (bindingName.indexOf(expression) != -1) {
  16115. matches.push(binding);
  16116. }
  16117. }
  16118. });
  16119. }
  16120. });
  16121. return matches;
  16122. };
  16123. /**
  16124. * @name $$testability#findModels
  16125. *
  16126. * @description
  16127. * Returns an array of elements that are two-way found via ng-model to
  16128. * expressions matching the input.
  16129. *
  16130. * @param {Element} element The element root to search from.
  16131. * @param {string} expression The model expression to match.
  16132. * @param {boolean} opt_exactMatch If true, only returns exact matches
  16133. * for the expression.
  16134. */
  16135. testability.findModels = function(element, expression, opt_exactMatch) {
  16136. var prefixes = ['ng-', 'data-ng-', 'ng\\:'];
  16137. for (var p = 0; p < prefixes.length; ++p) {
  16138. var attributeEquals = opt_exactMatch ? '=' : '*=';
  16139. var selector = '[' + prefixes[p] + 'model' + attributeEquals + '"' + expression + '"]';
  16140. var elements = element.querySelectorAll(selector);
  16141. if (elements.length) {
  16142. return elements;
  16143. }
  16144. }
  16145. };
  16146. /**
  16147. * @name $$testability#getLocation
  16148. *
  16149. * @description
  16150. * Shortcut for getting the location in a browser agnostic way. Returns
  16151. * the path, search, and hash. (e.g. /path?a=b#hash)
  16152. */
  16153. testability.getLocation = function() {
  16154. return $location.url();
  16155. };
  16156. /**
  16157. * @name $$testability#setLocation
  16158. *
  16159. * @description
  16160. * Shortcut for navigating to a location without doing a full page reload.
  16161. *
  16162. * @param {string} url The location url (path, search and hash,
  16163. * e.g. /path?a=b#hash) to go to.
  16164. */
  16165. testability.setLocation = function(url) {
  16166. if (url !== $location.url()) {
  16167. $location.url(url);
  16168. $rootScope.$digest();
  16169. }
  16170. };
  16171. /**
  16172. * @name $$testability#whenStable
  16173. *
  16174. * @description
  16175. * Calls the callback when $timeout and $http requests are completed.
  16176. *
  16177. * @param {function} callback
  16178. */
  16179. testability.whenStable = function(callback) {
  16180. $browser.notifyWhenNoOutstandingRequests(callback);
  16181. };
  16182. return testability;
  16183. }];
  16184. }
  16185. function $TimeoutProvider() {
  16186. this.$get = ['$rootScope', '$browser', '$q', '$$q', '$exceptionHandler',
  16187. function($rootScope, $browser, $q, $$q, $exceptionHandler) {
  16188. var deferreds = {};
  16189. /**
  16190. * @ngdoc service
  16191. * @name $timeout
  16192. *
  16193. * @description
  16194. * Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
  16195. * block and delegates any exceptions to
  16196. * {@link ng.$exceptionHandler $exceptionHandler} service.
  16197. *
  16198. * The return value of calling `$timeout` is a promise, which will be resolved when
  16199. * the delay has passed and the timeout function, if provided, is executed.
  16200. *
  16201. * To cancel a timeout request, call `$timeout.cancel(promise)`.
  16202. *
  16203. * In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
  16204. * synchronously flush the queue of deferred functions.
  16205. *
  16206. * If you only want a promise that will be resolved after some specified delay
  16207. * then you can call `$timeout` without the `fn` function.
  16208. *
  16209. * @param {function()=} fn A function, whose execution should be delayed.
  16210. * @param {number=} [delay=0] Delay in milliseconds.
  16211. * @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
  16212. * will invoke `fn` within the {@link ng.$rootScope.Scope#$apply $apply} block.
  16213. * @param {...*=} Pass additional parameters to the executed function.
  16214. * @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
  16215. * promise will be resolved with is the return value of the `fn` function.
  16216. *
  16217. */
  16218. function timeout(fn, delay, invokeApply) {
  16219. if (!isFunction(fn)) {
  16220. invokeApply = delay;
  16221. delay = fn;
  16222. fn = noop;
  16223. }
  16224. var args = sliceArgs(arguments, 3),
  16225. skipApply = (isDefined(invokeApply) && !invokeApply),
  16226. deferred = (skipApply ? $$q : $q).defer(),
  16227. promise = deferred.promise,
  16228. timeoutId;
  16229. timeoutId = $browser.defer(function() {
  16230. try {
  16231. deferred.resolve(fn.apply(null, args));
  16232. } catch (e) {
  16233. deferred.reject(e);
  16234. $exceptionHandler(e);
  16235. }
  16236. finally {
  16237. delete deferreds[promise.$$timeoutId];
  16238. }
  16239. if (!skipApply) $rootScope.$apply();
  16240. }, delay);
  16241. promise.$$timeoutId = timeoutId;
  16242. deferreds[timeoutId] = deferred;
  16243. return promise;
  16244. }
  16245. /**
  16246. * @ngdoc method
  16247. * @name $timeout#cancel
  16248. *
  16249. * @description
  16250. * Cancels a task associated with the `promise`. As a result of this, the promise will be
  16251. * resolved with a rejection.
  16252. *
  16253. * @param {Promise=} promise Promise returned by the `$timeout` function.
  16254. * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
  16255. * canceled.
  16256. */
  16257. timeout.cancel = function(promise) {
  16258. if (promise && promise.$$timeoutId in deferreds) {
  16259. deferreds[promise.$$timeoutId].reject('canceled');
  16260. delete deferreds[promise.$$timeoutId];
  16261. return $browser.defer.cancel(promise.$$timeoutId);
  16262. }
  16263. return false;
  16264. };
  16265. return timeout;
  16266. }];
  16267. }
  16268. // NOTE: The usage of window and document instead of $window and $document here is
  16269. // deliberate. This service depends on the specific behavior of anchor nodes created by the
  16270. // browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
  16271. // cause us to break tests. In addition, when the browser resolves a URL for XHR, it
  16272. // doesn't know about mocked locations and resolves URLs to the real document - which is
  16273. // exactly the behavior needed here. There is little value is mocking these out for this
  16274. // service.
  16275. var urlParsingNode = document.createElement("a");
  16276. var originUrl = urlResolve(window.location.href);
  16277. /**
  16278. *
  16279. * Implementation Notes for non-IE browsers
  16280. * ----------------------------------------
  16281. * Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
  16282. * results both in the normalizing and parsing of the URL. Normalizing means that a relative
  16283. * URL will be resolved into an absolute URL in the context of the application document.
  16284. * Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
  16285. * properties are all populated to reflect the normalized URL. This approach has wide
  16286. * compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
  16287. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16288. *
  16289. * Implementation Notes for IE
  16290. * ---------------------------
  16291. * IE <= 10 normalizes the URL when assigned to the anchor node similar to the other
  16292. * browsers. However, the parsed components will not be set if the URL assigned did not specify
  16293. * them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
  16294. * work around that by performing the parsing in a 2nd step by taking a previously normalized
  16295. * URL (e.g. by assigning to a.href) and assigning it a.href again. This correctly populates the
  16296. * properties such as protocol, hostname, port, etc.
  16297. *
  16298. * References:
  16299. * http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
  16300. * http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
  16301. * http://url.spec.whatwg.org/#urlutils
  16302. * https://github.com/angular/angular.js/pull/2902
  16303. * http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
  16304. *
  16305. * @kind function
  16306. * @param {string} url The URL to be parsed.
  16307. * @description Normalizes and parses a URL.
  16308. * @returns {object} Returns the normalized URL as a dictionary.
  16309. *
  16310. * | member name | Description |
  16311. * |---------------|----------------|
  16312. * | href | A normalized version of the provided URL if it was not an absolute URL |
  16313. * | protocol | The protocol including the trailing colon |
  16314. * | host | The host and port (if the port is non-default) of the normalizedUrl |
  16315. * | search | The search params, minus the question mark |
  16316. * | hash | The hash string, minus the hash symbol
  16317. * | hostname | The hostname
  16318. * | port | The port, without ":"
  16319. * | pathname | The pathname, beginning with "/"
  16320. *
  16321. */
  16322. function urlResolve(url) {
  16323. var href = url;
  16324. if (msie) {
  16325. // Normalize before parse. Refer Implementation Notes on why this is
  16326. // done in two steps on IE.
  16327. urlParsingNode.setAttribute("href", href);
  16328. href = urlParsingNode.href;
  16329. }
  16330. urlParsingNode.setAttribute('href', href);
  16331. // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
  16332. return {
  16333. href: urlParsingNode.href,
  16334. protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
  16335. host: urlParsingNode.host,
  16336. search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
  16337. hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
  16338. hostname: urlParsingNode.hostname,
  16339. port: urlParsingNode.port,
  16340. pathname: (urlParsingNode.pathname.charAt(0) === '/')
  16341. ? urlParsingNode.pathname
  16342. : '/' + urlParsingNode.pathname
  16343. };
  16344. }
  16345. /**
  16346. * Parse a request URL and determine whether this is a same-origin request as the application document.
  16347. *
  16348. * @param {string|object} requestUrl The url of the request as a string that will be resolved
  16349. * or a parsed URL object.
  16350. * @returns {boolean} Whether the request is for the same origin as the application document.
  16351. */
  16352. function urlIsSameOrigin(requestUrl) {
  16353. var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
  16354. return (parsed.protocol === originUrl.protocol &&
  16355. parsed.host === originUrl.host);
  16356. }
  16357. /**
  16358. * @ngdoc service
  16359. * @name $window
  16360. *
  16361. * @description
  16362. * A reference to the browser's `window` object. While `window`
  16363. * is globally available in JavaScript, it causes testability problems, because
  16364. * it is a global variable. In angular we always refer to it through the
  16365. * `$window` service, so it may be overridden, removed or mocked for testing.
  16366. *
  16367. * Expressions, like the one defined for the `ngClick` directive in the example
  16368. * below, are evaluated with respect to the current scope. Therefore, there is
  16369. * no risk of inadvertently coding in a dependency on a global value in such an
  16370. * expression.
  16371. *
  16372. * @example
  16373. <example module="windowExample">
  16374. <file name="index.html">
  16375. <script>
  16376. angular.module('windowExample', [])
  16377. .controller('ExampleController', ['$scope', '$window', function($scope, $window) {
  16378. $scope.greeting = 'Hello, World!';
  16379. $scope.doGreeting = function(greeting) {
  16380. $window.alert(greeting);
  16381. };
  16382. }]);
  16383. </script>
  16384. <div ng-controller="ExampleController">
  16385. <input type="text" ng-model="greeting" aria-label="greeting" />
  16386. <button ng-click="doGreeting(greeting)">ALERT</button>
  16387. </div>
  16388. </file>
  16389. <file name="protractor.js" type="protractor">
  16390. it('should display the greeting in the input box', function() {
  16391. element(by.model('greeting')).sendKeys('Hello, E2E Tests');
  16392. // If we click the button it will block the test runner
  16393. // element(':button').click();
  16394. });
  16395. </file>
  16396. </example>
  16397. */
  16398. function $WindowProvider() {
  16399. this.$get = valueFn(window);
  16400. }
  16401. /**
  16402. * @name $$cookieReader
  16403. * @requires $document
  16404. *
  16405. * @description
  16406. * This is a private service for reading cookies used by $http and ngCookies
  16407. *
  16408. * @return {Object} a key/value map of the current cookies
  16409. */
  16410. function $$CookieReader($document) {
  16411. var rawDocument = $document[0] || {};
  16412. var lastCookies = {};
  16413. var lastCookieString = '';
  16414. function safeDecodeURIComponent(str) {
  16415. try {
  16416. return decodeURIComponent(str);
  16417. } catch (e) {
  16418. return str;
  16419. }
  16420. }
  16421. return function() {
  16422. var cookieArray, cookie, i, index, name;
  16423. var currentCookieString = rawDocument.cookie || '';
  16424. if (currentCookieString !== lastCookieString) {
  16425. lastCookieString = currentCookieString;
  16426. cookieArray = lastCookieString.split('; ');
  16427. lastCookies = {};
  16428. for (i = 0; i < cookieArray.length; i++) {
  16429. cookie = cookieArray[i];
  16430. index = cookie.indexOf('=');
  16431. if (index > 0) { //ignore nameless cookies
  16432. name = safeDecodeURIComponent(cookie.substring(0, index));
  16433. // the first value that is seen for a cookie is the most
  16434. // specific one. values for the same cookie name that
  16435. // follow are for less specific paths.
  16436. if (isUndefined(lastCookies[name])) {
  16437. lastCookies[name] = safeDecodeURIComponent(cookie.substring(index + 1));
  16438. }
  16439. }
  16440. }
  16441. }
  16442. return lastCookies;
  16443. };
  16444. }
  16445. $$CookieReader.$inject = ['$document'];
  16446. function $$CookieReaderProvider() {
  16447. this.$get = $$CookieReader;
  16448. }
  16449. /* global currencyFilter: true,
  16450. dateFilter: true,
  16451. filterFilter: true,
  16452. jsonFilter: true,
  16453. limitToFilter: true,
  16454. lowercaseFilter: true,
  16455. numberFilter: true,
  16456. orderByFilter: true,
  16457. uppercaseFilter: true,
  16458. */
  16459. /**
  16460. * @ngdoc provider
  16461. * @name $filterProvider
  16462. * @description
  16463. *
  16464. * Filters are just functions which transform input to an output. However filters need to be
  16465. * Dependency Injected. To achieve this a filter definition consists of a factory function which is
  16466. * annotated with dependencies and is responsible for creating a filter function.
  16467. *
  16468. * <div class="alert alert-warning">
  16469. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16470. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16471. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16472. * (`myapp_subsection_filterx`).
  16473. * </div>
  16474. *
  16475. * ```js
  16476. * // Filter registration
  16477. * function MyModule($provide, $filterProvider) {
  16478. * // create a service to demonstrate injection (not always needed)
  16479. * $provide.value('greet', function(name){
  16480. * return 'Hello ' + name + '!';
  16481. * });
  16482. *
  16483. * // register a filter factory which uses the
  16484. * // greet service to demonstrate DI.
  16485. * $filterProvider.register('greet', function(greet){
  16486. * // return the filter function which uses the greet service
  16487. * // to generate salutation
  16488. * return function(text) {
  16489. * // filters need to be forgiving so check input validity
  16490. * return text && greet(text) || text;
  16491. * };
  16492. * });
  16493. * }
  16494. * ```
  16495. *
  16496. * The filter function is registered with the `$injector` under the filter name suffix with
  16497. * `Filter`.
  16498. *
  16499. * ```js
  16500. * it('should be the same instance', inject(
  16501. * function($filterProvider) {
  16502. * $filterProvider.register('reverse', function(){
  16503. * return ...;
  16504. * });
  16505. * },
  16506. * function($filter, reverseFilter) {
  16507. * expect($filter('reverse')).toBe(reverseFilter);
  16508. * });
  16509. * ```
  16510. *
  16511. *
  16512. * For more information about how angular filters work, and how to create your own filters, see
  16513. * {@link guide/filter Filters} in the Angular Developer Guide.
  16514. */
  16515. /**
  16516. * @ngdoc service
  16517. * @name $filter
  16518. * @kind function
  16519. * @description
  16520. * Filters are used for formatting data displayed to the user.
  16521. *
  16522. * The general syntax in templates is as follows:
  16523. *
  16524. * {{ expression [| filter_name[:parameter_value] ... ] }}
  16525. *
  16526. * @param {String} name Name of the filter function to retrieve
  16527. * @return {Function} the filter function
  16528. * @example
  16529. <example name="$filter" module="filterExample">
  16530. <file name="index.html">
  16531. <div ng-controller="MainCtrl">
  16532. <h3>{{ originalText }}</h3>
  16533. <h3>{{ filteredText }}</h3>
  16534. </div>
  16535. </file>
  16536. <file name="script.js">
  16537. angular.module('filterExample', [])
  16538. .controller('MainCtrl', function($scope, $filter) {
  16539. $scope.originalText = 'hello';
  16540. $scope.filteredText = $filter('uppercase')($scope.originalText);
  16541. });
  16542. </file>
  16543. </example>
  16544. */
  16545. $FilterProvider.$inject = ['$provide'];
  16546. function $FilterProvider($provide) {
  16547. var suffix = 'Filter';
  16548. /**
  16549. * @ngdoc method
  16550. * @name $filterProvider#register
  16551. * @param {string|Object} name Name of the filter function, or an object map of filters where
  16552. * the keys are the filter names and the values are the filter factories.
  16553. *
  16554. * <div class="alert alert-warning">
  16555. * **Note:** Filter names must be valid angular {@link expression} identifiers, such as `uppercase` or `orderBy`.
  16556. * Names with special characters, such as hyphens and dots, are not allowed. If you wish to namespace
  16557. * your filters, then you can use capitalization (`myappSubsectionFilterx`) or underscores
  16558. * (`myapp_subsection_filterx`).
  16559. * </div>
  16560. * @param {Function} factory If the first argument was a string, a factory function for the filter to be registered.
  16561. * @returns {Object} Registered filter instance, or if a map of filters was provided then a map
  16562. * of the registered filter instances.
  16563. */
  16564. function register(name, factory) {
  16565. if (isObject(name)) {
  16566. var filters = {};
  16567. forEach(name, function(filter, key) {
  16568. filters[key] = register(key, filter);
  16569. });
  16570. return filters;
  16571. } else {
  16572. return $provide.factory(name + suffix, factory);
  16573. }
  16574. }
  16575. this.register = register;
  16576. this.$get = ['$injector', function($injector) {
  16577. return function(name) {
  16578. return $injector.get(name + suffix);
  16579. };
  16580. }];
  16581. ////////////////////////////////////////
  16582. /* global
  16583. currencyFilter: false,
  16584. dateFilter: false,
  16585. filterFilter: false,
  16586. jsonFilter: false,
  16587. limitToFilter: false,
  16588. lowercaseFilter: false,
  16589. numberFilter: false,
  16590. orderByFilter: false,
  16591. uppercaseFilter: false,
  16592. */
  16593. register('currency', currencyFilter);
  16594. register('date', dateFilter);
  16595. register('filter', filterFilter);
  16596. register('json', jsonFilter);
  16597. register('limitTo', limitToFilter);
  16598. register('lowercase', lowercaseFilter);
  16599. register('number', numberFilter);
  16600. register('orderBy', orderByFilter);
  16601. register('uppercase', uppercaseFilter);
  16602. }
  16603. /**
  16604. * @ngdoc filter
  16605. * @name filter
  16606. * @kind function
  16607. *
  16608. * @description
  16609. * Selects a subset of items from `array` and returns it as a new array.
  16610. *
  16611. * @param {Array} array The source array.
  16612. * @param {string|Object|function()} expression The predicate to be used for selecting items from
  16613. * `array`.
  16614. *
  16615. * Can be one of:
  16616. *
  16617. * - `string`: The string is used for matching against the contents of the `array`. All strings or
  16618. * objects with string properties in `array` that match this string will be returned. This also
  16619. * applies to nested object properties.
  16620. * The predicate can be negated by prefixing the string with `!`.
  16621. *
  16622. * - `Object`: A pattern object can be used to filter specific properties on objects contained
  16623. * by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
  16624. * which have property `name` containing "M" and property `phone` containing "1". A special
  16625. * property name `$` can be used (as in `{$:"text"}`) to accept a match against any
  16626. * property of the object or its nested object properties. That's equivalent to the simple
  16627. * substring match with a `string` as described above. The predicate can be negated by prefixing
  16628. * the string with `!`.
  16629. * For example `{name: "!M"}` predicate will return an array of items which have property `name`
  16630. * not containing "M".
  16631. *
  16632. * Note that a named property will match properties on the same level only, while the special
  16633. * `$` property will match properties on the same level or deeper. E.g. an array item like
  16634. * `{name: {first: 'John', last: 'Doe'}}` will **not** be matched by `{name: 'John'}`, but
  16635. * **will** be matched by `{$: 'John'}`.
  16636. *
  16637. * - `function(value, index, array)`: A predicate function can be used to write arbitrary filters.
  16638. * The function is called for each element of the array, with the element, its index, and
  16639. * the entire array itself as arguments.
  16640. *
  16641. * The final result is an array of those elements that the predicate returned true for.
  16642. *
  16643. * @param {function(actual, expected)|true|undefined} comparator Comparator which is used in
  16644. * determining if the expected value (from the filter expression) and actual value (from
  16645. * the object in the array) should be considered a match.
  16646. *
  16647. * Can be one of:
  16648. *
  16649. * - `function(actual, expected)`:
  16650. * The function will be given the object value and the predicate value to compare and
  16651. * should return true if both values should be considered equal.
  16652. *
  16653. * - `true`: A shorthand for `function(actual, expected) { return angular.equals(actual, expected)}`.
  16654. * This is essentially strict comparison of expected and actual.
  16655. *
  16656. * - `false|undefined`: A short hand for a function which will look for a substring match in case
  16657. * insensitive way.
  16658. *
  16659. * Primitive values are converted to strings. Objects are not compared against primitives,
  16660. * unless they have a custom `toString` method (e.g. `Date` objects).
  16661. *
  16662. * @example
  16663. <example>
  16664. <file name="index.html">
  16665. <div ng-init="friends = [{name:'John', phone:'555-1276'},
  16666. {name:'Mary', phone:'800-BIG-MARY'},
  16667. {name:'Mike', phone:'555-4321'},
  16668. {name:'Adam', phone:'555-5678'},
  16669. {name:'Julie', phone:'555-8765'},
  16670. {name:'Juliette', phone:'555-5678'}]"></div>
  16671. <label>Search: <input ng-model="searchText"></label>
  16672. <table id="searchTextResults">
  16673. <tr><th>Name</th><th>Phone</th></tr>
  16674. <tr ng-repeat="friend in friends | filter:searchText">
  16675. <td>{{friend.name}}</td>
  16676. <td>{{friend.phone}}</td>
  16677. </tr>
  16678. </table>
  16679. <hr>
  16680. <label>Any: <input ng-model="search.$"></label> <br>
  16681. <label>Name only <input ng-model="search.name"></label><br>
  16682. <label>Phone only <input ng-model="search.phone"></label><br>
  16683. <label>Equality <input type="checkbox" ng-model="strict"></label><br>
  16684. <table id="searchObjResults">
  16685. <tr><th>Name</th><th>Phone</th></tr>
  16686. <tr ng-repeat="friendObj in friends | filter:search:strict">
  16687. <td>{{friendObj.name}}</td>
  16688. <td>{{friendObj.phone}}</td>
  16689. </tr>
  16690. </table>
  16691. </file>
  16692. <file name="protractor.js" type="protractor">
  16693. var expectFriendNames = function(expectedNames, key) {
  16694. element.all(by.repeater(key + ' in friends').column(key + '.name')).then(function(arr) {
  16695. arr.forEach(function(wd, i) {
  16696. expect(wd.getText()).toMatch(expectedNames[i]);
  16697. });
  16698. });
  16699. };
  16700. it('should search across all fields when filtering with a string', function() {
  16701. var searchText = element(by.model('searchText'));
  16702. searchText.clear();
  16703. searchText.sendKeys('m');
  16704. expectFriendNames(['Mary', 'Mike', 'Adam'], 'friend');
  16705. searchText.clear();
  16706. searchText.sendKeys('76');
  16707. expectFriendNames(['John', 'Julie'], 'friend');
  16708. });
  16709. it('should search in specific fields when filtering with a predicate object', function() {
  16710. var searchAny = element(by.model('search.$'));
  16711. searchAny.clear();
  16712. searchAny.sendKeys('i');
  16713. expectFriendNames(['Mary', 'Mike', 'Julie', 'Juliette'], 'friendObj');
  16714. });
  16715. it('should use a equal comparison when comparator is true', function() {
  16716. var searchName = element(by.model('search.name'));
  16717. var strict = element(by.model('strict'));
  16718. searchName.clear();
  16719. searchName.sendKeys('Julie');
  16720. strict.click();
  16721. expectFriendNames(['Julie'], 'friendObj');
  16722. });
  16723. </file>
  16724. </example>
  16725. */
  16726. function filterFilter() {
  16727. return function(array, expression, comparator) {
  16728. if (!isArrayLike(array)) {
  16729. if (array == null) {
  16730. return array;
  16731. } else {
  16732. throw minErr('filter')('notarray', 'Expected array but received: {0}', array);
  16733. }
  16734. }
  16735. var expressionType = getTypeForFilter(expression);
  16736. var predicateFn;
  16737. var matchAgainstAnyProp;
  16738. switch (expressionType) {
  16739. case 'function':
  16740. predicateFn = expression;
  16741. break;
  16742. case 'boolean':
  16743. case 'null':
  16744. case 'number':
  16745. case 'string':
  16746. matchAgainstAnyProp = true;
  16747. //jshint -W086
  16748. case 'object':
  16749. //jshint +W086
  16750. predicateFn = createPredicateFn(expression, comparator, matchAgainstAnyProp);
  16751. break;
  16752. default:
  16753. return array;
  16754. }
  16755. return Array.prototype.filter.call(array, predicateFn);
  16756. };
  16757. }
  16758. // Helper functions for `filterFilter`
  16759. function createPredicateFn(expression, comparator, matchAgainstAnyProp) {
  16760. var shouldMatchPrimitives = isObject(expression) && ('$' in expression);
  16761. var predicateFn;
  16762. if (comparator === true) {
  16763. comparator = equals;
  16764. } else if (!isFunction(comparator)) {
  16765. comparator = function(actual, expected) {
  16766. if (isUndefined(actual)) {
  16767. // No substring matching against `undefined`
  16768. return false;
  16769. }
  16770. if ((actual === null) || (expected === null)) {
  16771. // No substring matching against `null`; only match against `null`
  16772. return actual === expected;
  16773. }
  16774. if (isObject(expected) || (isObject(actual) && !hasCustomToString(actual))) {
  16775. // Should not compare primitives against objects, unless they have custom `toString` method
  16776. return false;
  16777. }
  16778. actual = lowercase('' + actual);
  16779. expected = lowercase('' + expected);
  16780. return actual.indexOf(expected) !== -1;
  16781. };
  16782. }
  16783. predicateFn = function(item) {
  16784. if (shouldMatchPrimitives && !isObject(item)) {
  16785. return deepCompare(item, expression.$, comparator, false);
  16786. }
  16787. return deepCompare(item, expression, comparator, matchAgainstAnyProp);
  16788. };
  16789. return predicateFn;
  16790. }
  16791. function deepCompare(actual, expected, comparator, matchAgainstAnyProp, dontMatchWholeObject) {
  16792. var actualType = getTypeForFilter(actual);
  16793. var expectedType = getTypeForFilter(expected);
  16794. if ((expectedType === 'string') && (expected.charAt(0) === '!')) {
  16795. return !deepCompare(actual, expected.substring(1), comparator, matchAgainstAnyProp);
  16796. } else if (isArray(actual)) {
  16797. // In case `actual` is an array, consider it a match
  16798. // if ANY of it's items matches `expected`
  16799. return actual.some(function(item) {
  16800. return deepCompare(item, expected, comparator, matchAgainstAnyProp);
  16801. });
  16802. }
  16803. switch (actualType) {
  16804. case 'object':
  16805. var key;
  16806. if (matchAgainstAnyProp) {
  16807. for (key in actual) {
  16808. if ((key.charAt(0) !== '$') && deepCompare(actual[key], expected, comparator, true)) {
  16809. return true;
  16810. }
  16811. }
  16812. return dontMatchWholeObject ? false : deepCompare(actual, expected, comparator, false);
  16813. } else if (expectedType === 'object') {
  16814. for (key in expected) {
  16815. var expectedVal = expected[key];
  16816. if (isFunction(expectedVal) || isUndefined(expectedVal)) {
  16817. continue;
  16818. }
  16819. var matchAnyProperty = key === '$';
  16820. var actualVal = matchAnyProperty ? actual : actual[key];
  16821. if (!deepCompare(actualVal, expectedVal, comparator, matchAnyProperty, matchAnyProperty)) {
  16822. return false;
  16823. }
  16824. }
  16825. return true;
  16826. } else {
  16827. return comparator(actual, expected);
  16828. }
  16829. break;
  16830. case 'function':
  16831. return false;
  16832. default:
  16833. return comparator(actual, expected);
  16834. }
  16835. }
  16836. // Used for easily differentiating between `null` and actual `object`
  16837. function getTypeForFilter(val) {
  16838. return (val === null) ? 'null' : typeof val;
  16839. }
  16840. /**
  16841. * @ngdoc filter
  16842. * @name currency
  16843. * @kind function
  16844. *
  16845. * @description
  16846. * Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
  16847. * symbol for current locale is used.
  16848. *
  16849. * @param {number} amount Input to filter.
  16850. * @param {string=} symbol Currency symbol or identifier to be displayed.
  16851. * @param {number=} fractionSize Number of decimal places to round the amount to, defaults to default max fraction size for current locale
  16852. * @returns {string} Formatted number.
  16853. *
  16854. *
  16855. * @example
  16856. <example module="currencyExample">
  16857. <file name="index.html">
  16858. <script>
  16859. angular.module('currencyExample', [])
  16860. .controller('ExampleController', ['$scope', function($scope) {
  16861. $scope.amount = 1234.56;
  16862. }]);
  16863. </script>
  16864. <div ng-controller="ExampleController">
  16865. <input type="number" ng-model="amount" aria-label="amount"> <br>
  16866. default currency symbol ($): <span id="currency-default">{{amount | currency}}</span><br>
  16867. custom currency identifier (USD$): <span id="currency-custom">{{amount | currency:"USD$"}}</span>
  16868. no fractions (0): <span id="currency-no-fractions">{{amount | currency:"USD$":0}}</span>
  16869. </div>
  16870. </file>
  16871. <file name="protractor.js" type="protractor">
  16872. it('should init with 1234.56', function() {
  16873. expect(element(by.id('currency-default')).getText()).toBe('$1,234.56');
  16874. expect(element(by.id('currency-custom')).getText()).toBe('USD$1,234.56');
  16875. expect(element(by.id('currency-no-fractions')).getText()).toBe('USD$1,235');
  16876. });
  16877. it('should update', function() {
  16878. if (browser.params.browser == 'safari') {
  16879. // Safari does not understand the minus key. See
  16880. // https://github.com/angular/protractor/issues/481
  16881. return;
  16882. }
  16883. element(by.model('amount')).clear();
  16884. element(by.model('amount')).sendKeys('-1234');
  16885. expect(element(by.id('currency-default')).getText()).toBe('-$1,234.00');
  16886. expect(element(by.id('currency-custom')).getText()).toBe('-USD$1,234.00');
  16887. expect(element(by.id('currency-no-fractions')).getText()).toBe('-USD$1,234');
  16888. });
  16889. </file>
  16890. </example>
  16891. */
  16892. currencyFilter.$inject = ['$locale'];
  16893. function currencyFilter($locale) {
  16894. var formats = $locale.NUMBER_FORMATS;
  16895. return function(amount, currencySymbol, fractionSize) {
  16896. if (isUndefined(currencySymbol)) {
  16897. currencySymbol = formats.CURRENCY_SYM;
  16898. }
  16899. if (isUndefined(fractionSize)) {
  16900. fractionSize = formats.PATTERNS[1].maxFrac;
  16901. }
  16902. // if null or undefined pass it through
  16903. return (amount == null)
  16904. ? amount
  16905. : formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, fractionSize).
  16906. replace(/\u00A4/g, currencySymbol);
  16907. };
  16908. }
  16909. /**
  16910. * @ngdoc filter
  16911. * @name number
  16912. * @kind function
  16913. *
  16914. * @description
  16915. * Formats a number as text.
  16916. *
  16917. * If the input is null or undefined, it will just be returned.
  16918. * If the input is infinite (Infinity/-Infinity) the Infinity symbol '∞' is returned.
  16919. * If the input is not a number an empty string is returned.
  16920. *
  16921. *
  16922. * @param {number|string} number Number to format.
  16923. * @param {(number|string)=} fractionSize Number of decimal places to round the number to.
  16924. * If this is not provided then the fraction size is computed from the current locale's number
  16925. * formatting pattern. In the case of the default locale, it will be 3.
  16926. * @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
  16927. *
  16928. * @example
  16929. <example module="numberFilterExample">
  16930. <file name="index.html">
  16931. <script>
  16932. angular.module('numberFilterExample', [])
  16933. .controller('ExampleController', ['$scope', function($scope) {
  16934. $scope.val = 1234.56789;
  16935. }]);
  16936. </script>
  16937. <div ng-controller="ExampleController">
  16938. <label>Enter number: <input ng-model='val'></label><br>
  16939. Default formatting: <span id='number-default'>{{val | number}}</span><br>
  16940. No fractions: <span>{{val | number:0}}</span><br>
  16941. Negative number: <span>{{-val | number:4}}</span>
  16942. </div>
  16943. </file>
  16944. <file name="protractor.js" type="protractor">
  16945. it('should format numbers', function() {
  16946. expect(element(by.id('number-default')).getText()).toBe('1,234.568');
  16947. expect(element(by.binding('val | number:0')).getText()).toBe('1,235');
  16948. expect(element(by.binding('-val | number:4')).getText()).toBe('-1,234.5679');
  16949. });
  16950. it('should update', function() {
  16951. element(by.model('val')).clear();
  16952. element(by.model('val')).sendKeys('3374.333');
  16953. expect(element(by.id('number-default')).getText()).toBe('3,374.333');
  16954. expect(element(by.binding('val | number:0')).getText()).toBe('3,374');
  16955. expect(element(by.binding('-val | number:4')).getText()).toBe('-3,374.3330');
  16956. });
  16957. </file>
  16958. </example>
  16959. */
  16960. numberFilter.$inject = ['$locale'];
  16961. function numberFilter($locale) {
  16962. var formats = $locale.NUMBER_FORMATS;
  16963. return function(number, fractionSize) {
  16964. // if null or undefined pass it through
  16965. return (number == null)
  16966. ? number
  16967. : formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
  16968. fractionSize);
  16969. };
  16970. }
  16971. var DECIMAL_SEP = '.';
  16972. function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
  16973. if (isObject(number)) return '';
  16974. var isNegative = number < 0;
  16975. number = Math.abs(number);
  16976. var isInfinity = number === Infinity;
  16977. if (!isInfinity && !isFinite(number)) return '';
  16978. var numStr = number + '',
  16979. formatedText = '',
  16980. hasExponent = false,
  16981. parts = [];
  16982. if (isInfinity) formatedText = '\u221e';
  16983. if (!isInfinity && numStr.indexOf('e') !== -1) {
  16984. var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
  16985. if (match && match[2] == '-' && match[3] > fractionSize + 1) {
  16986. number = 0;
  16987. } else {
  16988. formatedText = numStr;
  16989. hasExponent = true;
  16990. }
  16991. }
  16992. if (!isInfinity && !hasExponent) {
  16993. var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
  16994. // determine fractionSize if it is not specified
  16995. if (isUndefined(fractionSize)) {
  16996. fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
  16997. }
  16998. // safely round numbers in JS without hitting imprecisions of floating-point arithmetics
  16999. // inspired by:
  17000. // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round
  17001. number = +(Math.round(+(number.toString() + 'e' + fractionSize)).toString() + 'e' + -fractionSize);
  17002. var fraction = ('' + number).split(DECIMAL_SEP);
  17003. var whole = fraction[0];
  17004. fraction = fraction[1] || '';
  17005. var i, pos = 0,
  17006. lgroup = pattern.lgSize,
  17007. group = pattern.gSize;
  17008. if (whole.length >= (lgroup + group)) {
  17009. pos = whole.length - lgroup;
  17010. for (i = 0; i < pos; i++) {
  17011. if ((pos - i) % group === 0 && i !== 0) {
  17012. formatedText += groupSep;
  17013. }
  17014. formatedText += whole.charAt(i);
  17015. }
  17016. }
  17017. for (i = pos; i < whole.length; i++) {
  17018. if ((whole.length - i) % lgroup === 0 && i !== 0) {
  17019. formatedText += groupSep;
  17020. }
  17021. formatedText += whole.charAt(i);
  17022. }
  17023. // format fraction part.
  17024. while (fraction.length < fractionSize) {
  17025. fraction += '0';
  17026. }
  17027. if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
  17028. } else {
  17029. if (fractionSize > 0 && number < 1) {
  17030. formatedText = number.toFixed(fractionSize);
  17031. number = parseFloat(formatedText);
  17032. formatedText = formatedText.replace(DECIMAL_SEP, decimalSep);
  17033. }
  17034. }
  17035. if (number === 0) {
  17036. isNegative = false;
  17037. }
  17038. parts.push(isNegative ? pattern.negPre : pattern.posPre,
  17039. formatedText,
  17040. isNegative ? pattern.negSuf : pattern.posSuf);
  17041. return parts.join('');
  17042. }
  17043. function padNumber(num, digits, trim) {
  17044. var neg = '';
  17045. if (num < 0) {
  17046. neg = '-';
  17047. num = -num;
  17048. }
  17049. num = '' + num;
  17050. while (num.length < digits) num = '0' + num;
  17051. if (trim) {
  17052. num = num.substr(num.length - digits);
  17053. }
  17054. return neg + num;
  17055. }
  17056. function dateGetter(name, size, offset, trim) {
  17057. offset = offset || 0;
  17058. return function(date) {
  17059. var value = date['get' + name]();
  17060. if (offset > 0 || value > -offset) {
  17061. value += offset;
  17062. }
  17063. if (value === 0 && offset == -12) value = 12;
  17064. return padNumber(value, size, trim);
  17065. };
  17066. }
  17067. function dateStrGetter(name, shortForm) {
  17068. return function(date, formats) {
  17069. var value = date['get' + name]();
  17070. var get = uppercase(shortForm ? ('SHORT' + name) : name);
  17071. return formats[get][value];
  17072. };
  17073. }
  17074. function timeZoneGetter(date, formats, offset) {
  17075. var zone = -1 * offset;
  17076. var paddedZone = (zone >= 0) ? "+" : "";
  17077. paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
  17078. padNumber(Math.abs(zone % 60), 2);
  17079. return paddedZone;
  17080. }
  17081. function getFirstThursdayOfYear(year) {
  17082. // 0 = index of January
  17083. var dayOfWeekOnFirst = (new Date(year, 0, 1)).getDay();
  17084. // 4 = index of Thursday (+1 to account for 1st = 5)
  17085. // 11 = index of *next* Thursday (+1 account for 1st = 12)
  17086. return new Date(year, 0, ((dayOfWeekOnFirst <= 4) ? 5 : 12) - dayOfWeekOnFirst);
  17087. }
  17088. function getThursdayThisWeek(datetime) {
  17089. return new Date(datetime.getFullYear(), datetime.getMonth(),
  17090. // 4 = index of Thursday
  17091. datetime.getDate() + (4 - datetime.getDay()));
  17092. }
  17093. function weekGetter(size) {
  17094. return function(date) {
  17095. var firstThurs = getFirstThursdayOfYear(date.getFullYear()),
  17096. thisThurs = getThursdayThisWeek(date);
  17097. var diff = +thisThurs - +firstThurs,
  17098. result = 1 + Math.round(diff / 6.048e8); // 6.048e8 ms per week
  17099. return padNumber(result, size);
  17100. };
  17101. }
  17102. function ampmGetter(date, formats) {
  17103. return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
  17104. }
  17105. function eraGetter(date, formats) {
  17106. return date.getFullYear() <= 0 ? formats.ERAS[0] : formats.ERAS[1];
  17107. }
  17108. function longEraGetter(date, formats) {
  17109. return date.getFullYear() <= 0 ? formats.ERANAMES[0] : formats.ERANAMES[1];
  17110. }
  17111. var DATE_FORMATS = {
  17112. yyyy: dateGetter('FullYear', 4),
  17113. yy: dateGetter('FullYear', 2, 0, true),
  17114. y: dateGetter('FullYear', 1),
  17115. MMMM: dateStrGetter('Month'),
  17116. MMM: dateStrGetter('Month', true),
  17117. MM: dateGetter('Month', 2, 1),
  17118. M: dateGetter('Month', 1, 1),
  17119. dd: dateGetter('Date', 2),
  17120. d: dateGetter('Date', 1),
  17121. HH: dateGetter('Hours', 2),
  17122. H: dateGetter('Hours', 1),
  17123. hh: dateGetter('Hours', 2, -12),
  17124. h: dateGetter('Hours', 1, -12),
  17125. mm: dateGetter('Minutes', 2),
  17126. m: dateGetter('Minutes', 1),
  17127. ss: dateGetter('Seconds', 2),
  17128. s: dateGetter('Seconds', 1),
  17129. // while ISO 8601 requires fractions to be prefixed with `.` or `,`
  17130. // we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
  17131. sss: dateGetter('Milliseconds', 3),
  17132. EEEE: dateStrGetter('Day'),
  17133. EEE: dateStrGetter('Day', true),
  17134. a: ampmGetter,
  17135. Z: timeZoneGetter,
  17136. ww: weekGetter(2),
  17137. w: weekGetter(1),
  17138. G: eraGetter,
  17139. GG: eraGetter,
  17140. GGG: eraGetter,
  17141. GGGG: longEraGetter
  17142. };
  17143. var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZEwG']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z|G+|w+))(.*)/,
  17144. NUMBER_STRING = /^\-?\d+$/;
  17145. /**
  17146. * @ngdoc filter
  17147. * @name date
  17148. * @kind function
  17149. *
  17150. * @description
  17151. * Formats `date` to a string based on the requested `format`.
  17152. *
  17153. * `format` string can be composed of the following elements:
  17154. *
  17155. * * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
  17156. * * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
  17157. * * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
  17158. * * `'MMMM'`: Month in year (January-December)
  17159. * * `'MMM'`: Month in year (Jan-Dec)
  17160. * * `'MM'`: Month in year, padded (01-12)
  17161. * * `'M'`: Month in year (1-12)
  17162. * * `'dd'`: Day in month, padded (01-31)
  17163. * * `'d'`: Day in month (1-31)
  17164. * * `'EEEE'`: Day in Week,(Sunday-Saturday)
  17165. * * `'EEE'`: Day in Week, (Sun-Sat)
  17166. * * `'HH'`: Hour in day, padded (00-23)
  17167. * * `'H'`: Hour in day (0-23)
  17168. * * `'hh'`: Hour in AM/PM, padded (01-12)
  17169. * * `'h'`: Hour in AM/PM, (1-12)
  17170. * * `'mm'`: Minute in hour, padded (00-59)
  17171. * * `'m'`: Minute in hour (0-59)
  17172. * * `'ss'`: Second in minute, padded (00-59)
  17173. * * `'s'`: Second in minute (0-59)
  17174. * * `'sss'`: Millisecond in second, padded (000-999)
  17175. * * `'a'`: AM/PM marker
  17176. * * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
  17177. * * `'ww'`: Week of year, padded (00-53). Week 01 is the week with the first Thursday of the year
  17178. * * `'w'`: Week of year (0-53). Week 1 is the week with the first Thursday of the year
  17179. * * `'G'`, `'GG'`, `'GGG'`: The abbreviated form of the era string (e.g. 'AD')
  17180. * * `'GGGG'`: The long form of the era string (e.g. 'Anno Domini')
  17181. *
  17182. * `format` string can also be one of the following predefined
  17183. * {@link guide/i18n localizable formats}:
  17184. *
  17185. * * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
  17186. * (e.g. Sep 3, 2010 12:05:08 PM)
  17187. * * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 PM)
  17188. * * `'fullDate'`: equivalent to `'EEEE, MMMM d, y'` for en_US locale
  17189. * (e.g. Friday, September 3, 2010)
  17190. * * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
  17191. * * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
  17192. * * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
  17193. * * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 PM)
  17194. * * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 PM)
  17195. *
  17196. * `format` string can contain literal values. These need to be escaped by surrounding with single quotes (e.g.
  17197. * `"h 'in the morning'"`). In order to output a single quote, escape it - i.e., two single quotes in a sequence
  17198. * (e.g. `"h 'o''clock'"`).
  17199. *
  17200. * @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
  17201. * number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.sssZ and its
  17202. * shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
  17203. * specified in the string input, the time is considered to be in the local timezone.
  17204. * @param {string=} format Formatting rules (see Description). If not specified,
  17205. * `mediumDate` is used.
  17206. * @param {string=} timezone Timezone to be used for formatting. It understands UTC/GMT and the
  17207. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  17208. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  17209. * If not specified, the timezone of the browser will be used.
  17210. * @returns {string} Formatted string or the input if input is not recognized as date/millis.
  17211. *
  17212. * @example
  17213. <example>
  17214. <file name="index.html">
  17215. <span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
  17216. <span>{{1288323623006 | date:'medium'}}</span><br>
  17217. <span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
  17218. <span>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span><br>
  17219. <span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
  17220. <span>{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}</span><br>
  17221. <span ng-non-bindable>{{1288323623006 | date:"MM/dd/yyyy 'at' h:mma"}}</span>:
  17222. <span>{{'1288323623006' | date:"MM/dd/yyyy 'at' h:mma"}}</span><br>
  17223. </file>
  17224. <file name="protractor.js" type="protractor">
  17225. it('should format date', function() {
  17226. expect(element(by.binding("1288323623006 | date:'medium'")).getText()).
  17227. toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
  17228. expect(element(by.binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).getText()).
  17229. toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
  17230. expect(element(by.binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).getText()).
  17231. toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
  17232. expect(element(by.binding("'1288323623006' | date:\"MM/dd/yyyy 'at' h:mma\"")).getText()).
  17233. toMatch(/10\/2\d\/2010 at \d{1,2}:\d{2}(AM|PM)/);
  17234. });
  17235. </file>
  17236. </example>
  17237. */
  17238. dateFilter.$inject = ['$locale'];
  17239. function dateFilter($locale) {
  17240. var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
  17241. // 1 2 3 4 5 6 7 8 9 10 11
  17242. function jsonStringToDate(string) {
  17243. var match;
  17244. if (match = string.match(R_ISO8601_STR)) {
  17245. var date = new Date(0),
  17246. tzHour = 0,
  17247. tzMin = 0,
  17248. dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
  17249. timeSetter = match[8] ? date.setUTCHours : date.setHours;
  17250. if (match[9]) {
  17251. tzHour = toInt(match[9] + match[10]);
  17252. tzMin = toInt(match[9] + match[11]);
  17253. }
  17254. dateSetter.call(date, toInt(match[1]), toInt(match[2]) - 1, toInt(match[3]));
  17255. var h = toInt(match[4] || 0) - tzHour;
  17256. var m = toInt(match[5] || 0) - tzMin;
  17257. var s = toInt(match[6] || 0);
  17258. var ms = Math.round(parseFloat('0.' + (match[7] || 0)) * 1000);
  17259. timeSetter.call(date, h, m, s, ms);
  17260. return date;
  17261. }
  17262. return string;
  17263. }
  17264. return function(date, format, timezone) {
  17265. var text = '',
  17266. parts = [],
  17267. fn, match;
  17268. format = format || 'mediumDate';
  17269. format = $locale.DATETIME_FORMATS[format] || format;
  17270. if (isString(date)) {
  17271. date = NUMBER_STRING.test(date) ? toInt(date) : jsonStringToDate(date);
  17272. }
  17273. if (isNumber(date)) {
  17274. date = new Date(date);
  17275. }
  17276. if (!isDate(date) || !isFinite(date.getTime())) {
  17277. return date;
  17278. }
  17279. while (format) {
  17280. match = DATE_FORMATS_SPLIT.exec(format);
  17281. if (match) {
  17282. parts = concat(parts, match, 1);
  17283. format = parts.pop();
  17284. } else {
  17285. parts.push(format);
  17286. format = null;
  17287. }
  17288. }
  17289. var dateTimezoneOffset = date.getTimezoneOffset();
  17290. if (timezone) {
  17291. dateTimezoneOffset = timezoneToOffset(timezone, date.getTimezoneOffset());
  17292. date = convertTimezoneToLocal(date, timezone, true);
  17293. }
  17294. forEach(parts, function(value) {
  17295. fn = DATE_FORMATS[value];
  17296. text += fn ? fn(date, $locale.DATETIME_FORMATS, dateTimezoneOffset)
  17297. : value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
  17298. });
  17299. return text;
  17300. };
  17301. }
  17302. /**
  17303. * @ngdoc filter
  17304. * @name json
  17305. * @kind function
  17306. *
  17307. * @description
  17308. * Allows you to convert a JavaScript object into JSON string.
  17309. *
  17310. * This filter is mostly useful for debugging. When using the double curly {{value}} notation
  17311. * the binding is automatically converted to JSON.
  17312. *
  17313. * @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
  17314. * @param {number=} spacing The number of spaces to use per indentation, defaults to 2.
  17315. * @returns {string} JSON string.
  17316. *
  17317. *
  17318. * @example
  17319. <example>
  17320. <file name="index.html">
  17321. <pre id="default-spacing">{{ {'name':'value'} | json }}</pre>
  17322. <pre id="custom-spacing">{{ {'name':'value'} | json:4 }}</pre>
  17323. </file>
  17324. <file name="protractor.js" type="protractor">
  17325. it('should jsonify filtered objects', function() {
  17326. expect(element(by.id('default-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17327. expect(element(by.id('custom-spacing')).getText()).toMatch(/\{\n "name": ?"value"\n}/);
  17328. });
  17329. </file>
  17330. </example>
  17331. *
  17332. */
  17333. function jsonFilter() {
  17334. return function(object, spacing) {
  17335. if (isUndefined(spacing)) {
  17336. spacing = 2;
  17337. }
  17338. return toJson(object, spacing);
  17339. };
  17340. }
  17341. /**
  17342. * @ngdoc filter
  17343. * @name lowercase
  17344. * @kind function
  17345. * @description
  17346. * Converts string to lowercase.
  17347. * @see angular.lowercase
  17348. */
  17349. var lowercaseFilter = valueFn(lowercase);
  17350. /**
  17351. * @ngdoc filter
  17352. * @name uppercase
  17353. * @kind function
  17354. * @description
  17355. * Converts string to uppercase.
  17356. * @see angular.uppercase
  17357. */
  17358. var uppercaseFilter = valueFn(uppercase);
  17359. /**
  17360. * @ngdoc filter
  17361. * @name limitTo
  17362. * @kind function
  17363. *
  17364. * @description
  17365. * Creates a new array or string containing only a specified number of elements. The elements
  17366. * are taken from either the beginning or the end of the source array, string or number, as specified by
  17367. * the value and sign (positive or negative) of `limit`. If a number is used as input, it is
  17368. * converted to a string.
  17369. *
  17370. * @param {Array|string|number} input Source array, string or number to be limited.
  17371. * @param {string|number} limit The length of the returned array or string. If the `limit` number
  17372. * is positive, `limit` number of items from the beginning of the source array/string are copied.
  17373. * If the number is negative, `limit` number of items from the end of the source array/string
  17374. * are copied. The `limit` will be trimmed if it exceeds `array.length`. If `limit` is undefined,
  17375. * the input will be returned unchanged.
  17376. * @param {(string|number)=} begin Index at which to begin limitation. As a negative index, `begin`
  17377. * indicates an offset from the end of `input`. Defaults to `0`.
  17378. * @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
  17379. * had less than `limit` elements.
  17380. *
  17381. * @example
  17382. <example module="limitToExample">
  17383. <file name="index.html">
  17384. <script>
  17385. angular.module('limitToExample', [])
  17386. .controller('ExampleController', ['$scope', function($scope) {
  17387. $scope.numbers = [1,2,3,4,5,6,7,8,9];
  17388. $scope.letters = "abcdefghi";
  17389. $scope.longNumber = 2345432342;
  17390. $scope.numLimit = 3;
  17391. $scope.letterLimit = 3;
  17392. $scope.longNumberLimit = 3;
  17393. }]);
  17394. </script>
  17395. <div ng-controller="ExampleController">
  17396. <label>
  17397. Limit {{numbers}} to:
  17398. <input type="number" step="1" ng-model="numLimit">
  17399. </label>
  17400. <p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
  17401. <label>
  17402. Limit {{letters}} to:
  17403. <input type="number" step="1" ng-model="letterLimit">
  17404. </label>
  17405. <p>Output letters: {{ letters | limitTo:letterLimit }}</p>
  17406. <label>
  17407. Limit {{longNumber}} to:
  17408. <input type="number" step="1" ng-model="longNumberLimit">
  17409. </label>
  17410. <p>Output long number: {{ longNumber | limitTo:longNumberLimit }}</p>
  17411. </div>
  17412. </file>
  17413. <file name="protractor.js" type="protractor">
  17414. var numLimitInput = element(by.model('numLimit'));
  17415. var letterLimitInput = element(by.model('letterLimit'));
  17416. var longNumberLimitInput = element(by.model('longNumberLimit'));
  17417. var limitedNumbers = element(by.binding('numbers | limitTo:numLimit'));
  17418. var limitedLetters = element(by.binding('letters | limitTo:letterLimit'));
  17419. var limitedLongNumber = element(by.binding('longNumber | limitTo:longNumberLimit'));
  17420. it('should limit the number array to first three items', function() {
  17421. expect(numLimitInput.getAttribute('value')).toBe('3');
  17422. expect(letterLimitInput.getAttribute('value')).toBe('3');
  17423. expect(longNumberLimitInput.getAttribute('value')).toBe('3');
  17424. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3]');
  17425. expect(limitedLetters.getText()).toEqual('Output letters: abc');
  17426. expect(limitedLongNumber.getText()).toEqual('Output long number: 234');
  17427. });
  17428. // There is a bug in safari and protractor that doesn't like the minus key
  17429. // it('should update the output when -3 is entered', function() {
  17430. // numLimitInput.clear();
  17431. // numLimitInput.sendKeys('-3');
  17432. // letterLimitInput.clear();
  17433. // letterLimitInput.sendKeys('-3');
  17434. // longNumberLimitInput.clear();
  17435. // longNumberLimitInput.sendKeys('-3');
  17436. // expect(limitedNumbers.getText()).toEqual('Output numbers: [7,8,9]');
  17437. // expect(limitedLetters.getText()).toEqual('Output letters: ghi');
  17438. // expect(limitedLongNumber.getText()).toEqual('Output long number: 342');
  17439. // });
  17440. it('should not exceed the maximum size of input array', function() {
  17441. numLimitInput.clear();
  17442. numLimitInput.sendKeys('100');
  17443. letterLimitInput.clear();
  17444. letterLimitInput.sendKeys('100');
  17445. longNumberLimitInput.clear();
  17446. longNumberLimitInput.sendKeys('100');
  17447. expect(limitedNumbers.getText()).toEqual('Output numbers: [1,2,3,4,5,6,7,8,9]');
  17448. expect(limitedLetters.getText()).toEqual('Output letters: abcdefghi');
  17449. expect(limitedLongNumber.getText()).toEqual('Output long number: 2345432342');
  17450. });
  17451. </file>
  17452. </example>
  17453. */
  17454. function limitToFilter() {
  17455. return function(input, limit, begin) {
  17456. if (Math.abs(Number(limit)) === Infinity) {
  17457. limit = Number(limit);
  17458. } else {
  17459. limit = toInt(limit);
  17460. }
  17461. if (isNaN(limit)) return input;
  17462. if (isNumber(input)) input = input.toString();
  17463. if (!isArray(input) && !isString(input)) return input;
  17464. begin = (!begin || isNaN(begin)) ? 0 : toInt(begin);
  17465. begin = (begin < 0) ? Math.max(0, input.length + begin) : begin;
  17466. if (limit >= 0) {
  17467. return input.slice(begin, begin + limit);
  17468. } else {
  17469. if (begin === 0) {
  17470. return input.slice(limit, input.length);
  17471. } else {
  17472. return input.slice(Math.max(0, begin + limit), begin);
  17473. }
  17474. }
  17475. };
  17476. }
  17477. /**
  17478. * @ngdoc filter
  17479. * @name orderBy
  17480. * @kind function
  17481. *
  17482. * @description
  17483. * Orders a specified `array` by the `expression` predicate. It is ordered alphabetically
  17484. * for strings and numerically for numbers. Note: if you notice numbers are not being sorted
  17485. * as expected, make sure they are actually being saved as numbers and not strings.
  17486. *
  17487. * @param {Array} array The array to sort.
  17488. * @param {function(*)|string|Array.<(function(*)|string)>=} expression A predicate to be
  17489. * used by the comparator to determine the order of elements.
  17490. *
  17491. * Can be one of:
  17492. *
  17493. * - `function`: Getter function. The result of this function will be sorted using the
  17494. * `<`, `===`, `>` operator.
  17495. * - `string`: An Angular expression. The result of this expression is used to compare elements
  17496. * (for example `name` to sort by a property called `name` or `name.substr(0, 3)` to sort by
  17497. * 3 first characters of a property called `name`). The result of a constant expression
  17498. * is interpreted as a property name to be used in comparisons (for example `"special name"`
  17499. * to sort object by the value of their `special name` property). An expression can be
  17500. * optionally prefixed with `+` or `-` to control ascending or descending sort order
  17501. * (for example, `+name` or `-name`). If no property is provided, (e.g. `'+'`) then the array
  17502. * element itself is used to compare where sorting.
  17503. * - `Array`: An array of function or string predicates. The first predicate in the array
  17504. * is used for sorting, but when two items are equivalent, the next predicate is used.
  17505. *
  17506. * If the predicate is missing or empty then it defaults to `'+'`.
  17507. *
  17508. * @param {boolean=} reverse Reverse the order of the array.
  17509. * @returns {Array} Sorted copy of the source array.
  17510. *
  17511. *
  17512. * @example
  17513. * The example below demonstrates a simple ngRepeat, where the data is sorted
  17514. * by age in descending order (predicate is set to `'-age'`).
  17515. * `reverse` is not set, which means it defaults to `false`.
  17516. <example module="orderByExample">
  17517. <file name="index.html">
  17518. <script>
  17519. angular.module('orderByExample', [])
  17520. .controller('ExampleController', ['$scope', function($scope) {
  17521. $scope.friends =
  17522. [{name:'John', phone:'555-1212', age:10},
  17523. {name:'Mary', phone:'555-9876', age:19},
  17524. {name:'Mike', phone:'555-4321', age:21},
  17525. {name:'Adam', phone:'555-5678', age:35},
  17526. {name:'Julie', phone:'555-8765', age:29}];
  17527. }]);
  17528. </script>
  17529. <div ng-controller="ExampleController">
  17530. <table class="friend">
  17531. <tr>
  17532. <th>Name</th>
  17533. <th>Phone Number</th>
  17534. <th>Age</th>
  17535. </tr>
  17536. <tr ng-repeat="friend in friends | orderBy:'-age'">
  17537. <td>{{friend.name}}</td>
  17538. <td>{{friend.phone}}</td>
  17539. <td>{{friend.age}}</td>
  17540. </tr>
  17541. </table>
  17542. </div>
  17543. </file>
  17544. </example>
  17545. *
  17546. * The predicate and reverse parameters can be controlled dynamically through scope properties,
  17547. * as shown in the next example.
  17548. * @example
  17549. <example module="orderByExample">
  17550. <file name="index.html">
  17551. <script>
  17552. angular.module('orderByExample', [])
  17553. .controller('ExampleController', ['$scope', function($scope) {
  17554. $scope.friends =
  17555. [{name:'John', phone:'555-1212', age:10},
  17556. {name:'Mary', phone:'555-9876', age:19},
  17557. {name:'Mike', phone:'555-4321', age:21},
  17558. {name:'Adam', phone:'555-5678', age:35},
  17559. {name:'Julie', phone:'555-8765', age:29}];
  17560. $scope.predicate = 'age';
  17561. $scope.reverse = true;
  17562. $scope.order = function(predicate) {
  17563. $scope.reverse = ($scope.predicate === predicate) ? !$scope.reverse : false;
  17564. $scope.predicate = predicate;
  17565. };
  17566. }]);
  17567. </script>
  17568. <style type="text/css">
  17569. .sortorder:after {
  17570. content: '\25b2';
  17571. }
  17572. .sortorder.reverse:after {
  17573. content: '\25bc';
  17574. }
  17575. </style>
  17576. <div ng-controller="ExampleController">
  17577. <pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
  17578. <hr/>
  17579. [ <a href="" ng-click="predicate=''">unsorted</a> ]
  17580. <table class="friend">
  17581. <tr>
  17582. <th>
  17583. <a href="" ng-click="order('name')">Name</a>
  17584. <span class="sortorder" ng-show="predicate === 'name'" ng-class="{reverse:reverse}"></span>
  17585. </th>
  17586. <th>
  17587. <a href="" ng-click="order('phone')">Phone Number</a>
  17588. <span class="sortorder" ng-show="predicate === 'phone'" ng-class="{reverse:reverse}"></span>
  17589. </th>
  17590. <th>
  17591. <a href="" ng-click="order('age')">Age</a>
  17592. <span class="sortorder" ng-show="predicate === 'age'" ng-class="{reverse:reverse}"></span>
  17593. </th>
  17594. </tr>
  17595. <tr ng-repeat="friend in friends | orderBy:predicate:reverse">
  17596. <td>{{friend.name}}</td>
  17597. <td>{{friend.phone}}</td>
  17598. <td>{{friend.age}}</td>
  17599. </tr>
  17600. </table>
  17601. </div>
  17602. </file>
  17603. </example>
  17604. *
  17605. * It's also possible to call the orderBy filter manually, by injecting `$filter`, retrieving the
  17606. * filter routine with `$filter('orderBy')`, and calling the returned filter routine with the
  17607. * desired parameters.
  17608. *
  17609. * Example:
  17610. *
  17611. * @example
  17612. <example module="orderByExample">
  17613. <file name="index.html">
  17614. <div ng-controller="ExampleController">
  17615. <table class="friend">
  17616. <tr>
  17617. <th><a href="" ng-click="reverse=false;order('name', false)">Name</a>
  17618. (<a href="" ng-click="order('-name',false)">^</a>)</th>
  17619. <th><a href="" ng-click="reverse=!reverse;order('phone', reverse)">Phone Number</a></th>
  17620. <th><a href="" ng-click="reverse=!reverse;order('age',reverse)">Age</a></th>
  17621. </tr>
  17622. <tr ng-repeat="friend in friends">
  17623. <td>{{friend.name}}</td>
  17624. <td>{{friend.phone}}</td>
  17625. <td>{{friend.age}}</td>
  17626. </tr>
  17627. </table>
  17628. </div>
  17629. </file>
  17630. <file name="script.js">
  17631. angular.module('orderByExample', [])
  17632. .controller('ExampleController', ['$scope', '$filter', function($scope, $filter) {
  17633. var orderBy = $filter('orderBy');
  17634. $scope.friends = [
  17635. { name: 'John', phone: '555-1212', age: 10 },
  17636. { name: 'Mary', phone: '555-9876', age: 19 },
  17637. { name: 'Mike', phone: '555-4321', age: 21 },
  17638. { name: 'Adam', phone: '555-5678', age: 35 },
  17639. { name: 'Julie', phone: '555-8765', age: 29 }
  17640. ];
  17641. $scope.order = function(predicate, reverse) {
  17642. $scope.friends = orderBy($scope.friends, predicate, reverse);
  17643. };
  17644. $scope.order('-age',false);
  17645. }]);
  17646. </file>
  17647. </example>
  17648. */
  17649. orderByFilter.$inject = ['$parse'];
  17650. function orderByFilter($parse) {
  17651. return function(array, sortPredicate, reverseOrder) {
  17652. if (!(isArrayLike(array))) return array;
  17653. if (!isArray(sortPredicate)) { sortPredicate = [sortPredicate]; }
  17654. if (sortPredicate.length === 0) { sortPredicate = ['+']; }
  17655. var predicates = processPredicates(sortPredicate, reverseOrder);
  17656. // Add a predicate at the end that evaluates to the element index. This makes the
  17657. // sort stable as it works as a tie-breaker when all the input predicates cannot
  17658. // distinguish between two elements.
  17659. predicates.push({ get: function() { return {}; }, descending: reverseOrder ? -1 : 1});
  17660. // The next three lines are a version of a Swartzian Transform idiom from Perl
  17661. // (sometimes called the Decorate-Sort-Undecorate idiom)
  17662. // See https://en.wikipedia.org/wiki/Schwartzian_transform
  17663. var compareValues = Array.prototype.map.call(array, getComparisonObject);
  17664. compareValues.sort(doComparison);
  17665. array = compareValues.map(function(item) { return item.value; });
  17666. return array;
  17667. function getComparisonObject(value, index) {
  17668. return {
  17669. value: value,
  17670. predicateValues: predicates.map(function(predicate) {
  17671. return getPredicateValue(predicate.get(value), index);
  17672. })
  17673. };
  17674. }
  17675. function doComparison(v1, v2) {
  17676. var result = 0;
  17677. for (var index=0, length = predicates.length; index < length; ++index) {
  17678. result = compare(v1.predicateValues[index], v2.predicateValues[index]) * predicates[index].descending;
  17679. if (result) break;
  17680. }
  17681. return result;
  17682. }
  17683. };
  17684. function processPredicates(sortPredicate, reverseOrder) {
  17685. reverseOrder = reverseOrder ? -1 : 1;
  17686. return sortPredicate.map(function(predicate) {
  17687. var descending = 1, get = identity;
  17688. if (isFunction(predicate)) {
  17689. get = predicate;
  17690. } else if (isString(predicate)) {
  17691. if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
  17692. descending = predicate.charAt(0) == '-' ? -1 : 1;
  17693. predicate = predicate.substring(1);
  17694. }
  17695. if (predicate !== '') {
  17696. get = $parse(predicate);
  17697. if (get.constant) {
  17698. var key = get();
  17699. get = function(value) { return value[key]; };
  17700. }
  17701. }
  17702. }
  17703. return { get: get, descending: descending * reverseOrder };
  17704. });
  17705. }
  17706. function isPrimitive(value) {
  17707. switch (typeof value) {
  17708. case 'number': /* falls through */
  17709. case 'boolean': /* falls through */
  17710. case 'string':
  17711. return true;
  17712. default:
  17713. return false;
  17714. }
  17715. }
  17716. function objectValue(value, index) {
  17717. // If `valueOf` is a valid function use that
  17718. if (typeof value.valueOf === 'function') {
  17719. value = value.valueOf();
  17720. if (isPrimitive(value)) return value;
  17721. }
  17722. // If `toString` is a valid function and not the one from `Object.prototype` use that
  17723. if (hasCustomToString(value)) {
  17724. value = value.toString();
  17725. if (isPrimitive(value)) return value;
  17726. }
  17727. // We have a basic object so we use the position of the object in the collection
  17728. return index;
  17729. }
  17730. function getPredicateValue(value, index) {
  17731. var type = typeof value;
  17732. if (value === null) {
  17733. type = 'string';
  17734. value = 'null';
  17735. } else if (type === 'string') {
  17736. value = value.toLowerCase();
  17737. } else if (type === 'object') {
  17738. value = objectValue(value, index);
  17739. }
  17740. return { value: value, type: type };
  17741. }
  17742. function compare(v1, v2) {
  17743. var result = 0;
  17744. if (v1.type === v2.type) {
  17745. if (v1.value !== v2.value) {
  17746. result = v1.value < v2.value ? -1 : 1;
  17747. }
  17748. } else {
  17749. result = v1.type < v2.type ? -1 : 1;
  17750. }
  17751. return result;
  17752. }
  17753. }
  17754. function ngDirective(directive) {
  17755. if (isFunction(directive)) {
  17756. directive = {
  17757. link: directive
  17758. };
  17759. }
  17760. directive.restrict = directive.restrict || 'AC';
  17761. return valueFn(directive);
  17762. }
  17763. /**
  17764. * @ngdoc directive
  17765. * @name a
  17766. * @restrict E
  17767. *
  17768. * @description
  17769. * Modifies the default behavior of the html A tag so that the default action is prevented when
  17770. * the href attribute is empty.
  17771. *
  17772. * This change permits the easy creation of action links with the `ngClick` directive
  17773. * without changing the location or causing page reloads, e.g.:
  17774. * `<a href="" ng-click="list.addItem()">Add Item</a>`
  17775. */
  17776. var htmlAnchorDirective = valueFn({
  17777. restrict: 'E',
  17778. compile: function(element, attr) {
  17779. if (!attr.href && !attr.xlinkHref) {
  17780. return function(scope, element) {
  17781. // If the linked element is not an anchor tag anymore, do nothing
  17782. if (element[0].nodeName.toLowerCase() !== 'a') return;
  17783. // SVGAElement does not use the href attribute, but rather the 'xlinkHref' attribute.
  17784. var href = toString.call(element.prop('href')) === '[object SVGAnimatedString]' ?
  17785. 'xlink:href' : 'href';
  17786. element.on('click', function(event) {
  17787. // if we have no href url, then don't navigate anywhere.
  17788. if (!element.attr(href)) {
  17789. event.preventDefault();
  17790. }
  17791. });
  17792. };
  17793. }
  17794. }
  17795. });
  17796. /**
  17797. * @ngdoc directive
  17798. * @name ngHref
  17799. * @restrict A
  17800. * @priority 99
  17801. *
  17802. * @description
  17803. * Using Angular markup like `{{hash}}` in an href attribute will
  17804. * make the link go to the wrong URL if the user clicks it before
  17805. * Angular has a chance to replace the `{{hash}}` markup with its
  17806. * value. Until Angular replaces the markup the link will be broken
  17807. * and will most likely return a 404 error. The `ngHref` directive
  17808. * solves this problem.
  17809. *
  17810. * The wrong way to write it:
  17811. * ```html
  17812. * <a href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17813. * ```
  17814. *
  17815. * The correct way to write it:
  17816. * ```html
  17817. * <a ng-href="http://www.gravatar.com/avatar/{{hash}}">link1</a>
  17818. * ```
  17819. *
  17820. * @element A
  17821. * @param {template} ngHref any string which can contain `{{}}` markup.
  17822. *
  17823. * @example
  17824. * This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
  17825. * in links and their different behaviors:
  17826. <example>
  17827. <file name="index.html">
  17828. <input ng-model="value" /><br />
  17829. <a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
  17830. <a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
  17831. <a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
  17832. <a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
  17833. <a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
  17834. <a id="link-6" ng-href="{{value}}">link</a> (link, change location)
  17835. </file>
  17836. <file name="protractor.js" type="protractor">
  17837. it('should execute ng-click but not reload when href without value', function() {
  17838. element(by.id('link-1')).click();
  17839. expect(element(by.model('value')).getAttribute('value')).toEqual('1');
  17840. expect(element(by.id('link-1')).getAttribute('href')).toBe('');
  17841. });
  17842. it('should execute ng-click but not reload when href empty string', function() {
  17843. element(by.id('link-2')).click();
  17844. expect(element(by.model('value')).getAttribute('value')).toEqual('2');
  17845. expect(element(by.id('link-2')).getAttribute('href')).toBe('');
  17846. });
  17847. it('should execute ng-click and change url when ng-href specified', function() {
  17848. expect(element(by.id('link-3')).getAttribute('href')).toMatch(/\/123$/);
  17849. element(by.id('link-3')).click();
  17850. // At this point, we navigate away from an Angular page, so we need
  17851. // to use browser.driver to get the base webdriver.
  17852. browser.wait(function() {
  17853. return browser.driver.getCurrentUrl().then(function(url) {
  17854. return url.match(/\/123$/);
  17855. });
  17856. }, 5000, 'page should navigate to /123');
  17857. });
  17858. it('should execute ng-click but not reload when href empty string and name specified', function() {
  17859. element(by.id('link-4')).click();
  17860. expect(element(by.model('value')).getAttribute('value')).toEqual('4');
  17861. expect(element(by.id('link-4')).getAttribute('href')).toBe('');
  17862. });
  17863. it('should execute ng-click but not reload when no href but name specified', function() {
  17864. element(by.id('link-5')).click();
  17865. expect(element(by.model('value')).getAttribute('value')).toEqual('5');
  17866. expect(element(by.id('link-5')).getAttribute('href')).toBe(null);
  17867. });
  17868. it('should only change url when only ng-href', function() {
  17869. element(by.model('value')).clear();
  17870. element(by.model('value')).sendKeys('6');
  17871. expect(element(by.id('link-6')).getAttribute('href')).toMatch(/\/6$/);
  17872. element(by.id('link-6')).click();
  17873. // At this point, we navigate away from an Angular page, so we need
  17874. // to use browser.driver to get the base webdriver.
  17875. browser.wait(function() {
  17876. return browser.driver.getCurrentUrl().then(function(url) {
  17877. return url.match(/\/6$/);
  17878. });
  17879. }, 5000, 'page should navigate to /6');
  17880. });
  17881. </file>
  17882. </example>
  17883. */
  17884. /**
  17885. * @ngdoc directive
  17886. * @name ngSrc
  17887. * @restrict A
  17888. * @priority 99
  17889. *
  17890. * @description
  17891. * Using Angular markup like `{{hash}}` in a `src` attribute doesn't
  17892. * work right: The browser will fetch from the URL with the literal
  17893. * text `{{hash}}` until Angular replaces the expression inside
  17894. * `{{hash}}`. The `ngSrc` directive solves this problem.
  17895. *
  17896. * The buggy way to write it:
  17897. * ```html
  17898. * <img src="http://www.gravatar.com/avatar/{{hash}}" alt="Description"/>
  17899. * ```
  17900. *
  17901. * The correct way to write it:
  17902. * ```html
  17903. * <img ng-src="http://www.gravatar.com/avatar/{{hash}}" alt="Description" />
  17904. * ```
  17905. *
  17906. * @element IMG
  17907. * @param {template} ngSrc any string which can contain `{{}}` markup.
  17908. */
  17909. /**
  17910. * @ngdoc directive
  17911. * @name ngSrcset
  17912. * @restrict A
  17913. * @priority 99
  17914. *
  17915. * @description
  17916. * Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
  17917. * work right: The browser will fetch from the URL with the literal
  17918. * text `{{hash}}` until Angular replaces the expression inside
  17919. * `{{hash}}`. The `ngSrcset` directive solves this problem.
  17920. *
  17921. * The buggy way to write it:
  17922. * ```html
  17923. * <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description"/>
  17924. * ```
  17925. *
  17926. * The correct way to write it:
  17927. * ```html
  17928. * <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x" alt="Description" />
  17929. * ```
  17930. *
  17931. * @element IMG
  17932. * @param {template} ngSrcset any string which can contain `{{}}` markup.
  17933. */
  17934. /**
  17935. * @ngdoc directive
  17936. * @name ngDisabled
  17937. * @restrict A
  17938. * @priority 100
  17939. *
  17940. * @description
  17941. *
  17942. * This directive sets the `disabled` attribute on the element if the
  17943. * {@link guide/expression expression} inside `ngDisabled` evaluates to truthy.
  17944. *
  17945. * A special directive is necessary because we cannot use interpolation inside the `disabled`
  17946. * attribute. The following example would make the button enabled on Chrome/Firefox
  17947. * but not on older IEs:
  17948. *
  17949. * ```html
  17950. * <!-- See below for an example of ng-disabled being used correctly -->
  17951. * <div ng-init="isDisabled = false">
  17952. * <button disabled="{{isDisabled}}">Disabled</button>
  17953. * </div>
  17954. * ```
  17955. *
  17956. * This is because the HTML specification does not require browsers to preserve the values of
  17957. * boolean attributes such as `disabled` (Their presence means true and their absence means false.)
  17958. * If we put an Angular interpolation expression into such an attribute then the
  17959. * binding information would be lost when the browser removes the attribute.
  17960. *
  17961. * @example
  17962. <example>
  17963. <file name="index.html">
  17964. <label>Click me to toggle: <input type="checkbox" ng-model="checked"></label><br/>
  17965. <button ng-model="button" ng-disabled="checked">Button</button>
  17966. </file>
  17967. <file name="protractor.js" type="protractor">
  17968. it('should toggle button', function() {
  17969. expect(element(by.css('button')).getAttribute('disabled')).toBeFalsy();
  17970. element(by.model('checked')).click();
  17971. expect(element(by.css('button')).getAttribute('disabled')).toBeTruthy();
  17972. });
  17973. </file>
  17974. </example>
  17975. *
  17976. * @element INPUT
  17977. * @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
  17978. * then the `disabled` attribute will be set on the element
  17979. */
  17980. /**
  17981. * @ngdoc directive
  17982. * @name ngChecked
  17983. * @restrict A
  17984. * @priority 100
  17985. *
  17986. * @description
  17987. * Sets the `checked` attribute on the element, if the expression inside `ngChecked` is truthy.
  17988. *
  17989. * Note that this directive should not be used together with {@link ngModel `ngModel`},
  17990. * as this can lead to unexpected behavior.
  17991. *
  17992. * ### Why do we need `ngChecked`?
  17993. *
  17994. * The HTML specification does not require browsers to preserve the values of boolean attributes
  17995. * such as checked. (Their presence means true and their absence means false.)
  17996. * If we put an Angular interpolation expression into such an attribute then the
  17997. * binding information would be lost when the browser removes the attribute.
  17998. * The `ngChecked` directive solves this problem for the `checked` attribute.
  17999. * This complementary directive is not removed by the browser and so provides
  18000. * a permanent reliable place to store the binding information.
  18001. * @example
  18002. <example>
  18003. <file name="index.html">
  18004. <label>Check me to check both: <input type="checkbox" ng-model="master"></label><br/>
  18005. <input id="checkSlave" type="checkbox" ng-checked="master" aria-label="Slave input">
  18006. </file>
  18007. <file name="protractor.js" type="protractor">
  18008. it('should check both checkBoxes', function() {
  18009. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeFalsy();
  18010. element(by.model('master')).click();
  18011. expect(element(by.id('checkSlave')).getAttribute('checked')).toBeTruthy();
  18012. });
  18013. </file>
  18014. </example>
  18015. *
  18016. * @element INPUT
  18017. * @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
  18018. * then the `checked` attribute will be set on the element
  18019. */
  18020. /**
  18021. * @ngdoc directive
  18022. * @name ngReadonly
  18023. * @restrict A
  18024. * @priority 100
  18025. *
  18026. * @description
  18027. * The HTML specification does not require browsers to preserve the values of boolean attributes
  18028. * such as readonly. (Their presence means true and their absence means false.)
  18029. * If we put an Angular interpolation expression into such an attribute then the
  18030. * binding information would be lost when the browser removes the attribute.
  18031. * The `ngReadonly` directive solves this problem for the `readonly` attribute.
  18032. * This complementary directive is not removed by the browser and so provides
  18033. * a permanent reliable place to store the binding information.
  18034. * @example
  18035. <example>
  18036. <file name="index.html">
  18037. <label>Check me to make text readonly: <input type="checkbox" ng-model="checked"></label><br/>
  18038. <input type="text" ng-readonly="checked" value="I'm Angular" aria-label="Readonly field" />
  18039. </file>
  18040. <file name="protractor.js" type="protractor">
  18041. it('should toggle readonly attr', function() {
  18042. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeFalsy();
  18043. element(by.model('checked')).click();
  18044. expect(element(by.css('[type="text"]')).getAttribute('readonly')).toBeTruthy();
  18045. });
  18046. </file>
  18047. </example>
  18048. *
  18049. * @element INPUT
  18050. * @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
  18051. * then special attribute "readonly" will be set on the element
  18052. */
  18053. /**
  18054. * @ngdoc directive
  18055. * @name ngSelected
  18056. * @restrict A
  18057. * @priority 100
  18058. *
  18059. * @description
  18060. * The HTML specification does not require browsers to preserve the values of boolean attributes
  18061. * such as selected. (Their presence means true and their absence means false.)
  18062. * If we put an Angular interpolation expression into such an attribute then the
  18063. * binding information would be lost when the browser removes the attribute.
  18064. * The `ngSelected` directive solves this problem for the `selected` attribute.
  18065. * This complementary directive is not removed by the browser and so provides
  18066. * a permanent reliable place to store the binding information.
  18067. *
  18068. * @example
  18069. <example>
  18070. <file name="index.html">
  18071. <label>Check me to select: <input type="checkbox" ng-model="selected"></label><br/>
  18072. <select aria-label="ngSelected demo">
  18073. <option>Hello!</option>
  18074. <option id="greet" ng-selected="selected">Greetings!</option>
  18075. </select>
  18076. </file>
  18077. <file name="protractor.js" type="protractor">
  18078. it('should select Greetings!', function() {
  18079. expect(element(by.id('greet')).getAttribute('selected')).toBeFalsy();
  18080. element(by.model('selected')).click();
  18081. expect(element(by.id('greet')).getAttribute('selected')).toBeTruthy();
  18082. });
  18083. </file>
  18084. </example>
  18085. *
  18086. * @element OPTION
  18087. * @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
  18088. * then special attribute "selected" will be set on the element
  18089. */
  18090. /**
  18091. * @ngdoc directive
  18092. * @name ngOpen
  18093. * @restrict A
  18094. * @priority 100
  18095. *
  18096. * @description
  18097. * The HTML specification does not require browsers to preserve the values of boolean attributes
  18098. * such as open. (Their presence means true and their absence means false.)
  18099. * If we put an Angular interpolation expression into such an attribute then the
  18100. * binding information would be lost when the browser removes the attribute.
  18101. * The `ngOpen` directive solves this problem for the `open` attribute.
  18102. * This complementary directive is not removed by the browser and so provides
  18103. * a permanent reliable place to store the binding information.
  18104. * @example
  18105. <example>
  18106. <file name="index.html">
  18107. <label>Check me check multiple: <input type="checkbox" ng-model="open"></label><br/>
  18108. <details id="details" ng-open="open">
  18109. <summary>Show/Hide me</summary>
  18110. </details>
  18111. </file>
  18112. <file name="protractor.js" type="protractor">
  18113. it('should toggle open', function() {
  18114. expect(element(by.id('details')).getAttribute('open')).toBeFalsy();
  18115. element(by.model('open')).click();
  18116. expect(element(by.id('details')).getAttribute('open')).toBeTruthy();
  18117. });
  18118. </file>
  18119. </example>
  18120. *
  18121. * @element DETAILS
  18122. * @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
  18123. * then special attribute "open" will be set on the element
  18124. */
  18125. var ngAttributeAliasDirectives = {};
  18126. // boolean attrs are evaluated
  18127. forEach(BOOLEAN_ATTR, function(propName, attrName) {
  18128. // binding to multiple is not supported
  18129. if (propName == "multiple") return;
  18130. function defaultLinkFn(scope, element, attr) {
  18131. scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
  18132. attr.$set(attrName, !!value);
  18133. });
  18134. }
  18135. var normalized = directiveNormalize('ng-' + attrName);
  18136. var linkFn = defaultLinkFn;
  18137. if (propName === 'checked') {
  18138. linkFn = function(scope, element, attr) {
  18139. // ensuring ngChecked doesn't interfere with ngModel when both are set on the same input
  18140. if (attr.ngModel !== attr[normalized]) {
  18141. defaultLinkFn(scope, element, attr);
  18142. }
  18143. };
  18144. }
  18145. ngAttributeAliasDirectives[normalized] = function() {
  18146. return {
  18147. restrict: 'A',
  18148. priority: 100,
  18149. link: linkFn
  18150. };
  18151. };
  18152. });
  18153. // aliased input attrs are evaluated
  18154. forEach(ALIASED_ATTR, function(htmlAttr, ngAttr) {
  18155. ngAttributeAliasDirectives[ngAttr] = function() {
  18156. return {
  18157. priority: 100,
  18158. link: function(scope, element, attr) {
  18159. //special case ngPattern when a literal regular expression value
  18160. //is used as the expression (this way we don't have to watch anything).
  18161. if (ngAttr === "ngPattern" && attr.ngPattern.charAt(0) == "/") {
  18162. var match = attr.ngPattern.match(REGEX_STRING_REGEXP);
  18163. if (match) {
  18164. attr.$set("ngPattern", new RegExp(match[1], match[2]));
  18165. return;
  18166. }
  18167. }
  18168. scope.$watch(attr[ngAttr], function ngAttrAliasWatchAction(value) {
  18169. attr.$set(ngAttr, value);
  18170. });
  18171. }
  18172. };
  18173. };
  18174. });
  18175. // ng-src, ng-srcset, ng-href are interpolated
  18176. forEach(['src', 'srcset', 'href'], function(attrName) {
  18177. var normalized = directiveNormalize('ng-' + attrName);
  18178. ngAttributeAliasDirectives[normalized] = function() {
  18179. return {
  18180. priority: 99, // it needs to run after the attributes are interpolated
  18181. link: function(scope, element, attr) {
  18182. var propName = attrName,
  18183. name = attrName;
  18184. if (attrName === 'href' &&
  18185. toString.call(element.prop('href')) === '[object SVGAnimatedString]') {
  18186. name = 'xlinkHref';
  18187. attr.$attr[name] = 'xlink:href';
  18188. propName = null;
  18189. }
  18190. attr.$observe(normalized, function(value) {
  18191. if (!value) {
  18192. if (attrName === 'href') {
  18193. attr.$set(name, null);
  18194. }
  18195. return;
  18196. }
  18197. attr.$set(name, value);
  18198. // on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
  18199. // then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
  18200. // to set the property as well to achieve the desired effect.
  18201. // we use attr[attrName] value since $set can sanitize the url.
  18202. if (msie && propName) element.prop(propName, attr[name]);
  18203. });
  18204. }
  18205. };
  18206. };
  18207. });
  18208. /* global -nullFormCtrl, -SUBMITTED_CLASS, addSetValidityMethod: true
  18209. */
  18210. var nullFormCtrl = {
  18211. $addControl: noop,
  18212. $$renameControl: nullFormRenameControl,
  18213. $removeControl: noop,
  18214. $setValidity: noop,
  18215. $setDirty: noop,
  18216. $setPristine: noop,
  18217. $setSubmitted: noop
  18218. },
  18219. SUBMITTED_CLASS = 'ng-submitted';
  18220. function nullFormRenameControl(control, name) {
  18221. control.$name = name;
  18222. }
  18223. /**
  18224. * @ngdoc type
  18225. * @name form.FormController
  18226. *
  18227. * @property {boolean} $pristine True if user has not interacted with the form yet.
  18228. * @property {boolean} $dirty True if user has already interacted with the form.
  18229. * @property {boolean} $valid True if all of the containing forms and controls are valid.
  18230. * @property {boolean} $invalid True if at least one containing control or form is invalid.
  18231. * @property {boolean} $pending True if at least one containing control or form is pending.
  18232. * @property {boolean} $submitted True if user has submitted the form even if its invalid.
  18233. *
  18234. * @property {Object} $error Is an object hash, containing references to controls or
  18235. * forms with failing validators, where:
  18236. *
  18237. * - keys are validation tokens (error names),
  18238. * - values are arrays of controls or forms that have a failing validator for given error name.
  18239. *
  18240. * Built-in validation tokens:
  18241. *
  18242. * - `email`
  18243. * - `max`
  18244. * - `maxlength`
  18245. * - `min`
  18246. * - `minlength`
  18247. * - `number`
  18248. * - `pattern`
  18249. * - `required`
  18250. * - `url`
  18251. * - `date`
  18252. * - `datetimelocal`
  18253. * - `time`
  18254. * - `week`
  18255. * - `month`
  18256. *
  18257. * @description
  18258. * `FormController` keeps track of all its controls and nested forms as well as the state of them,
  18259. * such as being valid/invalid or dirty/pristine.
  18260. *
  18261. * Each {@link ng.directive:form form} directive creates an instance
  18262. * of `FormController`.
  18263. *
  18264. */
  18265. //asks for $scope to fool the BC controller module
  18266. FormController.$inject = ['$element', '$attrs', '$scope', '$animate', '$interpolate'];
  18267. function FormController(element, attrs, $scope, $animate, $interpolate) {
  18268. var form = this,
  18269. controls = [];
  18270. // init state
  18271. form.$error = {};
  18272. form.$$success = {};
  18273. form.$pending = undefined;
  18274. form.$name = $interpolate(attrs.name || attrs.ngForm || '')($scope);
  18275. form.$dirty = false;
  18276. form.$pristine = true;
  18277. form.$valid = true;
  18278. form.$invalid = false;
  18279. form.$submitted = false;
  18280. form.$$parentForm = nullFormCtrl;
  18281. /**
  18282. * @ngdoc method
  18283. * @name form.FormController#$rollbackViewValue
  18284. *
  18285. * @description
  18286. * Rollback all form controls pending updates to the `$modelValue`.
  18287. *
  18288. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18289. * event defined in `ng-model-options`. This method is typically needed by the reset button of
  18290. * a form that uses `ng-model-options` to pend updates.
  18291. */
  18292. form.$rollbackViewValue = function() {
  18293. forEach(controls, function(control) {
  18294. control.$rollbackViewValue();
  18295. });
  18296. };
  18297. /**
  18298. * @ngdoc method
  18299. * @name form.FormController#$commitViewValue
  18300. *
  18301. * @description
  18302. * Commit all form controls pending updates to the `$modelValue`.
  18303. *
  18304. * Updates may be pending by a debounced event or because the input is waiting for a some future
  18305. * event defined in `ng-model-options`. This method is rarely needed as `NgModelController`
  18306. * usually handles calling this in response to input events.
  18307. */
  18308. form.$commitViewValue = function() {
  18309. forEach(controls, function(control) {
  18310. control.$commitViewValue();
  18311. });
  18312. };
  18313. /**
  18314. * @ngdoc method
  18315. * @name form.FormController#$addControl
  18316. * @param {object} control control object, either a {@link form.FormController} or an
  18317. * {@link ngModel.NgModelController}
  18318. *
  18319. * @description
  18320. * Register a control with the form. Input elements using ngModelController do this automatically
  18321. * when they are linked.
  18322. *
  18323. * Note that the current state of the control will not be reflected on the new parent form. This
  18324. * is not an issue with normal use, as freshly compiled and linked controls are in a `$pristine`
  18325. * state.
  18326. *
  18327. * However, if the method is used programmatically, for example by adding dynamically created controls,
  18328. * or controls that have been previously removed without destroying their corresponding DOM element,
  18329. * it's the developers responsiblity to make sure the current state propagates to the parent form.
  18330. *
  18331. * For example, if an input control is added that is already `$dirty` and has `$error` properties,
  18332. * calling `$setDirty()` and `$validate()` afterwards will propagate the state to the parent form.
  18333. */
  18334. form.$addControl = function(control) {
  18335. // Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
  18336. // and not added to the scope. Now we throw an error.
  18337. assertNotHasOwnProperty(control.$name, 'input');
  18338. controls.push(control);
  18339. if (control.$name) {
  18340. form[control.$name] = control;
  18341. }
  18342. control.$$parentForm = form;
  18343. };
  18344. // Private API: rename a form control
  18345. form.$$renameControl = function(control, newName) {
  18346. var oldName = control.$name;
  18347. if (form[oldName] === control) {
  18348. delete form[oldName];
  18349. }
  18350. form[newName] = control;
  18351. control.$name = newName;
  18352. };
  18353. /**
  18354. * @ngdoc method
  18355. * @name form.FormController#$removeControl
  18356. * @param {object} control control object, either a {@link form.FormController} or an
  18357. * {@link ngModel.NgModelController}
  18358. *
  18359. * @description
  18360. * Deregister a control from the form.
  18361. *
  18362. * Input elements using ngModelController do this automatically when they are destroyed.
  18363. *
  18364. * Note that only the removed control's validation state (`$errors`etc.) will be removed from the
  18365. * form. `$dirty`, `$submitted` states will not be changed, because the expected behavior can be
  18366. * different from case to case. For example, removing the only `$dirty` control from a form may or
  18367. * may not mean that the form is still `$dirty`.
  18368. */
  18369. form.$removeControl = function(control) {
  18370. if (control.$name && form[control.$name] === control) {
  18371. delete form[control.$name];
  18372. }
  18373. forEach(form.$pending, function(value, name) {
  18374. form.$setValidity(name, null, control);
  18375. });
  18376. forEach(form.$error, function(value, name) {
  18377. form.$setValidity(name, null, control);
  18378. });
  18379. forEach(form.$$success, function(value, name) {
  18380. form.$setValidity(name, null, control);
  18381. });
  18382. arrayRemove(controls, control);
  18383. control.$$parentForm = nullFormCtrl;
  18384. };
  18385. /**
  18386. * @ngdoc method
  18387. * @name form.FormController#$setValidity
  18388. *
  18389. * @description
  18390. * Sets the validity of a form control.
  18391. *
  18392. * This method will also propagate to parent forms.
  18393. */
  18394. addSetValidityMethod({
  18395. ctrl: this,
  18396. $element: element,
  18397. set: function(object, property, controller) {
  18398. var list = object[property];
  18399. if (!list) {
  18400. object[property] = [controller];
  18401. } else {
  18402. var index = list.indexOf(controller);
  18403. if (index === -1) {
  18404. list.push(controller);
  18405. }
  18406. }
  18407. },
  18408. unset: function(object, property, controller) {
  18409. var list = object[property];
  18410. if (!list) {
  18411. return;
  18412. }
  18413. arrayRemove(list, controller);
  18414. if (list.length === 0) {
  18415. delete object[property];
  18416. }
  18417. },
  18418. $animate: $animate
  18419. });
  18420. /**
  18421. * @ngdoc method
  18422. * @name form.FormController#$setDirty
  18423. *
  18424. * @description
  18425. * Sets the form to a dirty state.
  18426. *
  18427. * This method can be called to add the 'ng-dirty' class and set the form to a dirty
  18428. * state (ng-dirty class). This method will also propagate to parent forms.
  18429. */
  18430. form.$setDirty = function() {
  18431. $animate.removeClass(element, PRISTINE_CLASS);
  18432. $animate.addClass(element, DIRTY_CLASS);
  18433. form.$dirty = true;
  18434. form.$pristine = false;
  18435. form.$$parentForm.$setDirty();
  18436. };
  18437. /**
  18438. * @ngdoc method
  18439. * @name form.FormController#$setPristine
  18440. *
  18441. * @description
  18442. * Sets the form to its pristine state.
  18443. *
  18444. * This method can be called to remove the 'ng-dirty' class and set the form to its pristine
  18445. * state (ng-pristine class). This method will also propagate to all the controls contained
  18446. * in this form.
  18447. *
  18448. * Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
  18449. * saving or resetting it.
  18450. */
  18451. form.$setPristine = function() {
  18452. $animate.setClass(element, PRISTINE_CLASS, DIRTY_CLASS + ' ' + SUBMITTED_CLASS);
  18453. form.$dirty = false;
  18454. form.$pristine = true;
  18455. form.$submitted = false;
  18456. forEach(controls, function(control) {
  18457. control.$setPristine();
  18458. });
  18459. };
  18460. /**
  18461. * @ngdoc method
  18462. * @name form.FormController#$setUntouched
  18463. *
  18464. * @description
  18465. * Sets the form to its untouched state.
  18466. *
  18467. * This method can be called to remove the 'ng-touched' class and set the form controls to their
  18468. * untouched state (ng-untouched class).
  18469. *
  18470. * Setting a form controls back to their untouched state is often useful when setting the form
  18471. * back to its pristine state.
  18472. */
  18473. form.$setUntouched = function() {
  18474. forEach(controls, function(control) {
  18475. control.$setUntouched();
  18476. });
  18477. };
  18478. /**
  18479. * @ngdoc method
  18480. * @name form.FormController#$setSubmitted
  18481. *
  18482. * @description
  18483. * Sets the form to its submitted state.
  18484. */
  18485. form.$setSubmitted = function() {
  18486. $animate.addClass(element, SUBMITTED_CLASS);
  18487. form.$submitted = true;
  18488. form.$$parentForm.$setSubmitted();
  18489. };
  18490. }
  18491. /**
  18492. * @ngdoc directive
  18493. * @name ngForm
  18494. * @restrict EAC
  18495. *
  18496. * @description
  18497. * Nestable alias of {@link ng.directive:form `form`} directive. HTML
  18498. * does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
  18499. * sub-group of controls needs to be determined.
  18500. *
  18501. * Note: the purpose of `ngForm` is to group controls,
  18502. * but not to be a replacement for the `<form>` tag with all of its capabilities
  18503. * (e.g. posting to the server, ...).
  18504. *
  18505. * @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
  18506. * related scope, under this name.
  18507. *
  18508. */
  18509. /**
  18510. * @ngdoc directive
  18511. * @name form
  18512. * @restrict E
  18513. *
  18514. * @description
  18515. * Directive that instantiates
  18516. * {@link form.FormController FormController}.
  18517. *
  18518. * If the `name` attribute is specified, the form controller is published onto the current scope under
  18519. * this name.
  18520. *
  18521. * # Alias: {@link ng.directive:ngForm `ngForm`}
  18522. *
  18523. * In Angular, forms can be nested. This means that the outer form is valid when all of the child
  18524. * forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
  18525. * Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
  18526. * `<form>` but can be nested. This allows you to have nested forms, which is very useful when
  18527. * using Angular validation directives in forms that are dynamically generated using the
  18528. * {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
  18529. * attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
  18530. * `ngForm` directive and nest these in an outer `form` element.
  18531. *
  18532. *
  18533. * # CSS classes
  18534. * - `ng-valid` is set if the form is valid.
  18535. * - `ng-invalid` is set if the form is invalid.
  18536. * - `ng-pending` is set if the form is pending.
  18537. * - `ng-pristine` is set if the form is pristine.
  18538. * - `ng-dirty` is set if the form is dirty.
  18539. * - `ng-submitted` is set if the form was submitted.
  18540. *
  18541. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  18542. *
  18543. *
  18544. * # Submitting a form and preventing the default action
  18545. *
  18546. * Since the role of forms in client-side Angular applications is different than in classical
  18547. * roundtrip apps, it is desirable for the browser not to translate the form submission into a full
  18548. * page reload that sends the data to the server. Instead some javascript logic should be triggered
  18549. * to handle the form submission in an application-specific way.
  18550. *
  18551. * For this reason, Angular prevents the default action (form submission to the server) unless the
  18552. * `<form>` element has an `action` attribute specified.
  18553. *
  18554. * You can use one of the following two ways to specify what javascript method should be called when
  18555. * a form is submitted:
  18556. *
  18557. * - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
  18558. * - {@link ng.directive:ngClick ngClick} directive on the first
  18559. * button or input field of type submit (input[type=submit])
  18560. *
  18561. * To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
  18562. * or {@link ng.directive:ngClick ngClick} directives.
  18563. * This is because of the following form submission rules in the HTML specification:
  18564. *
  18565. * - If a form has only one input field then hitting enter in this field triggers form submit
  18566. * (`ngSubmit`)
  18567. * - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
  18568. * doesn't trigger submit
  18569. * - if a form has one or more input fields and one or more buttons or input[type=submit] then
  18570. * hitting enter in any of the input fields will trigger the click handler on the *first* button or
  18571. * input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
  18572. *
  18573. * Any pending `ngModelOptions` changes will take place immediately when an enclosing form is
  18574. * submitted. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  18575. * to have access to the updated model.
  18576. *
  18577. * ## Animation Hooks
  18578. *
  18579. * Animations in ngForm are triggered when any of the associated CSS classes are added and removed.
  18580. * These classes are: `.ng-pristine`, `.ng-dirty`, `.ng-invalid` and `.ng-valid` as well as any
  18581. * other validations that are performed within the form. Animations in ngForm are similar to how
  18582. * they work in ngClass and animations can be hooked into using CSS transitions, keyframes as well
  18583. * as JS animations.
  18584. *
  18585. * The following example shows a simple way to utilize CSS transitions to style a form element
  18586. * that has been rendered as invalid after it has been validated:
  18587. *
  18588. * <pre>
  18589. * //be sure to include ngAnimate as a module to hook into more
  18590. * //advanced animations
  18591. * .my-form {
  18592. * transition:0.5s linear all;
  18593. * background: white;
  18594. * }
  18595. * .my-form.ng-invalid {
  18596. * background: red;
  18597. * color:white;
  18598. * }
  18599. * </pre>
  18600. *
  18601. * @example
  18602. <example deps="angular-animate.js" animations="true" fixBase="true" module="formExample">
  18603. <file name="index.html">
  18604. <script>
  18605. angular.module('formExample', [])
  18606. .controller('FormController', ['$scope', function($scope) {
  18607. $scope.userType = 'guest';
  18608. }]);
  18609. </script>
  18610. <style>
  18611. .my-form {
  18612. transition:all linear 0.5s;
  18613. background: transparent;
  18614. }
  18615. .my-form.ng-invalid {
  18616. background: red;
  18617. }
  18618. </style>
  18619. <form name="myForm" ng-controller="FormController" class="my-form">
  18620. userType: <input name="input" ng-model="userType" required>
  18621. <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
  18622. <code>userType = {{userType}}</code><br>
  18623. <code>myForm.input.$valid = {{myForm.input.$valid}}</code><br>
  18624. <code>myForm.input.$error = {{myForm.input.$error}}</code><br>
  18625. <code>myForm.$valid = {{myForm.$valid}}</code><br>
  18626. <code>myForm.$error.required = {{!!myForm.$error.required}}</code><br>
  18627. </form>
  18628. </file>
  18629. <file name="protractor.js" type="protractor">
  18630. it('should initialize to model', function() {
  18631. var userType = element(by.binding('userType'));
  18632. var valid = element(by.binding('myForm.input.$valid'));
  18633. expect(userType.getText()).toContain('guest');
  18634. expect(valid.getText()).toContain('true');
  18635. });
  18636. it('should be invalid if empty', function() {
  18637. var userType = element(by.binding('userType'));
  18638. var valid = element(by.binding('myForm.input.$valid'));
  18639. var userInput = element(by.model('userType'));
  18640. userInput.clear();
  18641. userInput.sendKeys('');
  18642. expect(userType.getText()).toEqual('userType =');
  18643. expect(valid.getText()).toContain('false');
  18644. });
  18645. </file>
  18646. </example>
  18647. *
  18648. * @param {string=} name Name of the form. If specified, the form controller will be published into
  18649. * related scope, under this name.
  18650. */
  18651. var formDirectiveFactory = function(isNgForm) {
  18652. return ['$timeout', '$parse', function($timeout, $parse) {
  18653. var formDirective = {
  18654. name: 'form',
  18655. restrict: isNgForm ? 'EAC' : 'E',
  18656. require: ['form', '^^?form'], //first is the form's own ctrl, second is an optional parent form
  18657. controller: FormController,
  18658. compile: function ngFormCompile(formElement, attr) {
  18659. // Setup initial state of the control
  18660. formElement.addClass(PRISTINE_CLASS).addClass(VALID_CLASS);
  18661. var nameAttr = attr.name ? 'name' : (isNgForm && attr.ngForm ? 'ngForm' : false);
  18662. return {
  18663. pre: function ngFormPreLink(scope, formElement, attr, ctrls) {
  18664. var controller = ctrls[0];
  18665. // if `action` attr is not present on the form, prevent the default action (submission)
  18666. if (!('action' in attr)) {
  18667. // we can't use jq events because if a form is destroyed during submission the default
  18668. // action is not prevented. see #1238
  18669. //
  18670. // IE 9 is not affected because it doesn't fire a submit event and try to do a full
  18671. // page reload if the form was destroyed by submission of the form via a click handler
  18672. // on a button in the form. Looks like an IE9 specific bug.
  18673. var handleFormSubmission = function(event) {
  18674. scope.$apply(function() {
  18675. controller.$commitViewValue();
  18676. controller.$setSubmitted();
  18677. });
  18678. event.preventDefault();
  18679. };
  18680. addEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18681. // unregister the preventDefault listener so that we don't not leak memory but in a
  18682. // way that will achieve the prevention of the default action.
  18683. formElement.on('$destroy', function() {
  18684. $timeout(function() {
  18685. removeEventListenerFn(formElement[0], 'submit', handleFormSubmission);
  18686. }, 0, false);
  18687. });
  18688. }
  18689. var parentFormCtrl = ctrls[1] || controller.$$parentForm;
  18690. parentFormCtrl.$addControl(controller);
  18691. var setter = nameAttr ? getSetter(controller.$name) : noop;
  18692. if (nameAttr) {
  18693. setter(scope, controller);
  18694. attr.$observe(nameAttr, function(newValue) {
  18695. if (controller.$name === newValue) return;
  18696. setter(scope, undefined);
  18697. controller.$$parentForm.$$renameControl(controller, newValue);
  18698. setter = getSetter(controller.$name);
  18699. setter(scope, controller);
  18700. });
  18701. }
  18702. formElement.on('$destroy', function() {
  18703. controller.$$parentForm.$removeControl(controller);
  18704. setter(scope, undefined);
  18705. extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
  18706. });
  18707. }
  18708. };
  18709. }
  18710. };
  18711. return formDirective;
  18712. function getSetter(expression) {
  18713. if (expression === '') {
  18714. //create an assignable expression, so forms with an empty name can be renamed later
  18715. return $parse('this[""]').assign;
  18716. }
  18717. return $parse(expression).assign || noop;
  18718. }
  18719. }];
  18720. };
  18721. var formDirective = formDirectiveFactory();
  18722. var ngFormDirective = formDirectiveFactory(true);
  18723. /* global VALID_CLASS: false,
  18724. INVALID_CLASS: false,
  18725. PRISTINE_CLASS: false,
  18726. DIRTY_CLASS: false,
  18727. UNTOUCHED_CLASS: false,
  18728. TOUCHED_CLASS: false,
  18729. ngModelMinErr: false,
  18730. */
  18731. // Regex code is obtained from SO: https://stackoverflow.com/questions/3143070/javascript-regex-iso-datetime#answer-3143231
  18732. 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)/;
  18733. // See valid URLs in RFC3987 (http://tools.ietf.org/html/rfc3987)
  18734. var URL_REGEXP = /^[A-Za-z][A-Za-z\d.+-]*:\/*(?:\w+(?::\w+)?@)?[^\s/]+(?::\d+)?(?:\/[\w#!:.?+=&%@\-/]*)?$/;
  18735. 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;
  18736. var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))([eE][+-]?\d+)?\s*$/;
  18737. var DATE_REGEXP = /^(\d{4})-(\d{2})-(\d{2})$/;
  18738. var DATETIMELOCAL_REGEXP = /^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18739. var WEEK_REGEXP = /^(\d{4})-W(\d\d)$/;
  18740. var MONTH_REGEXP = /^(\d{4})-(\d\d)$/;
  18741. var TIME_REGEXP = /^(\d\d):(\d\d)(?::(\d\d)(\.\d{1,3})?)?$/;
  18742. var inputType = {
  18743. /**
  18744. * @ngdoc input
  18745. * @name input[text]
  18746. *
  18747. * @description
  18748. * Standard HTML text input with angular data binding, inherited by most of the `input` elements.
  18749. *
  18750. *
  18751. * @param {string} ngModel Assignable angular expression to data-bind to.
  18752. * @param {string=} name Property name of the form under which the control is published.
  18753. * @param {string=} required Adds `required` validation error key if the value is not entered.
  18754. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18755. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18756. * `required` when you want to data-bind to the `required` attribute.
  18757. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  18758. * minlength.
  18759. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  18760. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  18761. * any length.
  18762. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  18763. * that contains the regular expression body that will be converted to a regular expression
  18764. * as in the ngPattern directive.
  18765. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  18766. * a RegExp found by evaluating the Angular expression given in the attribute value.
  18767. * If the expression evaluates to a RegExp object, then this is used directly.
  18768. * If the expression evaluates to a string, then it will be converted to a RegExp
  18769. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  18770. * `new RegExp('^abc$')`.<br />
  18771. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  18772. * start at the index of the last search's match, thus not taking the whole input value into
  18773. * account.
  18774. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18775. * interaction with the input element.
  18776. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  18777. * This parameter is ignored for input[type=password] controls, which will never trim the
  18778. * input.
  18779. *
  18780. * @example
  18781. <example name="text-input-directive" module="textInputExample">
  18782. <file name="index.html">
  18783. <script>
  18784. angular.module('textInputExample', [])
  18785. .controller('ExampleController', ['$scope', function($scope) {
  18786. $scope.example = {
  18787. text: 'guest',
  18788. word: /^\s*\w*\s*$/
  18789. };
  18790. }]);
  18791. </script>
  18792. <form name="myForm" ng-controller="ExampleController">
  18793. <label>Single word:
  18794. <input type="text" name="input" ng-model="example.text"
  18795. ng-pattern="example.word" required ng-trim="false">
  18796. </label>
  18797. <div role="alert">
  18798. <span class="error" ng-show="myForm.input.$error.required">
  18799. Required!</span>
  18800. <span class="error" ng-show="myForm.input.$error.pattern">
  18801. Single word only!</span>
  18802. </div>
  18803. <tt>text = {{example.text}}</tt><br/>
  18804. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18805. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18806. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18807. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18808. </form>
  18809. </file>
  18810. <file name="protractor.js" type="protractor">
  18811. var text = element(by.binding('example.text'));
  18812. var valid = element(by.binding('myForm.input.$valid'));
  18813. var input = element(by.model('example.text'));
  18814. it('should initialize to model', function() {
  18815. expect(text.getText()).toContain('guest');
  18816. expect(valid.getText()).toContain('true');
  18817. });
  18818. it('should be invalid if empty', function() {
  18819. input.clear();
  18820. input.sendKeys('');
  18821. expect(text.getText()).toEqual('text =');
  18822. expect(valid.getText()).toContain('false');
  18823. });
  18824. it('should be invalid if multi word', function() {
  18825. input.clear();
  18826. input.sendKeys('hello world');
  18827. expect(valid.getText()).toContain('false');
  18828. });
  18829. </file>
  18830. </example>
  18831. */
  18832. 'text': textInputType,
  18833. /**
  18834. * @ngdoc input
  18835. * @name input[date]
  18836. *
  18837. * @description
  18838. * Input with date validation and transformation. In browsers that do not yet support
  18839. * the HTML5 date input, a text element will be used. In that case, text must be entered in a valid ISO-8601
  18840. * date format (yyyy-MM-dd), for example: `2009-01-06`. Since many
  18841. * modern browsers do not yet support this input type, it is important to provide cues to users on the
  18842. * expected input format via a placeholder or label.
  18843. *
  18844. * The model must always be a Date object, otherwise Angular will throw an error.
  18845. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18846. *
  18847. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18848. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18849. *
  18850. * @param {string} ngModel Assignable angular expression to data-bind to.
  18851. * @param {string=} name Property name of the form under which the control is published.
  18852. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`. This must be a
  18853. * valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  18854. * (e.g. `min="{{minDate | date:'yyyy-MM-dd'}}"`). Note that `min` will also add native HTML5
  18855. * constraint validation.
  18856. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`. This must be
  18857. * a valid ISO date string (yyyy-MM-dd). You can also use interpolation inside this attribute
  18858. * (e.g. `max="{{maxDate | date:'yyyy-MM-dd'}}"`). Note that `max` will also add native HTML5
  18859. * constraint validation.
  18860. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO date string
  18861. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  18862. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO date string
  18863. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  18864. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18865. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18866. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18867. * `required` when you want to data-bind to the `required` attribute.
  18868. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18869. * interaction with the input element.
  18870. *
  18871. * @example
  18872. <example name="date-input-directive" module="dateInputExample">
  18873. <file name="index.html">
  18874. <script>
  18875. angular.module('dateInputExample', [])
  18876. .controller('DateController', ['$scope', function($scope) {
  18877. $scope.example = {
  18878. value: new Date(2013, 9, 22)
  18879. };
  18880. }]);
  18881. </script>
  18882. <form name="myForm" ng-controller="DateController as dateCtrl">
  18883. <label for="exampleInput">Pick a date in 2013:</label>
  18884. <input type="date" id="exampleInput" name="input" ng-model="example.value"
  18885. placeholder="yyyy-MM-dd" min="2013-01-01" max="2013-12-31" required />
  18886. <div role="alert">
  18887. <span class="error" ng-show="myForm.input.$error.required">
  18888. Required!</span>
  18889. <span class="error" ng-show="myForm.input.$error.date">
  18890. Not a valid date!</span>
  18891. </div>
  18892. <tt>value = {{example.value | date: "yyyy-MM-dd"}}</tt><br/>
  18893. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18894. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18895. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18896. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18897. </form>
  18898. </file>
  18899. <file name="protractor.js" type="protractor">
  18900. var value = element(by.binding('example.value | date: "yyyy-MM-dd"'));
  18901. var valid = element(by.binding('myForm.input.$valid'));
  18902. var input = element(by.model('example.value'));
  18903. // currently protractor/webdriver does not support
  18904. // sending keys to all known HTML5 input controls
  18905. // for various browsers (see https://github.com/angular/protractor/issues/562).
  18906. function setInput(val) {
  18907. // set the value of the element and force validation.
  18908. var scr = "var ipt = document.getElementById('exampleInput'); " +
  18909. "ipt.value = '" + val + "';" +
  18910. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  18911. browser.executeScript(scr);
  18912. }
  18913. it('should initialize to model', function() {
  18914. expect(value.getText()).toContain('2013-10-22');
  18915. expect(valid.getText()).toContain('myForm.input.$valid = true');
  18916. });
  18917. it('should be invalid if empty', function() {
  18918. setInput('');
  18919. expect(value.getText()).toEqual('value =');
  18920. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18921. });
  18922. it('should be invalid if over max', function() {
  18923. setInput('2015-01-01');
  18924. expect(value.getText()).toContain('');
  18925. expect(valid.getText()).toContain('myForm.input.$valid = false');
  18926. });
  18927. </file>
  18928. </example>
  18929. */
  18930. 'date': createDateInputType('date', DATE_REGEXP,
  18931. createDateParser(DATE_REGEXP, ['yyyy', 'MM', 'dd']),
  18932. 'yyyy-MM-dd'),
  18933. /**
  18934. * @ngdoc input
  18935. * @name input[datetime-local]
  18936. *
  18937. * @description
  18938. * Input with datetime validation and transformation. In browsers that do not yet support
  18939. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  18940. * local datetime format (yyyy-MM-ddTHH:mm:ss), for example: `2010-12-28T14:57:00`.
  18941. *
  18942. * The model must always be a Date object, otherwise Angular will throw an error.
  18943. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  18944. *
  18945. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  18946. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  18947. *
  18948. * @param {string} ngModel Assignable angular expression to data-bind to.
  18949. * @param {string=} name Property name of the form under which the control is published.
  18950. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  18951. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  18952. * inside this attribute (e.g. `min="{{minDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  18953. * Note that `min` will also add native HTML5 constraint validation.
  18954. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  18955. * This must be a valid ISO datetime format (yyyy-MM-ddTHH:mm:ss). You can also use interpolation
  18956. * inside this attribute (e.g. `max="{{maxDatetimeLocal | date:'yyyy-MM-ddTHH:mm:ss'}}"`).
  18957. * Note that `max` will also add native HTML5 constraint validation.
  18958. * @param {(date|string)=} ngMin Sets the `min` validation error key to the Date / ISO datetime string
  18959. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  18960. * @param {(date|string)=} ngMax Sets the `max` validation error key to the Date / ISO datetime string
  18961. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  18962. * @param {string=} required Sets `required` validation error key if the value is not entered.
  18963. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  18964. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  18965. * `required` when you want to data-bind to the `required` attribute.
  18966. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  18967. * interaction with the input element.
  18968. *
  18969. * @example
  18970. <example name="datetimelocal-input-directive" module="dateExample">
  18971. <file name="index.html">
  18972. <script>
  18973. angular.module('dateExample', [])
  18974. .controller('DateController', ['$scope', function($scope) {
  18975. $scope.example = {
  18976. value: new Date(2010, 11, 28, 14, 57)
  18977. };
  18978. }]);
  18979. </script>
  18980. <form name="myForm" ng-controller="DateController as dateCtrl">
  18981. <label for="exampleInput">Pick a date between in 2013:</label>
  18982. <input type="datetime-local" id="exampleInput" name="input" ng-model="example.value"
  18983. placeholder="yyyy-MM-ddTHH:mm:ss" min="2001-01-01T00:00:00" max="2013-12-31T00:00:00" required />
  18984. <div role="alert">
  18985. <span class="error" ng-show="myForm.input.$error.required">
  18986. Required!</span>
  18987. <span class="error" ng-show="myForm.input.$error.datetimelocal">
  18988. Not a valid date!</span>
  18989. </div>
  18990. <tt>value = {{example.value | date: "yyyy-MM-ddTHH:mm:ss"}}</tt><br/>
  18991. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  18992. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  18993. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  18994. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  18995. </form>
  18996. </file>
  18997. <file name="protractor.js" type="protractor">
  18998. var value = element(by.binding('example.value | date: "yyyy-MM-ddTHH:mm:ss"'));
  18999. var valid = element(by.binding('myForm.input.$valid'));
  19000. var input = element(by.model('example.value'));
  19001. // currently protractor/webdriver does not support
  19002. // sending keys to all known HTML5 input controls
  19003. // for various browsers (https://github.com/angular/protractor/issues/562).
  19004. function setInput(val) {
  19005. // set the value of the element and force validation.
  19006. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19007. "ipt.value = '" + val + "';" +
  19008. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19009. browser.executeScript(scr);
  19010. }
  19011. it('should initialize to model', function() {
  19012. expect(value.getText()).toContain('2010-12-28T14:57:00');
  19013. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19014. });
  19015. it('should be invalid if empty', function() {
  19016. setInput('');
  19017. expect(value.getText()).toEqual('value =');
  19018. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19019. });
  19020. it('should be invalid if over max', function() {
  19021. setInput('2015-01-01T23:59:00');
  19022. expect(value.getText()).toContain('');
  19023. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19024. });
  19025. </file>
  19026. </example>
  19027. */
  19028. 'datetime-local': createDateInputType('datetimelocal', DATETIMELOCAL_REGEXP,
  19029. createDateParser(DATETIMELOCAL_REGEXP, ['yyyy', 'MM', 'dd', 'HH', 'mm', 'ss', 'sss']),
  19030. 'yyyy-MM-ddTHH:mm:ss.sss'),
  19031. /**
  19032. * @ngdoc input
  19033. * @name input[time]
  19034. *
  19035. * @description
  19036. * Input with time validation and transformation. In browsers that do not yet support
  19037. * the HTML5 date input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19038. * local time format (HH:mm:ss), for example: `14:57:00`. Model must be a Date object. This binding will always output a
  19039. * Date object to the model of January 1, 1970, or local date `new Date(1970, 0, 1, HH, mm, ss)`.
  19040. *
  19041. * The model must always be a Date object, otherwise Angular will throw an error.
  19042. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19043. *
  19044. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19045. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19046. *
  19047. * @param {string} ngModel Assignable angular expression to data-bind to.
  19048. * @param {string=} name Property name of the form under which the control is published.
  19049. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19050. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  19051. * attribute (e.g. `min="{{minTime | date:'HH:mm:ss'}}"`). Note that `min` will also add
  19052. * native HTML5 constraint validation.
  19053. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19054. * This must be a valid ISO time format (HH:mm:ss). You can also use interpolation inside this
  19055. * attribute (e.g. `max="{{maxTime | date:'HH:mm:ss'}}"`). Note that `max` will also add
  19056. * native HTML5 constraint validation.
  19057. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO time string the
  19058. * `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19059. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO time string the
  19060. * `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19061. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19062. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19063. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19064. * `required` when you want to data-bind to the `required` attribute.
  19065. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19066. * interaction with the input element.
  19067. *
  19068. * @example
  19069. <example name="time-input-directive" module="timeExample">
  19070. <file name="index.html">
  19071. <script>
  19072. angular.module('timeExample', [])
  19073. .controller('DateController', ['$scope', function($scope) {
  19074. $scope.example = {
  19075. value: new Date(1970, 0, 1, 14, 57, 0)
  19076. };
  19077. }]);
  19078. </script>
  19079. <form name="myForm" ng-controller="DateController as dateCtrl">
  19080. <label for="exampleInput">Pick a between 8am and 5pm:</label>
  19081. <input type="time" id="exampleInput" name="input" ng-model="example.value"
  19082. placeholder="HH:mm:ss" min="08:00:00" max="17:00:00" required />
  19083. <div role="alert">
  19084. <span class="error" ng-show="myForm.input.$error.required">
  19085. Required!</span>
  19086. <span class="error" ng-show="myForm.input.$error.time">
  19087. Not a valid date!</span>
  19088. </div>
  19089. <tt>value = {{example.value | date: "HH:mm:ss"}}</tt><br/>
  19090. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19091. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19092. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19093. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19094. </form>
  19095. </file>
  19096. <file name="protractor.js" type="protractor">
  19097. var value = element(by.binding('example.value | date: "HH:mm:ss"'));
  19098. var valid = element(by.binding('myForm.input.$valid'));
  19099. var input = element(by.model('example.value'));
  19100. // currently protractor/webdriver does not support
  19101. // sending keys to all known HTML5 input controls
  19102. // for various browsers (https://github.com/angular/protractor/issues/562).
  19103. function setInput(val) {
  19104. // set the value of the element and force validation.
  19105. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19106. "ipt.value = '" + val + "';" +
  19107. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19108. browser.executeScript(scr);
  19109. }
  19110. it('should initialize to model', function() {
  19111. expect(value.getText()).toContain('14:57:00');
  19112. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19113. });
  19114. it('should be invalid if empty', function() {
  19115. setInput('');
  19116. expect(value.getText()).toEqual('value =');
  19117. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19118. });
  19119. it('should be invalid if over max', function() {
  19120. setInput('23:59:00');
  19121. expect(value.getText()).toContain('');
  19122. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19123. });
  19124. </file>
  19125. </example>
  19126. */
  19127. 'time': createDateInputType('time', TIME_REGEXP,
  19128. createDateParser(TIME_REGEXP, ['HH', 'mm', 'ss', 'sss']),
  19129. 'HH:mm:ss.sss'),
  19130. /**
  19131. * @ngdoc input
  19132. * @name input[week]
  19133. *
  19134. * @description
  19135. * Input with week-of-the-year validation and transformation to Date. In browsers that do not yet support
  19136. * the HTML5 week input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19137. * week format (yyyy-W##), for example: `2013-W02`.
  19138. *
  19139. * The model must always be a Date object, otherwise Angular will throw an error.
  19140. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19141. *
  19142. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19143. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19144. *
  19145. * @param {string} ngModel Assignable angular expression to data-bind to.
  19146. * @param {string=} name Property name of the form under which the control is published.
  19147. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19148. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  19149. * attribute (e.g. `min="{{minWeek | date:'yyyy-Www'}}"`). Note that `min` will also add
  19150. * native HTML5 constraint validation.
  19151. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19152. * This must be a valid ISO week format (yyyy-W##). You can also use interpolation inside this
  19153. * attribute (e.g. `max="{{maxWeek | date:'yyyy-Www'}}"`). Note that `max` will also add
  19154. * native HTML5 constraint validation.
  19155. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  19156. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19157. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  19158. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19159. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19160. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19161. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19162. * `required` when you want to data-bind to the `required` attribute.
  19163. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19164. * interaction with the input element.
  19165. *
  19166. * @example
  19167. <example name="week-input-directive" module="weekExample">
  19168. <file name="index.html">
  19169. <script>
  19170. angular.module('weekExample', [])
  19171. .controller('DateController', ['$scope', function($scope) {
  19172. $scope.example = {
  19173. value: new Date(2013, 0, 3)
  19174. };
  19175. }]);
  19176. </script>
  19177. <form name="myForm" ng-controller="DateController as dateCtrl">
  19178. <label>Pick a date between in 2013:
  19179. <input id="exampleInput" type="week" name="input" ng-model="example.value"
  19180. placeholder="YYYY-W##" min="2012-W32"
  19181. max="2013-W52" required />
  19182. </label>
  19183. <div role="alert">
  19184. <span class="error" ng-show="myForm.input.$error.required">
  19185. Required!</span>
  19186. <span class="error" ng-show="myForm.input.$error.week">
  19187. Not a valid date!</span>
  19188. </div>
  19189. <tt>value = {{example.value | date: "yyyy-Www"}}</tt><br/>
  19190. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19191. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19192. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19193. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19194. </form>
  19195. </file>
  19196. <file name="protractor.js" type="protractor">
  19197. var value = element(by.binding('example.value | date: "yyyy-Www"'));
  19198. var valid = element(by.binding('myForm.input.$valid'));
  19199. var input = element(by.model('example.value'));
  19200. // currently protractor/webdriver does not support
  19201. // sending keys to all known HTML5 input controls
  19202. // for various browsers (https://github.com/angular/protractor/issues/562).
  19203. function setInput(val) {
  19204. // set the value of the element and force validation.
  19205. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19206. "ipt.value = '" + val + "';" +
  19207. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19208. browser.executeScript(scr);
  19209. }
  19210. it('should initialize to model', function() {
  19211. expect(value.getText()).toContain('2013-W01');
  19212. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19213. });
  19214. it('should be invalid if empty', function() {
  19215. setInput('');
  19216. expect(value.getText()).toEqual('value =');
  19217. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19218. });
  19219. it('should be invalid if over max', function() {
  19220. setInput('2015-W01');
  19221. expect(value.getText()).toContain('');
  19222. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19223. });
  19224. </file>
  19225. </example>
  19226. */
  19227. 'week': createDateInputType('week', WEEK_REGEXP, weekParser, 'yyyy-Www'),
  19228. /**
  19229. * @ngdoc input
  19230. * @name input[month]
  19231. *
  19232. * @description
  19233. * Input with month validation and transformation. In browsers that do not yet support
  19234. * the HTML5 month input, a text element will be used. In that case, the text must be entered in a valid ISO-8601
  19235. * month format (yyyy-MM), for example: `2009-01`.
  19236. *
  19237. * The model must always be a Date object, otherwise Angular will throw an error.
  19238. * Invalid `Date` objects (dates whose `getTime()` is `NaN`) will be rendered as an empty string.
  19239. * If the model is not set to the first of the month, the next view to model update will set it
  19240. * to the first of the month.
  19241. *
  19242. * The timezone to be used to read/write the `Date` instance in the model can be defined using
  19243. * {@link ng.directive:ngModelOptions ngModelOptions}. By default, this is the timezone of the browser.
  19244. *
  19245. * @param {string} ngModel Assignable angular expression to data-bind to.
  19246. * @param {string=} name Property name of the form under which the control is published.
  19247. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19248. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  19249. * attribute (e.g. `min="{{minMonth | date:'yyyy-MM'}}"`). Note that `min` will also add
  19250. * native HTML5 constraint validation.
  19251. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19252. * This must be a valid ISO month format (yyyy-MM). You can also use interpolation inside this
  19253. * attribute (e.g. `max="{{maxMonth | date:'yyyy-MM'}}"`). Note that `max` will also add
  19254. * native HTML5 constraint validation.
  19255. * @param {(date|string)=} ngMin Sets the `min` validation constraint to the Date / ISO week string
  19256. * the `ngMin` expression evaluates to. Note that it does not set the `min` attribute.
  19257. * @param {(date|string)=} ngMax Sets the `max` validation constraint to the Date / ISO week string
  19258. * the `ngMax` expression evaluates to. Note that it does not set the `max` attribute.
  19259. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19260. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19261. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19262. * `required` when you want to data-bind to the `required` attribute.
  19263. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19264. * interaction with the input element.
  19265. *
  19266. * @example
  19267. <example name="month-input-directive" module="monthExample">
  19268. <file name="index.html">
  19269. <script>
  19270. angular.module('monthExample', [])
  19271. .controller('DateController', ['$scope', function($scope) {
  19272. $scope.example = {
  19273. value: new Date(2013, 9, 1)
  19274. };
  19275. }]);
  19276. </script>
  19277. <form name="myForm" ng-controller="DateController as dateCtrl">
  19278. <label for="exampleInput">Pick a month in 2013:</label>
  19279. <input id="exampleInput" type="month" name="input" ng-model="example.value"
  19280. placeholder="yyyy-MM" min="2013-01" max="2013-12" required />
  19281. <div role="alert">
  19282. <span class="error" ng-show="myForm.input.$error.required">
  19283. Required!</span>
  19284. <span class="error" ng-show="myForm.input.$error.month">
  19285. Not a valid month!</span>
  19286. </div>
  19287. <tt>value = {{example.value | date: "yyyy-MM"}}</tt><br/>
  19288. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19289. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19290. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19291. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19292. </form>
  19293. </file>
  19294. <file name="protractor.js" type="protractor">
  19295. var value = element(by.binding('example.value | date: "yyyy-MM"'));
  19296. var valid = element(by.binding('myForm.input.$valid'));
  19297. var input = element(by.model('example.value'));
  19298. // currently protractor/webdriver does not support
  19299. // sending keys to all known HTML5 input controls
  19300. // for various browsers (https://github.com/angular/protractor/issues/562).
  19301. function setInput(val) {
  19302. // set the value of the element and force validation.
  19303. var scr = "var ipt = document.getElementById('exampleInput'); " +
  19304. "ipt.value = '" + val + "';" +
  19305. "angular.element(ipt).scope().$apply(function(s) { s.myForm[ipt.name].$setViewValue('" + val + "'); });";
  19306. browser.executeScript(scr);
  19307. }
  19308. it('should initialize to model', function() {
  19309. expect(value.getText()).toContain('2013-10');
  19310. expect(valid.getText()).toContain('myForm.input.$valid = true');
  19311. });
  19312. it('should be invalid if empty', function() {
  19313. setInput('');
  19314. expect(value.getText()).toEqual('value =');
  19315. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19316. });
  19317. it('should be invalid if over max', function() {
  19318. setInput('2015-01');
  19319. expect(value.getText()).toContain('');
  19320. expect(valid.getText()).toContain('myForm.input.$valid = false');
  19321. });
  19322. </file>
  19323. </example>
  19324. */
  19325. 'month': createDateInputType('month', MONTH_REGEXP,
  19326. createDateParser(MONTH_REGEXP, ['yyyy', 'MM']),
  19327. 'yyyy-MM'),
  19328. /**
  19329. * @ngdoc input
  19330. * @name input[number]
  19331. *
  19332. * @description
  19333. * Text input with number validation and transformation. Sets the `number` validation
  19334. * error if not a valid number.
  19335. *
  19336. * <div class="alert alert-warning">
  19337. * The model must always be of type `number` otherwise Angular will throw an error.
  19338. * Be aware that a string containing a number is not enough. See the {@link ngModel:numfmt}
  19339. * error docs for more information and an example of how to convert your model if necessary.
  19340. * </div>
  19341. *
  19342. * ## Issues with HTML5 constraint validation
  19343. *
  19344. * In browsers that follow the
  19345. * [HTML5 specification](https://html.spec.whatwg.org/multipage/forms.html#number-state-%28type=number%29),
  19346. * `input[number]` does not work as expected with {@link ngModelOptions `ngModelOptions.allowInvalid`}.
  19347. * If a non-number is entered in the input, the browser will report the value as an empty string,
  19348. * which means the view / model values in `ngModel` and subsequently the scope value
  19349. * will also be an empty string.
  19350. *
  19351. *
  19352. * @param {string} ngModel Assignable angular expression to data-bind to.
  19353. * @param {string=} name Property name of the form under which the control is published.
  19354. * @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
  19355. * @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
  19356. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19357. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19358. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19359. * `required` when you want to data-bind to the `required` attribute.
  19360. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19361. * minlength.
  19362. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19363. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19364. * any length.
  19365. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19366. * that contains the regular expression body that will be converted to a regular expression
  19367. * as in the ngPattern directive.
  19368. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19369. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19370. * If the expression evaluates to a RegExp object, then this is used directly.
  19371. * If the expression evaluates to a string, then it will be converted to a RegExp
  19372. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19373. * `new RegExp('^abc$')`.<br />
  19374. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19375. * start at the index of the last search's match, thus not taking the whole input value into
  19376. * account.
  19377. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19378. * interaction with the input element.
  19379. *
  19380. * @example
  19381. <example name="number-input-directive" module="numberExample">
  19382. <file name="index.html">
  19383. <script>
  19384. angular.module('numberExample', [])
  19385. .controller('ExampleController', ['$scope', function($scope) {
  19386. $scope.example = {
  19387. value: 12
  19388. };
  19389. }]);
  19390. </script>
  19391. <form name="myForm" ng-controller="ExampleController">
  19392. <label>Number:
  19393. <input type="number" name="input" ng-model="example.value"
  19394. min="0" max="99" required>
  19395. </label>
  19396. <div role="alert">
  19397. <span class="error" ng-show="myForm.input.$error.required">
  19398. Required!</span>
  19399. <span class="error" ng-show="myForm.input.$error.number">
  19400. Not valid number!</span>
  19401. </div>
  19402. <tt>value = {{example.value}}</tt><br/>
  19403. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19404. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19405. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19406. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19407. </form>
  19408. </file>
  19409. <file name="protractor.js" type="protractor">
  19410. var value = element(by.binding('example.value'));
  19411. var valid = element(by.binding('myForm.input.$valid'));
  19412. var input = element(by.model('example.value'));
  19413. it('should initialize to model', function() {
  19414. expect(value.getText()).toContain('12');
  19415. expect(valid.getText()).toContain('true');
  19416. });
  19417. it('should be invalid if empty', function() {
  19418. input.clear();
  19419. input.sendKeys('');
  19420. expect(value.getText()).toEqual('value =');
  19421. expect(valid.getText()).toContain('false');
  19422. });
  19423. it('should be invalid if over max', function() {
  19424. input.clear();
  19425. input.sendKeys('123');
  19426. expect(value.getText()).toEqual('value =');
  19427. expect(valid.getText()).toContain('false');
  19428. });
  19429. </file>
  19430. </example>
  19431. */
  19432. 'number': numberInputType,
  19433. /**
  19434. * @ngdoc input
  19435. * @name input[url]
  19436. *
  19437. * @description
  19438. * Text input with URL validation. Sets the `url` validation error key if the content is not a
  19439. * valid URL.
  19440. *
  19441. * <div class="alert alert-warning">
  19442. * **Note:** `input[url]` uses a regex to validate urls that is derived from the regex
  19443. * used in Chromium. If you need stricter validation, you can use `ng-pattern` or modify
  19444. * the built-in validators (see the {@link guide/forms Forms guide})
  19445. * </div>
  19446. *
  19447. * @param {string} ngModel Assignable angular expression to data-bind to.
  19448. * @param {string=} name Property name of the form under which the control is published.
  19449. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19450. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19451. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19452. * `required` when you want to data-bind to the `required` attribute.
  19453. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19454. * minlength.
  19455. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19456. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19457. * any length.
  19458. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19459. * that contains the regular expression body that will be converted to a regular expression
  19460. * as in the ngPattern directive.
  19461. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19462. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19463. * If the expression evaluates to a RegExp object, then this is used directly.
  19464. * If the expression evaluates to a string, then it will be converted to a RegExp
  19465. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19466. * `new RegExp('^abc$')`.<br />
  19467. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19468. * start at the index of the last search's match, thus not taking the whole input value into
  19469. * account.
  19470. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19471. * interaction with the input element.
  19472. *
  19473. * @example
  19474. <example name="url-input-directive" module="urlExample">
  19475. <file name="index.html">
  19476. <script>
  19477. angular.module('urlExample', [])
  19478. .controller('ExampleController', ['$scope', function($scope) {
  19479. $scope.url = {
  19480. text: 'http://google.com'
  19481. };
  19482. }]);
  19483. </script>
  19484. <form name="myForm" ng-controller="ExampleController">
  19485. <label>URL:
  19486. <input type="url" name="input" ng-model="url.text" required>
  19487. <label>
  19488. <div role="alert">
  19489. <span class="error" ng-show="myForm.input.$error.required">
  19490. Required!</span>
  19491. <span class="error" ng-show="myForm.input.$error.url">
  19492. Not valid url!</span>
  19493. </div>
  19494. <tt>text = {{url.text}}</tt><br/>
  19495. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19496. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19497. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19498. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19499. <tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
  19500. </form>
  19501. </file>
  19502. <file name="protractor.js" type="protractor">
  19503. var text = element(by.binding('url.text'));
  19504. var valid = element(by.binding('myForm.input.$valid'));
  19505. var input = element(by.model('url.text'));
  19506. it('should initialize to model', function() {
  19507. expect(text.getText()).toContain('http://google.com');
  19508. expect(valid.getText()).toContain('true');
  19509. });
  19510. it('should be invalid if empty', function() {
  19511. input.clear();
  19512. input.sendKeys('');
  19513. expect(text.getText()).toEqual('text =');
  19514. expect(valid.getText()).toContain('false');
  19515. });
  19516. it('should be invalid if not url', function() {
  19517. input.clear();
  19518. input.sendKeys('box');
  19519. expect(valid.getText()).toContain('false');
  19520. });
  19521. </file>
  19522. </example>
  19523. */
  19524. 'url': urlInputType,
  19525. /**
  19526. * @ngdoc input
  19527. * @name input[email]
  19528. *
  19529. * @description
  19530. * Text input with email validation. Sets the `email` validation error key if not a valid email
  19531. * address.
  19532. *
  19533. * <div class="alert alert-warning">
  19534. * **Note:** `input[email]` uses a regex to validate email addresses that is derived from the regex
  19535. * used in Chromium. If you need stricter validation (e.g. requiring a top-level domain), you can
  19536. * use `ng-pattern` or modify the built-in validators (see the {@link guide/forms Forms guide})
  19537. * </div>
  19538. *
  19539. * @param {string} ngModel Assignable angular expression to data-bind to.
  19540. * @param {string=} name Property name of the form under which the control is published.
  19541. * @param {string=} required Sets `required` validation error key if the value is not entered.
  19542. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  19543. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  19544. * `required` when you want to data-bind to the `required` attribute.
  19545. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  19546. * minlength.
  19547. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  19548. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of
  19549. * any length.
  19550. * @param {string=} pattern Similar to `ngPattern` except that the attribute value is the actual string
  19551. * that contains the regular expression body that will be converted to a regular expression
  19552. * as in the ngPattern directive.
  19553. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  19554. * a RegExp found by evaluating the Angular expression given in the attribute value.
  19555. * If the expression evaluates to a RegExp object, then this is used directly.
  19556. * If the expression evaluates to a string, then it will be converted to a RegExp
  19557. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  19558. * `new RegExp('^abc$')`.<br />
  19559. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  19560. * start at the index of the last search's match, thus not taking the whole input value into
  19561. * account.
  19562. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19563. * interaction with the input element.
  19564. *
  19565. * @example
  19566. <example name="email-input-directive" module="emailExample">
  19567. <file name="index.html">
  19568. <script>
  19569. angular.module('emailExample', [])
  19570. .controller('ExampleController', ['$scope', function($scope) {
  19571. $scope.email = {
  19572. text: 'me@example.com'
  19573. };
  19574. }]);
  19575. </script>
  19576. <form name="myForm" ng-controller="ExampleController">
  19577. <label>Email:
  19578. <input type="email" name="input" ng-model="email.text" required>
  19579. </label>
  19580. <div role="alert">
  19581. <span class="error" ng-show="myForm.input.$error.required">
  19582. Required!</span>
  19583. <span class="error" ng-show="myForm.input.$error.email">
  19584. Not valid email!</span>
  19585. </div>
  19586. <tt>text = {{email.text}}</tt><br/>
  19587. <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
  19588. <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
  19589. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  19590. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  19591. <tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
  19592. </form>
  19593. </file>
  19594. <file name="protractor.js" type="protractor">
  19595. var text = element(by.binding('email.text'));
  19596. var valid = element(by.binding('myForm.input.$valid'));
  19597. var input = element(by.model('email.text'));
  19598. it('should initialize to model', function() {
  19599. expect(text.getText()).toContain('me@example.com');
  19600. expect(valid.getText()).toContain('true');
  19601. });
  19602. it('should be invalid if empty', function() {
  19603. input.clear();
  19604. input.sendKeys('');
  19605. expect(text.getText()).toEqual('text =');
  19606. expect(valid.getText()).toContain('false');
  19607. });
  19608. it('should be invalid if not email', function() {
  19609. input.clear();
  19610. input.sendKeys('xxx');
  19611. expect(valid.getText()).toContain('false');
  19612. });
  19613. </file>
  19614. </example>
  19615. */
  19616. 'email': emailInputType,
  19617. /**
  19618. * @ngdoc input
  19619. * @name input[radio]
  19620. *
  19621. * @description
  19622. * HTML radio button.
  19623. *
  19624. * @param {string} ngModel Assignable angular expression to data-bind to.
  19625. * @param {string} value The value to which the `ngModel` expression should be set when selected.
  19626. * Note that `value` only supports `string` values, i.e. the scope model needs to be a string,
  19627. * too. Use `ngValue` if you need complex models (`number`, `object`, ...).
  19628. * @param {string=} name Property name of the form under which the control is published.
  19629. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19630. * interaction with the input element.
  19631. * @param {string} ngValue Angular expression to which `ngModel` will be be set when the radio
  19632. * is selected. Should be used instead of the `value` attribute if you need
  19633. * a non-string `ngModel` (`boolean`, `array`, ...).
  19634. *
  19635. * @example
  19636. <example name="radio-input-directive" module="radioExample">
  19637. <file name="index.html">
  19638. <script>
  19639. angular.module('radioExample', [])
  19640. .controller('ExampleController', ['$scope', function($scope) {
  19641. $scope.color = {
  19642. name: 'blue'
  19643. };
  19644. $scope.specialValue = {
  19645. "id": "12345",
  19646. "value": "green"
  19647. };
  19648. }]);
  19649. </script>
  19650. <form name="myForm" ng-controller="ExampleController">
  19651. <label>
  19652. <input type="radio" ng-model="color.name" value="red">
  19653. Red
  19654. </label><br/>
  19655. <label>
  19656. <input type="radio" ng-model="color.name" ng-value="specialValue">
  19657. Green
  19658. </label><br/>
  19659. <label>
  19660. <input type="radio" ng-model="color.name" value="blue">
  19661. Blue
  19662. </label><br/>
  19663. <tt>color = {{color.name | json}}</tt><br/>
  19664. </form>
  19665. Note that `ng-value="specialValue"` sets radio item's value to be the value of `$scope.specialValue`.
  19666. </file>
  19667. <file name="protractor.js" type="protractor">
  19668. it('should change state', function() {
  19669. var color = element(by.binding('color.name'));
  19670. expect(color.getText()).toContain('blue');
  19671. element.all(by.model('color.name')).get(0).click();
  19672. expect(color.getText()).toContain('red');
  19673. });
  19674. </file>
  19675. </example>
  19676. */
  19677. 'radio': radioInputType,
  19678. /**
  19679. * @ngdoc input
  19680. * @name input[checkbox]
  19681. *
  19682. * @description
  19683. * HTML checkbox.
  19684. *
  19685. * @param {string} ngModel Assignable angular expression to data-bind to.
  19686. * @param {string=} name Property name of the form under which the control is published.
  19687. * @param {expression=} ngTrueValue The value to which the expression should be set when selected.
  19688. * @param {expression=} ngFalseValue The value to which the expression should be set when not selected.
  19689. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  19690. * interaction with the input element.
  19691. *
  19692. * @example
  19693. <example name="checkbox-input-directive" module="checkboxExample">
  19694. <file name="index.html">
  19695. <script>
  19696. angular.module('checkboxExample', [])
  19697. .controller('ExampleController', ['$scope', function($scope) {
  19698. $scope.checkboxModel = {
  19699. value1 : true,
  19700. value2 : 'YES'
  19701. };
  19702. }]);
  19703. </script>
  19704. <form name="myForm" ng-controller="ExampleController">
  19705. <label>Value1:
  19706. <input type="checkbox" ng-model="checkboxModel.value1">
  19707. </label><br/>
  19708. <label>Value2:
  19709. <input type="checkbox" ng-model="checkboxModel.value2"
  19710. ng-true-value="'YES'" ng-false-value="'NO'">
  19711. </label><br/>
  19712. <tt>value1 = {{checkboxModel.value1}}</tt><br/>
  19713. <tt>value2 = {{checkboxModel.value2}}</tt><br/>
  19714. </form>
  19715. </file>
  19716. <file name="protractor.js" type="protractor">
  19717. it('should change state', function() {
  19718. var value1 = element(by.binding('checkboxModel.value1'));
  19719. var value2 = element(by.binding('checkboxModel.value2'));
  19720. expect(value1.getText()).toContain('true');
  19721. expect(value2.getText()).toContain('YES');
  19722. element(by.model('checkboxModel.value1')).click();
  19723. element(by.model('checkboxModel.value2')).click();
  19724. expect(value1.getText()).toContain('false');
  19725. expect(value2.getText()).toContain('NO');
  19726. });
  19727. </file>
  19728. </example>
  19729. */
  19730. 'checkbox': checkboxInputType,
  19731. 'hidden': noop,
  19732. 'button': noop,
  19733. 'submit': noop,
  19734. 'reset': noop,
  19735. 'file': noop
  19736. };
  19737. function stringBasedInputType(ctrl) {
  19738. ctrl.$formatters.push(function(value) {
  19739. return ctrl.$isEmpty(value) ? value : value.toString();
  19740. });
  19741. }
  19742. function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19743. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19744. stringBasedInputType(ctrl);
  19745. }
  19746. function baseInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19747. var type = lowercase(element[0].type);
  19748. // In composition mode, users are still inputing intermediate text buffer,
  19749. // hold the listener until composition is done.
  19750. // More about composition events: https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent
  19751. if (!$sniffer.android) {
  19752. var composing = false;
  19753. element.on('compositionstart', function(data) {
  19754. composing = true;
  19755. });
  19756. element.on('compositionend', function() {
  19757. composing = false;
  19758. listener();
  19759. });
  19760. }
  19761. var listener = function(ev) {
  19762. if (timeout) {
  19763. $browser.defer.cancel(timeout);
  19764. timeout = null;
  19765. }
  19766. if (composing) return;
  19767. var value = element.val(),
  19768. event = ev && ev.type;
  19769. // By default we will trim the value
  19770. // If the attribute ng-trim exists we will avoid trimming
  19771. // If input type is 'password', the value is never trimmed
  19772. if (type !== 'password' && (!attr.ngTrim || attr.ngTrim !== 'false')) {
  19773. value = trim(value);
  19774. }
  19775. // If a control is suffering from bad input (due to native validators), browsers discard its
  19776. // value, so it may be necessary to revalidate (by calling $setViewValue again) even if the
  19777. // control's value is the same empty value twice in a row.
  19778. if (ctrl.$viewValue !== value || (value === '' && ctrl.$$hasNativeValidators)) {
  19779. ctrl.$setViewValue(value, event);
  19780. }
  19781. };
  19782. // if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
  19783. // input event on backspace, delete or cut
  19784. if ($sniffer.hasEvent('input')) {
  19785. element.on('input', listener);
  19786. } else {
  19787. var timeout;
  19788. var deferListener = function(ev, input, origValue) {
  19789. if (!timeout) {
  19790. timeout = $browser.defer(function() {
  19791. timeout = null;
  19792. if (!input || input.value !== origValue) {
  19793. listener(ev);
  19794. }
  19795. });
  19796. }
  19797. };
  19798. element.on('keydown', function(event) {
  19799. var key = event.keyCode;
  19800. // ignore
  19801. // command modifiers arrows
  19802. if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
  19803. deferListener(event, this, this.value);
  19804. });
  19805. // if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
  19806. if ($sniffer.hasEvent('paste')) {
  19807. element.on('paste cut', deferListener);
  19808. }
  19809. }
  19810. // if user paste into input using mouse on older browser
  19811. // or form autocomplete on newer browser, we need "change" event to catch it
  19812. element.on('change', listener);
  19813. ctrl.$render = function() {
  19814. // Workaround for Firefox validation #12102.
  19815. var value = ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue;
  19816. if (element.val() !== value) {
  19817. element.val(value);
  19818. }
  19819. };
  19820. }
  19821. function weekParser(isoWeek, existingDate) {
  19822. if (isDate(isoWeek)) {
  19823. return isoWeek;
  19824. }
  19825. if (isString(isoWeek)) {
  19826. WEEK_REGEXP.lastIndex = 0;
  19827. var parts = WEEK_REGEXP.exec(isoWeek);
  19828. if (parts) {
  19829. var year = +parts[1],
  19830. week = +parts[2],
  19831. hours = 0,
  19832. minutes = 0,
  19833. seconds = 0,
  19834. milliseconds = 0,
  19835. firstThurs = getFirstThursdayOfYear(year),
  19836. addDays = (week - 1) * 7;
  19837. if (existingDate) {
  19838. hours = existingDate.getHours();
  19839. minutes = existingDate.getMinutes();
  19840. seconds = existingDate.getSeconds();
  19841. milliseconds = existingDate.getMilliseconds();
  19842. }
  19843. return new Date(year, 0, firstThurs.getDate() + addDays, hours, minutes, seconds, milliseconds);
  19844. }
  19845. }
  19846. return NaN;
  19847. }
  19848. function createDateParser(regexp, mapping) {
  19849. return function(iso, date) {
  19850. var parts, map;
  19851. if (isDate(iso)) {
  19852. return iso;
  19853. }
  19854. if (isString(iso)) {
  19855. // When a date is JSON'ified to wraps itself inside of an extra
  19856. // set of double quotes. This makes the date parsing code unable
  19857. // to match the date string and parse it as a date.
  19858. if (iso.charAt(0) == '"' && iso.charAt(iso.length - 1) == '"') {
  19859. iso = iso.substring(1, iso.length - 1);
  19860. }
  19861. if (ISO_DATE_REGEXP.test(iso)) {
  19862. return new Date(iso);
  19863. }
  19864. regexp.lastIndex = 0;
  19865. parts = regexp.exec(iso);
  19866. if (parts) {
  19867. parts.shift();
  19868. if (date) {
  19869. map = {
  19870. yyyy: date.getFullYear(),
  19871. MM: date.getMonth() + 1,
  19872. dd: date.getDate(),
  19873. HH: date.getHours(),
  19874. mm: date.getMinutes(),
  19875. ss: date.getSeconds(),
  19876. sss: date.getMilliseconds() / 1000
  19877. };
  19878. } else {
  19879. map = { yyyy: 1970, MM: 1, dd: 1, HH: 0, mm: 0, ss: 0, sss: 0 };
  19880. }
  19881. forEach(parts, function(part, index) {
  19882. if (index < mapping.length) {
  19883. map[mapping[index]] = +part;
  19884. }
  19885. });
  19886. return new Date(map.yyyy, map.MM - 1, map.dd, map.HH, map.mm, map.ss || 0, map.sss * 1000 || 0);
  19887. }
  19888. }
  19889. return NaN;
  19890. };
  19891. }
  19892. function createDateInputType(type, regexp, parseDate, format) {
  19893. return function dynamicDateInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter) {
  19894. badInputChecker(scope, element, attr, ctrl);
  19895. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19896. var timezone = ctrl && ctrl.$options && ctrl.$options.timezone;
  19897. var previousDate;
  19898. ctrl.$$parserName = type;
  19899. ctrl.$parsers.push(function(value) {
  19900. if (ctrl.$isEmpty(value)) return null;
  19901. if (regexp.test(value)) {
  19902. // Note: We cannot read ctrl.$modelValue, as there might be a different
  19903. // parser/formatter in the processing chain so that the model
  19904. // contains some different data format!
  19905. var parsedDate = parseDate(value, previousDate);
  19906. if (timezone) {
  19907. parsedDate = convertTimezoneToLocal(parsedDate, timezone);
  19908. }
  19909. return parsedDate;
  19910. }
  19911. return undefined;
  19912. });
  19913. ctrl.$formatters.push(function(value) {
  19914. if (value && !isDate(value)) {
  19915. throw ngModelMinErr('datefmt', 'Expected `{0}` to be a date', value);
  19916. }
  19917. if (isValidDate(value)) {
  19918. previousDate = value;
  19919. if (previousDate && timezone) {
  19920. previousDate = convertTimezoneToLocal(previousDate, timezone, true);
  19921. }
  19922. return $filter('date')(value, format, timezone);
  19923. } else {
  19924. previousDate = null;
  19925. return '';
  19926. }
  19927. });
  19928. if (isDefined(attr.min) || attr.ngMin) {
  19929. var minVal;
  19930. ctrl.$validators.min = function(value) {
  19931. return !isValidDate(value) || isUndefined(minVal) || parseDate(value) >= minVal;
  19932. };
  19933. attr.$observe('min', function(val) {
  19934. minVal = parseObservedDateValue(val);
  19935. ctrl.$validate();
  19936. });
  19937. }
  19938. if (isDefined(attr.max) || attr.ngMax) {
  19939. var maxVal;
  19940. ctrl.$validators.max = function(value) {
  19941. return !isValidDate(value) || isUndefined(maxVal) || parseDate(value) <= maxVal;
  19942. };
  19943. attr.$observe('max', function(val) {
  19944. maxVal = parseObservedDateValue(val);
  19945. ctrl.$validate();
  19946. });
  19947. }
  19948. function isValidDate(value) {
  19949. // Invalid Date: getTime() returns NaN
  19950. return value && !(value.getTime && value.getTime() !== value.getTime());
  19951. }
  19952. function parseObservedDateValue(val) {
  19953. return isDefined(val) && !isDate(val) ? parseDate(val) || undefined : val;
  19954. }
  19955. };
  19956. }
  19957. function badInputChecker(scope, element, attr, ctrl) {
  19958. var node = element[0];
  19959. var nativeValidation = ctrl.$$hasNativeValidators = isObject(node.validity);
  19960. if (nativeValidation) {
  19961. ctrl.$parsers.push(function(value) {
  19962. var validity = element.prop(VALIDITY_STATE_PROPERTY) || {};
  19963. // Detect bug in FF35 for input[email] (https://bugzilla.mozilla.org/show_bug.cgi?id=1064430):
  19964. // - also sets validity.badInput (should only be validity.typeMismatch).
  19965. // - see http://www.whatwg.org/specs/web-apps/current-work/multipage/forms.html#e-mail-state-(type=email)
  19966. // - can ignore this case as we can still read out the erroneous email...
  19967. return validity.badInput && !validity.typeMismatch ? undefined : value;
  19968. });
  19969. }
  19970. }
  19971. function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  19972. badInputChecker(scope, element, attr, ctrl);
  19973. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  19974. ctrl.$$parserName = 'number';
  19975. ctrl.$parsers.push(function(value) {
  19976. if (ctrl.$isEmpty(value)) return null;
  19977. if (NUMBER_REGEXP.test(value)) return parseFloat(value);
  19978. return undefined;
  19979. });
  19980. ctrl.$formatters.push(function(value) {
  19981. if (!ctrl.$isEmpty(value)) {
  19982. if (!isNumber(value)) {
  19983. throw ngModelMinErr('numfmt', 'Expected `{0}` to be a number', value);
  19984. }
  19985. value = value.toString();
  19986. }
  19987. return value;
  19988. });
  19989. if (isDefined(attr.min) || attr.ngMin) {
  19990. var minVal;
  19991. ctrl.$validators.min = function(value) {
  19992. return ctrl.$isEmpty(value) || isUndefined(minVal) || value >= minVal;
  19993. };
  19994. attr.$observe('min', function(val) {
  19995. if (isDefined(val) && !isNumber(val)) {
  19996. val = parseFloat(val, 10);
  19997. }
  19998. minVal = isNumber(val) && !isNaN(val) ? val : undefined;
  19999. // TODO(matsko): implement validateLater to reduce number of validations
  20000. ctrl.$validate();
  20001. });
  20002. }
  20003. if (isDefined(attr.max) || attr.ngMax) {
  20004. var maxVal;
  20005. ctrl.$validators.max = function(value) {
  20006. return ctrl.$isEmpty(value) || isUndefined(maxVal) || value <= maxVal;
  20007. };
  20008. attr.$observe('max', function(val) {
  20009. if (isDefined(val) && !isNumber(val)) {
  20010. val = parseFloat(val, 10);
  20011. }
  20012. maxVal = isNumber(val) && !isNaN(val) ? val : undefined;
  20013. // TODO(matsko): implement validateLater to reduce number of validations
  20014. ctrl.$validate();
  20015. });
  20016. }
  20017. }
  20018. function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20019. // Note: no badInputChecker here by purpose as `url` is only a validation
  20020. // in browsers, i.e. we can always read out input.value even if it is not valid!
  20021. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20022. stringBasedInputType(ctrl);
  20023. ctrl.$$parserName = 'url';
  20024. ctrl.$validators.url = function(modelValue, viewValue) {
  20025. var value = modelValue || viewValue;
  20026. return ctrl.$isEmpty(value) || URL_REGEXP.test(value);
  20027. };
  20028. }
  20029. function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
  20030. // Note: no badInputChecker here by purpose as `url` is only a validation
  20031. // in browsers, i.e. we can always read out input.value even if it is not valid!
  20032. baseInputType(scope, element, attr, ctrl, $sniffer, $browser);
  20033. stringBasedInputType(ctrl);
  20034. ctrl.$$parserName = 'email';
  20035. ctrl.$validators.email = function(modelValue, viewValue) {
  20036. var value = modelValue || viewValue;
  20037. return ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value);
  20038. };
  20039. }
  20040. function radioInputType(scope, element, attr, ctrl) {
  20041. // make the name unique, if not defined
  20042. if (isUndefined(attr.name)) {
  20043. element.attr('name', nextUid());
  20044. }
  20045. var listener = function(ev) {
  20046. if (element[0].checked) {
  20047. ctrl.$setViewValue(attr.value, ev && ev.type);
  20048. }
  20049. };
  20050. element.on('click', listener);
  20051. ctrl.$render = function() {
  20052. var value = attr.value;
  20053. element[0].checked = (value == ctrl.$viewValue);
  20054. };
  20055. attr.$observe('value', ctrl.$render);
  20056. }
  20057. function parseConstantExpr($parse, context, name, expression, fallback) {
  20058. var parseFn;
  20059. if (isDefined(expression)) {
  20060. parseFn = $parse(expression);
  20061. if (!parseFn.constant) {
  20062. throw ngModelMinErr('constexpr', 'Expected constant expression for `{0}`, but saw ' +
  20063. '`{1}`.', name, expression);
  20064. }
  20065. return parseFn(context);
  20066. }
  20067. return fallback;
  20068. }
  20069. function checkboxInputType(scope, element, attr, ctrl, $sniffer, $browser, $filter, $parse) {
  20070. var trueValue = parseConstantExpr($parse, scope, 'ngTrueValue', attr.ngTrueValue, true);
  20071. var falseValue = parseConstantExpr($parse, scope, 'ngFalseValue', attr.ngFalseValue, false);
  20072. var listener = function(ev) {
  20073. ctrl.$setViewValue(element[0].checked, ev && ev.type);
  20074. };
  20075. element.on('click', listener);
  20076. ctrl.$render = function() {
  20077. element[0].checked = ctrl.$viewValue;
  20078. };
  20079. // Override the standard `$isEmpty` because the $viewValue of an empty checkbox is always set to `false`
  20080. // This is because of the parser below, which compares the `$modelValue` with `trueValue` to convert
  20081. // it to a boolean.
  20082. ctrl.$isEmpty = function(value) {
  20083. return value === false;
  20084. };
  20085. ctrl.$formatters.push(function(value) {
  20086. return equals(value, trueValue);
  20087. });
  20088. ctrl.$parsers.push(function(value) {
  20089. return value ? trueValue : falseValue;
  20090. });
  20091. }
  20092. /**
  20093. * @ngdoc directive
  20094. * @name textarea
  20095. * @restrict E
  20096. *
  20097. * @description
  20098. * HTML textarea element control with angular data-binding. The data-binding and validation
  20099. * properties of this element are exactly the same as those of the
  20100. * {@link ng.directive:input input element}.
  20101. *
  20102. * @param {string} ngModel Assignable angular expression to data-bind to.
  20103. * @param {string=} name Property name of the form under which the control is published.
  20104. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20105. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  20106. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  20107. * `required` when you want to data-bind to the `required` attribute.
  20108. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20109. * minlength.
  20110. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20111. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  20112. * length.
  20113. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  20114. * a RegExp found by evaluating the Angular expression given in the attribute value.
  20115. * If the expression evaluates to a RegExp object, then this is used directly.
  20116. * If the expression evaluates to a string, then it will be converted to a RegExp
  20117. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20118. * `new RegExp('^abc$')`.<br />
  20119. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20120. * start at the index of the last search's match, thus not taking the whole input value into
  20121. * account.
  20122. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20123. * interaction with the input element.
  20124. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20125. */
  20126. /**
  20127. * @ngdoc directive
  20128. * @name input
  20129. * @restrict E
  20130. *
  20131. * @description
  20132. * HTML input element control. When used together with {@link ngModel `ngModel`}, it provides data-binding,
  20133. * input state control, and validation.
  20134. * Input control follows HTML5 input types and polyfills the HTML5 validation behavior for older browsers.
  20135. *
  20136. * <div class="alert alert-warning">
  20137. * **Note:** Not every feature offered is available for all input types.
  20138. * Specifically, data binding and event handling via `ng-model` is unsupported for `input[file]`.
  20139. * </div>
  20140. *
  20141. * @param {string} ngModel Assignable angular expression to data-bind to.
  20142. * @param {string=} name Property name of the form under which the control is published.
  20143. * @param {string=} required Sets `required` validation error key if the value is not entered.
  20144. * @param {boolean=} ngRequired Sets `required` attribute if set to true
  20145. * @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
  20146. * minlength.
  20147. * @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
  20148. * maxlength. Setting the attribute to a negative or non-numeric value, allows view values of any
  20149. * length.
  20150. * @param {string=} ngPattern Sets `pattern` validation error key if the ngModel value does not match
  20151. * a RegExp found by evaluating the Angular expression given in the attribute value.
  20152. * If the expression evaluates to a RegExp object, then this is used directly.
  20153. * If the expression evaluates to a string, then it will be converted to a RegExp
  20154. * after wrapping it in `^` and `$` characters. For instance, `"abc"` will be converted to
  20155. * `new RegExp('^abc$')`.<br />
  20156. * **Note:** Avoid using the `g` flag on the RegExp, as it will cause each successive search to
  20157. * start at the index of the last search's match, thus not taking the whole input value into
  20158. * account.
  20159. * @param {string=} ngChange Angular expression to be executed when input changes due to user
  20160. * interaction with the input element.
  20161. * @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
  20162. * This parameter is ignored for input[type=password] controls, which will never trim the
  20163. * input.
  20164. *
  20165. * @example
  20166. <example name="input-directive" module="inputExample">
  20167. <file name="index.html">
  20168. <script>
  20169. angular.module('inputExample', [])
  20170. .controller('ExampleController', ['$scope', function($scope) {
  20171. $scope.user = {name: 'guest', last: 'visitor'};
  20172. }]);
  20173. </script>
  20174. <div ng-controller="ExampleController">
  20175. <form name="myForm">
  20176. <label>
  20177. User name:
  20178. <input type="text" name="userName" ng-model="user.name" required>
  20179. </label>
  20180. <div role="alert">
  20181. <span class="error" ng-show="myForm.userName.$error.required">
  20182. Required!</span>
  20183. </div>
  20184. <label>
  20185. Last name:
  20186. <input type="text" name="lastName" ng-model="user.last"
  20187. ng-minlength="3" ng-maxlength="10">
  20188. </label>
  20189. <div role="alert">
  20190. <span class="error" ng-show="myForm.lastName.$error.minlength">
  20191. Too short!</span>
  20192. <span class="error" ng-show="myForm.lastName.$error.maxlength">
  20193. Too long!</span>
  20194. </div>
  20195. </form>
  20196. <hr>
  20197. <tt>user = {{user}}</tt><br/>
  20198. <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br/>
  20199. <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br/>
  20200. <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br/>
  20201. <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br/>
  20202. <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  20203. <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  20204. <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br/>
  20205. <tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br/>
  20206. </div>
  20207. </file>
  20208. <file name="protractor.js" type="protractor">
  20209. var user = element(by.exactBinding('user'));
  20210. var userNameValid = element(by.binding('myForm.userName.$valid'));
  20211. var lastNameValid = element(by.binding('myForm.lastName.$valid'));
  20212. var lastNameError = element(by.binding('myForm.lastName.$error'));
  20213. var formValid = element(by.binding('myForm.$valid'));
  20214. var userNameInput = element(by.model('user.name'));
  20215. var userLastInput = element(by.model('user.last'));
  20216. it('should initialize to model', function() {
  20217. expect(user.getText()).toContain('{"name":"guest","last":"visitor"}');
  20218. expect(userNameValid.getText()).toContain('true');
  20219. expect(formValid.getText()).toContain('true');
  20220. });
  20221. it('should be invalid if empty when required', function() {
  20222. userNameInput.clear();
  20223. userNameInput.sendKeys('');
  20224. expect(user.getText()).toContain('{"last":"visitor"}');
  20225. expect(userNameValid.getText()).toContain('false');
  20226. expect(formValid.getText()).toContain('false');
  20227. });
  20228. it('should be valid if empty when min length is set', function() {
  20229. userLastInput.clear();
  20230. userLastInput.sendKeys('');
  20231. expect(user.getText()).toContain('{"name":"guest","last":""}');
  20232. expect(lastNameValid.getText()).toContain('true');
  20233. expect(formValid.getText()).toContain('true');
  20234. });
  20235. it('should be invalid if less than required min length', function() {
  20236. userLastInput.clear();
  20237. userLastInput.sendKeys('xx');
  20238. expect(user.getText()).toContain('{"name":"guest"}');
  20239. expect(lastNameValid.getText()).toContain('false');
  20240. expect(lastNameError.getText()).toContain('minlength');
  20241. expect(formValid.getText()).toContain('false');
  20242. });
  20243. it('should be invalid if longer than max length', function() {
  20244. userLastInput.clear();
  20245. userLastInput.sendKeys('some ridiculously long name');
  20246. expect(user.getText()).toContain('{"name":"guest"}');
  20247. expect(lastNameValid.getText()).toContain('false');
  20248. expect(lastNameError.getText()).toContain('maxlength');
  20249. expect(formValid.getText()).toContain('false');
  20250. });
  20251. </file>
  20252. </example>
  20253. */
  20254. var inputDirective = ['$browser', '$sniffer', '$filter', '$parse',
  20255. function($browser, $sniffer, $filter, $parse) {
  20256. return {
  20257. restrict: 'E',
  20258. require: ['?ngModel'],
  20259. link: {
  20260. pre: function(scope, element, attr, ctrls) {
  20261. if (ctrls[0]) {
  20262. (inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrls[0], $sniffer,
  20263. $browser, $filter, $parse);
  20264. }
  20265. }
  20266. }
  20267. };
  20268. }];
  20269. var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
  20270. /**
  20271. * @ngdoc directive
  20272. * @name ngValue
  20273. *
  20274. * @description
  20275. * Binds the given expression to the value of `<option>` or {@link input[radio] `input[radio]`},
  20276. * so that when the element is selected, the {@link ngModel `ngModel`} of that element is set to
  20277. * the bound value.
  20278. *
  20279. * `ngValue` is useful when dynamically generating lists of radio buttons using
  20280. * {@link ngRepeat `ngRepeat`}, as shown below.
  20281. *
  20282. * Likewise, `ngValue` can be used to generate `<option>` elements for
  20283. * the {@link select `select`} element. In that case however, only strings are supported
  20284. * for the `value `attribute, so the resulting `ngModel` will always be a string.
  20285. * Support for `select` models with non-string values is available via `ngOptions`.
  20286. *
  20287. * @element input
  20288. * @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
  20289. * of the `input` element
  20290. *
  20291. * @example
  20292. <example name="ngValue-directive" module="valueExample">
  20293. <file name="index.html">
  20294. <script>
  20295. angular.module('valueExample', [])
  20296. .controller('ExampleController', ['$scope', function($scope) {
  20297. $scope.names = ['pizza', 'unicorns', 'robots'];
  20298. $scope.my = { favorite: 'unicorns' };
  20299. }]);
  20300. </script>
  20301. <form ng-controller="ExampleController">
  20302. <h2>Which is your favorite?</h2>
  20303. <label ng-repeat="name in names" for="{{name}}">
  20304. {{name}}
  20305. <input type="radio"
  20306. ng-model="my.favorite"
  20307. ng-value="name"
  20308. id="{{name}}"
  20309. name="favorite">
  20310. </label>
  20311. <div>You chose {{my.favorite}}</div>
  20312. </form>
  20313. </file>
  20314. <file name="protractor.js" type="protractor">
  20315. var favorite = element(by.binding('my.favorite'));
  20316. it('should initialize to model', function() {
  20317. expect(favorite.getText()).toContain('unicorns');
  20318. });
  20319. it('should bind the values to the inputs', function() {
  20320. element.all(by.model('my.favorite')).get(0).click();
  20321. expect(favorite.getText()).toContain('pizza');
  20322. });
  20323. </file>
  20324. </example>
  20325. */
  20326. var ngValueDirective = function() {
  20327. return {
  20328. restrict: 'A',
  20329. priority: 100,
  20330. compile: function(tpl, tplAttr) {
  20331. if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
  20332. return function ngValueConstantLink(scope, elm, attr) {
  20333. attr.$set('value', scope.$eval(attr.ngValue));
  20334. };
  20335. } else {
  20336. return function ngValueLink(scope, elm, attr) {
  20337. scope.$watch(attr.ngValue, function valueWatchAction(value) {
  20338. attr.$set('value', value);
  20339. });
  20340. };
  20341. }
  20342. }
  20343. };
  20344. };
  20345. /**
  20346. * @ngdoc directive
  20347. * @name ngBind
  20348. * @restrict AC
  20349. *
  20350. * @description
  20351. * The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
  20352. * with the value of a given expression, and to update the text content when the value of that
  20353. * expression changes.
  20354. *
  20355. * Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
  20356. * `{{ expression }}` which is similar but less verbose.
  20357. *
  20358. * It is preferable to use `ngBind` instead of `{{ expression }}` if a template is momentarily
  20359. * displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
  20360. * element attribute, it makes the bindings invisible to the user while the page is loading.
  20361. *
  20362. * An alternative solution to this problem would be using the
  20363. * {@link ng.directive:ngCloak ngCloak} directive.
  20364. *
  20365. *
  20366. * @element ANY
  20367. * @param {expression} ngBind {@link guide/expression Expression} to evaluate.
  20368. *
  20369. * @example
  20370. * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
  20371. <example module="bindExample">
  20372. <file name="index.html">
  20373. <script>
  20374. angular.module('bindExample', [])
  20375. .controller('ExampleController', ['$scope', function($scope) {
  20376. $scope.name = 'Whirled';
  20377. }]);
  20378. </script>
  20379. <div ng-controller="ExampleController">
  20380. <label>Enter name: <input type="text" ng-model="name"></label><br>
  20381. Hello <span ng-bind="name"></span>!
  20382. </div>
  20383. </file>
  20384. <file name="protractor.js" type="protractor">
  20385. it('should check ng-bind', function() {
  20386. var nameInput = element(by.model('name'));
  20387. expect(element(by.binding('name')).getText()).toBe('Whirled');
  20388. nameInput.clear();
  20389. nameInput.sendKeys('world');
  20390. expect(element(by.binding('name')).getText()).toBe('world');
  20391. });
  20392. </file>
  20393. </example>
  20394. */
  20395. var ngBindDirective = ['$compile', function($compile) {
  20396. return {
  20397. restrict: 'AC',
  20398. compile: function ngBindCompile(templateElement) {
  20399. $compile.$$addBindingClass(templateElement);
  20400. return function ngBindLink(scope, element, attr) {
  20401. $compile.$$addBindingInfo(element, attr.ngBind);
  20402. element = element[0];
  20403. scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
  20404. element.textContent = isUndefined(value) ? '' : value;
  20405. });
  20406. };
  20407. }
  20408. };
  20409. }];
  20410. /**
  20411. * @ngdoc directive
  20412. * @name ngBindTemplate
  20413. *
  20414. * @description
  20415. * The `ngBindTemplate` directive specifies that the element
  20416. * text content should be replaced with the interpolation of the template
  20417. * in the `ngBindTemplate` attribute.
  20418. * Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
  20419. * expressions. This directive is needed since some HTML elements
  20420. * (such as TITLE and OPTION) cannot contain SPAN elements.
  20421. *
  20422. * @element ANY
  20423. * @param {string} ngBindTemplate template of form
  20424. * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
  20425. *
  20426. * @example
  20427. * Try it here: enter text in text box and watch the greeting change.
  20428. <example module="bindExample">
  20429. <file name="index.html">
  20430. <script>
  20431. angular.module('bindExample', [])
  20432. .controller('ExampleController', ['$scope', function($scope) {
  20433. $scope.salutation = 'Hello';
  20434. $scope.name = 'World';
  20435. }]);
  20436. </script>
  20437. <div ng-controller="ExampleController">
  20438. <label>Salutation: <input type="text" ng-model="salutation"></label><br>
  20439. <label>Name: <input type="text" ng-model="name"></label><br>
  20440. <pre ng-bind-template="{{salutation}} {{name}}!"></pre>
  20441. </div>
  20442. </file>
  20443. <file name="protractor.js" type="protractor">
  20444. it('should check ng-bind', function() {
  20445. var salutationElem = element(by.binding('salutation'));
  20446. var salutationInput = element(by.model('salutation'));
  20447. var nameInput = element(by.model('name'));
  20448. expect(salutationElem.getText()).toBe('Hello World!');
  20449. salutationInput.clear();
  20450. salutationInput.sendKeys('Greetings');
  20451. nameInput.clear();
  20452. nameInput.sendKeys('user');
  20453. expect(salutationElem.getText()).toBe('Greetings user!');
  20454. });
  20455. </file>
  20456. </example>
  20457. */
  20458. var ngBindTemplateDirective = ['$interpolate', '$compile', function($interpolate, $compile) {
  20459. return {
  20460. compile: function ngBindTemplateCompile(templateElement) {
  20461. $compile.$$addBindingClass(templateElement);
  20462. return function ngBindTemplateLink(scope, element, attr) {
  20463. var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
  20464. $compile.$$addBindingInfo(element, interpolateFn.expressions);
  20465. element = element[0];
  20466. attr.$observe('ngBindTemplate', function(value) {
  20467. element.textContent = isUndefined(value) ? '' : value;
  20468. });
  20469. };
  20470. }
  20471. };
  20472. }];
  20473. /**
  20474. * @ngdoc directive
  20475. * @name ngBindHtml
  20476. *
  20477. * @description
  20478. * Evaluates the expression and inserts the resulting HTML into the element in a secure way. By default,
  20479. * the resulting HTML content will be sanitized using the {@link ngSanitize.$sanitize $sanitize} service.
  20480. * To utilize this functionality, ensure that `$sanitize` is available, for example, by including {@link
  20481. * ngSanitize} in your module's dependencies (not in core Angular). In order to use {@link ngSanitize}
  20482. * in your module's dependencies, you need to include "angular-sanitize.js" in your application.
  20483. *
  20484. * You may also bypass sanitization for values you know are safe. To do so, bind to
  20485. * an explicitly trusted value via {@link ng.$sce#trustAsHtml $sce.trustAsHtml}. See the example
  20486. * under {@link ng.$sce#show-me-an-example-using-sce- Strict Contextual Escaping (SCE)}.
  20487. *
  20488. * Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
  20489. * will have an exception (instead of an exploit.)
  20490. *
  20491. * @element ANY
  20492. * @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
  20493. *
  20494. * @example
  20495. <example module="bindHtmlExample" deps="angular-sanitize.js">
  20496. <file name="index.html">
  20497. <div ng-controller="ExampleController">
  20498. <p ng-bind-html="myHTML"></p>
  20499. </div>
  20500. </file>
  20501. <file name="script.js">
  20502. angular.module('bindHtmlExample', ['ngSanitize'])
  20503. .controller('ExampleController', ['$scope', function($scope) {
  20504. $scope.myHTML =
  20505. 'I am an <code>HTML</code>string with ' +
  20506. '<a href="#">links!</a> and other <em>stuff</em>';
  20507. }]);
  20508. </file>
  20509. <file name="protractor.js" type="protractor">
  20510. it('should check ng-bind-html', function() {
  20511. expect(element(by.binding('myHTML')).getText()).toBe(
  20512. 'I am an HTMLstring with links! and other stuff');
  20513. });
  20514. </file>
  20515. </example>
  20516. */
  20517. var ngBindHtmlDirective = ['$sce', '$parse', '$compile', function($sce, $parse, $compile) {
  20518. return {
  20519. restrict: 'A',
  20520. compile: function ngBindHtmlCompile(tElement, tAttrs) {
  20521. var ngBindHtmlGetter = $parse(tAttrs.ngBindHtml);
  20522. var ngBindHtmlWatch = $parse(tAttrs.ngBindHtml, function getStringValue(value) {
  20523. return (value || '').toString();
  20524. });
  20525. $compile.$$addBindingClass(tElement);
  20526. return function ngBindHtmlLink(scope, element, attr) {
  20527. $compile.$$addBindingInfo(element, attr.ngBindHtml);
  20528. scope.$watch(ngBindHtmlWatch, function ngBindHtmlWatchAction() {
  20529. // we re-evaluate the expr because we want a TrustedValueHolderType
  20530. // for $sce, not a string
  20531. element.html($sce.getTrustedHtml(ngBindHtmlGetter(scope)) || '');
  20532. });
  20533. };
  20534. }
  20535. };
  20536. }];
  20537. /**
  20538. * @ngdoc directive
  20539. * @name ngChange
  20540. *
  20541. * @description
  20542. * Evaluate the given expression when the user changes the input.
  20543. * The expression is evaluated immediately, unlike the JavaScript onchange event
  20544. * which only triggers at the end of a change (usually, when the user leaves the
  20545. * form element or presses the return key).
  20546. *
  20547. * The `ngChange` expression is only evaluated when a change in the input value causes
  20548. * a new value to be committed to the model.
  20549. *
  20550. * It will not be evaluated:
  20551. * * if the value returned from the `$parsers` transformation pipeline has not changed
  20552. * * if the input has continued to be invalid since the model will stay `null`
  20553. * * if the model is changed programmatically and not by a change to the input value
  20554. *
  20555. *
  20556. * Note, this directive requires `ngModel` to be present.
  20557. *
  20558. * @element input
  20559. * @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
  20560. * in input value.
  20561. *
  20562. * @example
  20563. * <example name="ngChange-directive" module="changeExample">
  20564. * <file name="index.html">
  20565. * <script>
  20566. * angular.module('changeExample', [])
  20567. * .controller('ExampleController', ['$scope', function($scope) {
  20568. * $scope.counter = 0;
  20569. * $scope.change = function() {
  20570. * $scope.counter++;
  20571. * };
  20572. * }]);
  20573. * </script>
  20574. * <div ng-controller="ExampleController">
  20575. * <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
  20576. * <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
  20577. * <label for="ng-change-example2">Confirmed</label><br />
  20578. * <tt>debug = {{confirmed}}</tt><br/>
  20579. * <tt>counter = {{counter}}</tt><br/>
  20580. * </div>
  20581. * </file>
  20582. * <file name="protractor.js" type="protractor">
  20583. * var counter = element(by.binding('counter'));
  20584. * var debug = element(by.binding('confirmed'));
  20585. *
  20586. * it('should evaluate the expression if changing from view', function() {
  20587. * expect(counter.getText()).toContain('0');
  20588. *
  20589. * element(by.id('ng-change-example1')).click();
  20590. *
  20591. * expect(counter.getText()).toContain('1');
  20592. * expect(debug.getText()).toContain('true');
  20593. * });
  20594. *
  20595. * it('should not evaluate the expression if changing from model', function() {
  20596. * element(by.id('ng-change-example2')).click();
  20597. * expect(counter.getText()).toContain('0');
  20598. * expect(debug.getText()).toContain('true');
  20599. * });
  20600. * </file>
  20601. * </example>
  20602. */
  20603. var ngChangeDirective = valueFn({
  20604. restrict: 'A',
  20605. require: 'ngModel',
  20606. link: function(scope, element, attr, ctrl) {
  20607. ctrl.$viewChangeListeners.push(function() {
  20608. scope.$eval(attr.ngChange);
  20609. });
  20610. }
  20611. });
  20612. function classDirective(name, selector) {
  20613. name = 'ngClass' + name;
  20614. return ['$animate', function($animate) {
  20615. return {
  20616. restrict: 'AC',
  20617. link: function(scope, element, attr) {
  20618. var oldVal;
  20619. scope.$watch(attr[name], ngClassWatchAction, true);
  20620. attr.$observe('class', function(value) {
  20621. ngClassWatchAction(scope.$eval(attr[name]));
  20622. });
  20623. if (name !== 'ngClass') {
  20624. scope.$watch('$index', function($index, old$index) {
  20625. // jshint bitwise: false
  20626. var mod = $index & 1;
  20627. if (mod !== (old$index & 1)) {
  20628. var classes = arrayClasses(scope.$eval(attr[name]));
  20629. mod === selector ?
  20630. addClasses(classes) :
  20631. removeClasses(classes);
  20632. }
  20633. });
  20634. }
  20635. function addClasses(classes) {
  20636. var newClasses = digestClassCounts(classes, 1);
  20637. attr.$addClass(newClasses);
  20638. }
  20639. function removeClasses(classes) {
  20640. var newClasses = digestClassCounts(classes, -1);
  20641. attr.$removeClass(newClasses);
  20642. }
  20643. function digestClassCounts(classes, count) {
  20644. // Use createMap() to prevent class assumptions involving property
  20645. // names in Object.prototype
  20646. var classCounts = element.data('$classCounts') || createMap();
  20647. var classesToUpdate = [];
  20648. forEach(classes, function(className) {
  20649. if (count > 0 || classCounts[className]) {
  20650. classCounts[className] = (classCounts[className] || 0) + count;
  20651. if (classCounts[className] === +(count > 0)) {
  20652. classesToUpdate.push(className);
  20653. }
  20654. }
  20655. });
  20656. element.data('$classCounts', classCounts);
  20657. return classesToUpdate.join(' ');
  20658. }
  20659. function updateClasses(oldClasses, newClasses) {
  20660. var toAdd = arrayDifference(newClasses, oldClasses);
  20661. var toRemove = arrayDifference(oldClasses, newClasses);
  20662. toAdd = digestClassCounts(toAdd, 1);
  20663. toRemove = digestClassCounts(toRemove, -1);
  20664. if (toAdd && toAdd.length) {
  20665. $animate.addClass(element, toAdd);
  20666. }
  20667. if (toRemove && toRemove.length) {
  20668. $animate.removeClass(element, toRemove);
  20669. }
  20670. }
  20671. function ngClassWatchAction(newVal) {
  20672. if (selector === true || scope.$index % 2 === selector) {
  20673. var newClasses = arrayClasses(newVal || []);
  20674. if (!oldVal) {
  20675. addClasses(newClasses);
  20676. } else if (!equals(newVal,oldVal)) {
  20677. var oldClasses = arrayClasses(oldVal);
  20678. updateClasses(oldClasses, newClasses);
  20679. }
  20680. }
  20681. oldVal = shallowCopy(newVal);
  20682. }
  20683. }
  20684. };
  20685. function arrayDifference(tokens1, tokens2) {
  20686. var values = [];
  20687. outer:
  20688. for (var i = 0; i < tokens1.length; i++) {
  20689. var token = tokens1[i];
  20690. for (var j = 0; j < tokens2.length; j++) {
  20691. if (token == tokens2[j]) continue outer;
  20692. }
  20693. values.push(token);
  20694. }
  20695. return values;
  20696. }
  20697. function arrayClasses(classVal) {
  20698. var classes = [];
  20699. if (isArray(classVal)) {
  20700. forEach(classVal, function(v) {
  20701. classes = classes.concat(arrayClasses(v));
  20702. });
  20703. return classes;
  20704. } else if (isString(classVal)) {
  20705. return classVal.split(' ');
  20706. } else if (isObject(classVal)) {
  20707. forEach(classVal, function(v, k) {
  20708. if (v) {
  20709. classes = classes.concat(k.split(' '));
  20710. }
  20711. });
  20712. return classes;
  20713. }
  20714. return classVal;
  20715. }
  20716. }];
  20717. }
  20718. /**
  20719. * @ngdoc directive
  20720. * @name ngClass
  20721. * @restrict AC
  20722. *
  20723. * @description
  20724. * The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
  20725. * an expression that represents all classes to be added.
  20726. *
  20727. * The directive operates in three different ways, depending on which of three types the expression
  20728. * evaluates to:
  20729. *
  20730. * 1. If the expression evaluates to a string, the string should be one or more space-delimited class
  20731. * names.
  20732. *
  20733. * 2. If the expression evaluates to an object, then for each key-value pair of the
  20734. * object with a truthy value the corresponding key is used as a class name.
  20735. *
  20736. * 3. If the expression evaluates to an array, each element of the array should either be a string as in
  20737. * type 1 or an object as in type 2. This means that you can mix strings and objects together in an array
  20738. * to give you more control over what CSS classes appear. See the code below for an example of this.
  20739. *
  20740. *
  20741. * The directive won't add duplicate classes if a particular class was already set.
  20742. *
  20743. * When the expression changes, the previously added classes are removed and only then are the
  20744. * new classes added.
  20745. *
  20746. * @animations
  20747. * **add** - happens just before the class is applied to the elements
  20748. *
  20749. * **remove** - happens just before the class is removed from the element
  20750. *
  20751. * @element ANY
  20752. * @param {expression} ngClass {@link guide/expression Expression} to eval. The result
  20753. * of the evaluation can be a string representing space delimited class
  20754. * names, an array, or a map of class names to boolean values. In the case of a map, the
  20755. * names of the properties whose values are truthy will be added as css classes to the
  20756. * element.
  20757. *
  20758. * @example Example that demonstrates basic bindings via ngClass directive.
  20759. <example>
  20760. <file name="index.html">
  20761. <p ng-class="{strike: deleted, bold: important, 'has-error': error}">Map Syntax Example</p>
  20762. <label>
  20763. <input type="checkbox" ng-model="deleted">
  20764. deleted (apply "strike" class)
  20765. </label><br>
  20766. <label>
  20767. <input type="checkbox" ng-model="important">
  20768. important (apply "bold" class)
  20769. </label><br>
  20770. <label>
  20771. <input type="checkbox" ng-model="error">
  20772. error (apply "has-error" class)
  20773. </label>
  20774. <hr>
  20775. <p ng-class="style">Using String Syntax</p>
  20776. <input type="text" ng-model="style"
  20777. placeholder="Type: bold strike red" aria-label="Type: bold strike red">
  20778. <hr>
  20779. <p ng-class="[style1, style2, style3]">Using Array Syntax</p>
  20780. <input ng-model="style1"
  20781. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red"><br>
  20782. <input ng-model="style2"
  20783. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 2"><br>
  20784. <input ng-model="style3"
  20785. placeholder="Type: bold, strike or red" aria-label="Type: bold, strike or red 3"><br>
  20786. <hr>
  20787. <p ng-class="[style4, {orange: warning}]">Using Array and Map Syntax</p>
  20788. <input ng-model="style4" placeholder="Type: bold, strike" aria-label="Type: bold, strike"><br>
  20789. <label><input type="checkbox" ng-model="warning"> warning (apply "orange" class)</label>
  20790. </file>
  20791. <file name="style.css">
  20792. .strike {
  20793. text-decoration: line-through;
  20794. }
  20795. .bold {
  20796. font-weight: bold;
  20797. }
  20798. .red {
  20799. color: red;
  20800. }
  20801. .has-error {
  20802. color: red;
  20803. background-color: yellow;
  20804. }
  20805. .orange {
  20806. color: orange;
  20807. }
  20808. </file>
  20809. <file name="protractor.js" type="protractor">
  20810. var ps = element.all(by.css('p'));
  20811. it('should let you toggle the class', function() {
  20812. expect(ps.first().getAttribute('class')).not.toMatch(/bold/);
  20813. expect(ps.first().getAttribute('class')).not.toMatch(/has-error/);
  20814. element(by.model('important')).click();
  20815. expect(ps.first().getAttribute('class')).toMatch(/bold/);
  20816. element(by.model('error')).click();
  20817. expect(ps.first().getAttribute('class')).toMatch(/has-error/);
  20818. });
  20819. it('should let you toggle string example', function() {
  20820. expect(ps.get(1).getAttribute('class')).toBe('');
  20821. element(by.model('style')).clear();
  20822. element(by.model('style')).sendKeys('red');
  20823. expect(ps.get(1).getAttribute('class')).toBe('red');
  20824. });
  20825. it('array example should have 3 classes', function() {
  20826. expect(ps.get(2).getAttribute('class')).toBe('');
  20827. element(by.model('style1')).sendKeys('bold');
  20828. element(by.model('style2')).sendKeys('strike');
  20829. element(by.model('style3')).sendKeys('red');
  20830. expect(ps.get(2).getAttribute('class')).toBe('bold strike red');
  20831. });
  20832. it('array with map example should have 2 classes', function() {
  20833. expect(ps.last().getAttribute('class')).toBe('');
  20834. element(by.model('style4')).sendKeys('bold');
  20835. element(by.model('warning')).click();
  20836. expect(ps.last().getAttribute('class')).toBe('bold orange');
  20837. });
  20838. </file>
  20839. </example>
  20840. ## Animations
  20841. The example below demonstrates how to perform animations using ngClass.
  20842. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  20843. <file name="index.html">
  20844. <input id="setbtn" type="button" value="set" ng-click="myVar='my-class'">
  20845. <input id="clearbtn" type="button" value="clear" ng-click="myVar=''">
  20846. <br>
  20847. <span class="base-class" ng-class="myVar">Sample Text</span>
  20848. </file>
  20849. <file name="style.css">
  20850. .base-class {
  20851. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  20852. }
  20853. .base-class.my-class {
  20854. color: red;
  20855. font-size:3em;
  20856. }
  20857. </file>
  20858. <file name="protractor.js" type="protractor">
  20859. it('should check ng-class', function() {
  20860. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20861. toMatch(/my-class/);
  20862. element(by.id('setbtn')).click();
  20863. expect(element(by.css('.base-class')).getAttribute('class')).
  20864. toMatch(/my-class/);
  20865. element(by.id('clearbtn')).click();
  20866. expect(element(by.css('.base-class')).getAttribute('class')).not.
  20867. toMatch(/my-class/);
  20868. });
  20869. </file>
  20870. </example>
  20871. ## ngClass and pre-existing CSS3 Transitions/Animations
  20872. The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
  20873. Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
  20874. any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
  20875. to view the step by step details of {@link $animate#addClass $animate.addClass} and
  20876. {@link $animate#removeClass $animate.removeClass}.
  20877. */
  20878. var ngClassDirective = classDirective('', true);
  20879. /**
  20880. * @ngdoc directive
  20881. * @name ngClassOdd
  20882. * @restrict AC
  20883. *
  20884. * @description
  20885. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20886. * {@link ng.directive:ngClass ngClass}, except they work in
  20887. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20888. *
  20889. * This directive can be applied only within the scope of an
  20890. * {@link ng.directive:ngRepeat ngRepeat}.
  20891. *
  20892. * @element ANY
  20893. * @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
  20894. * of the evaluation can be a string representing space delimited class names or an array.
  20895. *
  20896. * @example
  20897. <example>
  20898. <file name="index.html">
  20899. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20900. <li ng-repeat="name in names">
  20901. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20902. {{name}}
  20903. </span>
  20904. </li>
  20905. </ol>
  20906. </file>
  20907. <file name="style.css">
  20908. .odd {
  20909. color: red;
  20910. }
  20911. .even {
  20912. color: blue;
  20913. }
  20914. </file>
  20915. <file name="protractor.js" type="protractor">
  20916. it('should check ng-class-odd and ng-class-even', function() {
  20917. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20918. toMatch(/odd/);
  20919. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20920. toMatch(/even/);
  20921. });
  20922. </file>
  20923. </example>
  20924. */
  20925. var ngClassOddDirective = classDirective('Odd', 0);
  20926. /**
  20927. * @ngdoc directive
  20928. * @name ngClassEven
  20929. * @restrict AC
  20930. *
  20931. * @description
  20932. * The `ngClassOdd` and `ngClassEven` directives work exactly as
  20933. * {@link ng.directive:ngClass ngClass}, except they work in
  20934. * conjunction with `ngRepeat` and take effect only on odd (even) rows.
  20935. *
  20936. * This directive can be applied only within the scope of an
  20937. * {@link ng.directive:ngRepeat ngRepeat}.
  20938. *
  20939. * @element ANY
  20940. * @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
  20941. * result of the evaluation can be a string representing space delimited class names or an array.
  20942. *
  20943. * @example
  20944. <example>
  20945. <file name="index.html">
  20946. <ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
  20947. <li ng-repeat="name in names">
  20948. <span ng-class-odd="'odd'" ng-class-even="'even'">
  20949. {{name}} &nbsp; &nbsp; &nbsp;
  20950. </span>
  20951. </li>
  20952. </ol>
  20953. </file>
  20954. <file name="style.css">
  20955. .odd {
  20956. color: red;
  20957. }
  20958. .even {
  20959. color: blue;
  20960. }
  20961. </file>
  20962. <file name="protractor.js" type="protractor">
  20963. it('should check ng-class-odd and ng-class-even', function() {
  20964. expect(element(by.repeater('name in names').row(0).column('name')).getAttribute('class')).
  20965. toMatch(/odd/);
  20966. expect(element(by.repeater('name in names').row(1).column('name')).getAttribute('class')).
  20967. toMatch(/even/);
  20968. });
  20969. </file>
  20970. </example>
  20971. */
  20972. var ngClassEvenDirective = classDirective('Even', 1);
  20973. /**
  20974. * @ngdoc directive
  20975. * @name ngCloak
  20976. * @restrict AC
  20977. *
  20978. * @description
  20979. * The `ngCloak` directive is used to prevent the Angular html template from being briefly
  20980. * displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
  20981. * directive to avoid the undesirable flicker effect caused by the html template display.
  20982. *
  20983. * The directive can be applied to the `<body>` element, but the preferred usage is to apply
  20984. * multiple `ngCloak` directives to small portions of the page to permit progressive rendering
  20985. * of the browser view.
  20986. *
  20987. * `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
  20988. * `angular.min.js`.
  20989. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  20990. *
  20991. * ```css
  20992. * [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
  20993. * display: none !important;
  20994. * }
  20995. * ```
  20996. *
  20997. * When this css rule is loaded by the browser, all html elements (including their children) that
  20998. * are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
  20999. * during the compilation of the template it deletes the `ngCloak` element attribute, making
  21000. * the compiled element visible.
  21001. *
  21002. * For the best result, the `angular.js` script must be loaded in the head section of the html
  21003. * document; alternatively, the css rule above must be included in the external stylesheet of the
  21004. * application.
  21005. *
  21006. * @element ANY
  21007. *
  21008. * @example
  21009. <example>
  21010. <file name="index.html">
  21011. <div id="template1" ng-cloak>{{ 'hello' }}</div>
  21012. <div id="template2" class="ng-cloak">{{ 'world' }}</div>
  21013. </file>
  21014. <file name="protractor.js" type="protractor">
  21015. it('should remove the template directive and css class', function() {
  21016. expect($('#template1').getAttribute('ng-cloak')).
  21017. toBeNull();
  21018. expect($('#template2').getAttribute('ng-cloak')).
  21019. toBeNull();
  21020. });
  21021. </file>
  21022. </example>
  21023. *
  21024. */
  21025. var ngCloakDirective = ngDirective({
  21026. compile: function(element, attr) {
  21027. attr.$set('ngCloak', undefined);
  21028. element.removeClass('ng-cloak');
  21029. }
  21030. });
  21031. /**
  21032. * @ngdoc directive
  21033. * @name ngController
  21034. *
  21035. * @description
  21036. * The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
  21037. * supports the principles behind the Model-View-Controller design pattern.
  21038. *
  21039. * MVC components in angular:
  21040. *
  21041. * * Model — Models are the properties of a scope; scopes are attached to the DOM where scope properties
  21042. * are accessed through bindings.
  21043. * * View — The template (HTML with data bindings) that is rendered into the View.
  21044. * * Controller — The `ngController` directive specifies a Controller class; the class contains business
  21045. * logic behind the application to decorate the scope with functions and values
  21046. *
  21047. * Note that you can also attach controllers to the DOM by declaring it in a route definition
  21048. * via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
  21049. * again using `ng-controller` in the template itself. This will cause the controller to be attached
  21050. * and executed twice.
  21051. *
  21052. * @element ANY
  21053. * @scope
  21054. * @priority 500
  21055. * @param {expression} ngController Name of a constructor function registered with the current
  21056. * {@link ng.$controllerProvider $controllerProvider} or an {@link guide/expression expression}
  21057. * that on the current scope evaluates to a constructor function.
  21058. *
  21059. * The controller instance can be published into a scope property by specifying
  21060. * `ng-controller="as propertyName"`.
  21061. *
  21062. * If the current `$controllerProvider` is configured to use globals (via
  21063. * {@link ng.$controllerProvider#allowGlobals `$controllerProvider.allowGlobals()` }), this may
  21064. * also be the name of a globally accessible constructor function (not recommended).
  21065. *
  21066. * @example
  21067. * Here is a simple form for editing user contact information. Adding, removing, clearing, and
  21068. * greeting are methods declared on the controller (see source tab). These methods can
  21069. * easily be called from the angular markup. Any changes to the data are automatically reflected
  21070. * in the View without the need for a manual update.
  21071. *
  21072. * Two different declaration styles are included below:
  21073. *
  21074. * * one binds methods and properties directly onto the controller using `this`:
  21075. * `ng-controller="SettingsController1 as settings"`
  21076. * * one injects `$scope` into the controller:
  21077. * `ng-controller="SettingsController2"`
  21078. *
  21079. * The second option is more common in the Angular community, and is generally used in boilerplates
  21080. * and in this guide. However, there are advantages to binding properties directly to the controller
  21081. * and avoiding scope.
  21082. *
  21083. * * Using `controller as` makes it obvious which controller you are accessing in the template when
  21084. * multiple controllers apply to an element.
  21085. * * If you are writing your controllers as classes you have easier access to the properties and
  21086. * methods, which will appear on the scope, from inside the controller code.
  21087. * * Since there is always a `.` in the bindings, you don't have to worry about prototypal
  21088. * inheritance masking primitives.
  21089. *
  21090. * This example demonstrates the `controller as` syntax.
  21091. *
  21092. * <example name="ngControllerAs" module="controllerAsExample">
  21093. * <file name="index.html">
  21094. * <div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
  21095. * <label>Name: <input type="text" ng-model="settings.name"/></label>
  21096. * <button ng-click="settings.greet()">greet</button><br/>
  21097. * Contact:
  21098. * <ul>
  21099. * <li ng-repeat="contact in settings.contacts">
  21100. * <select ng-model="contact.type" aria-label="Contact method" id="select_{{$index}}">
  21101. * <option>phone</option>
  21102. * <option>email</option>
  21103. * </select>
  21104. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  21105. * <button ng-click="settings.clearContact(contact)">clear</button>
  21106. * <button ng-click="settings.removeContact(contact)" aria-label="Remove">X</button>
  21107. * </li>
  21108. * <li><button ng-click="settings.addContact()">add</button></li>
  21109. * </ul>
  21110. * </div>
  21111. * </file>
  21112. * <file name="app.js">
  21113. * angular.module('controllerAsExample', [])
  21114. * .controller('SettingsController1', SettingsController1);
  21115. *
  21116. * function SettingsController1() {
  21117. * this.name = "John Smith";
  21118. * this.contacts = [
  21119. * {type: 'phone', value: '408 555 1212'},
  21120. * {type: 'email', value: 'john.smith@example.org'} ];
  21121. * }
  21122. *
  21123. * SettingsController1.prototype.greet = function() {
  21124. * alert(this.name);
  21125. * };
  21126. *
  21127. * SettingsController1.prototype.addContact = function() {
  21128. * this.contacts.push({type: 'email', value: 'yourname@example.org'});
  21129. * };
  21130. *
  21131. * SettingsController1.prototype.removeContact = function(contactToRemove) {
  21132. * var index = this.contacts.indexOf(contactToRemove);
  21133. * this.contacts.splice(index, 1);
  21134. * };
  21135. *
  21136. * SettingsController1.prototype.clearContact = function(contact) {
  21137. * contact.type = 'phone';
  21138. * contact.value = '';
  21139. * };
  21140. * </file>
  21141. * <file name="protractor.js" type="protractor">
  21142. * it('should check controller as', function() {
  21143. * var container = element(by.id('ctrl-as-exmpl'));
  21144. * expect(container.element(by.model('settings.name'))
  21145. * .getAttribute('value')).toBe('John Smith');
  21146. *
  21147. * var firstRepeat =
  21148. * container.element(by.repeater('contact in settings.contacts').row(0));
  21149. * var secondRepeat =
  21150. * container.element(by.repeater('contact in settings.contacts').row(1));
  21151. *
  21152. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21153. * .toBe('408 555 1212');
  21154. *
  21155. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  21156. * .toBe('john.smith@example.org');
  21157. *
  21158. * firstRepeat.element(by.buttonText('clear')).click();
  21159. *
  21160. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21161. * .toBe('');
  21162. *
  21163. * container.element(by.buttonText('add')).click();
  21164. *
  21165. * expect(container.element(by.repeater('contact in settings.contacts').row(2))
  21166. * .element(by.model('contact.value'))
  21167. * .getAttribute('value'))
  21168. * .toBe('yourname@example.org');
  21169. * });
  21170. * </file>
  21171. * </example>
  21172. *
  21173. * This example demonstrates the "attach to `$scope`" style of controller.
  21174. *
  21175. * <example name="ngController" module="controllerExample">
  21176. * <file name="index.html">
  21177. * <div id="ctrl-exmpl" ng-controller="SettingsController2">
  21178. * <label>Name: <input type="text" ng-model="name"/></label>
  21179. * <button ng-click="greet()">greet</button><br/>
  21180. * Contact:
  21181. * <ul>
  21182. * <li ng-repeat="contact in contacts">
  21183. * <select ng-model="contact.type" id="select_{{$index}}">
  21184. * <option>phone</option>
  21185. * <option>email</option>
  21186. * </select>
  21187. * <input type="text" ng-model="contact.value" aria-labelledby="select_{{$index}}" />
  21188. * <button ng-click="clearContact(contact)">clear</button>
  21189. * <button ng-click="removeContact(contact)">X</button>
  21190. * </li>
  21191. * <li>[ <button ng-click="addContact()">add</button> ]</li>
  21192. * </ul>
  21193. * </div>
  21194. * </file>
  21195. * <file name="app.js">
  21196. * angular.module('controllerExample', [])
  21197. * .controller('SettingsController2', ['$scope', SettingsController2]);
  21198. *
  21199. * function SettingsController2($scope) {
  21200. * $scope.name = "John Smith";
  21201. * $scope.contacts = [
  21202. * {type:'phone', value:'408 555 1212'},
  21203. * {type:'email', value:'john.smith@example.org'} ];
  21204. *
  21205. * $scope.greet = function() {
  21206. * alert($scope.name);
  21207. * };
  21208. *
  21209. * $scope.addContact = function() {
  21210. * $scope.contacts.push({type:'email', value:'yourname@example.org'});
  21211. * };
  21212. *
  21213. * $scope.removeContact = function(contactToRemove) {
  21214. * var index = $scope.contacts.indexOf(contactToRemove);
  21215. * $scope.contacts.splice(index, 1);
  21216. * };
  21217. *
  21218. * $scope.clearContact = function(contact) {
  21219. * contact.type = 'phone';
  21220. * contact.value = '';
  21221. * };
  21222. * }
  21223. * </file>
  21224. * <file name="protractor.js" type="protractor">
  21225. * it('should check controller', function() {
  21226. * var container = element(by.id('ctrl-exmpl'));
  21227. *
  21228. * expect(container.element(by.model('name'))
  21229. * .getAttribute('value')).toBe('John Smith');
  21230. *
  21231. * var firstRepeat =
  21232. * container.element(by.repeater('contact in contacts').row(0));
  21233. * var secondRepeat =
  21234. * container.element(by.repeater('contact in contacts').row(1));
  21235. *
  21236. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21237. * .toBe('408 555 1212');
  21238. * expect(secondRepeat.element(by.model('contact.value')).getAttribute('value'))
  21239. * .toBe('john.smith@example.org');
  21240. *
  21241. * firstRepeat.element(by.buttonText('clear')).click();
  21242. *
  21243. * expect(firstRepeat.element(by.model('contact.value')).getAttribute('value'))
  21244. * .toBe('');
  21245. *
  21246. * container.element(by.buttonText('add')).click();
  21247. *
  21248. * expect(container.element(by.repeater('contact in contacts').row(2))
  21249. * .element(by.model('contact.value'))
  21250. * .getAttribute('value'))
  21251. * .toBe('yourname@example.org');
  21252. * });
  21253. * </file>
  21254. *</example>
  21255. */
  21256. var ngControllerDirective = [function() {
  21257. return {
  21258. restrict: 'A',
  21259. scope: true,
  21260. controller: '@',
  21261. priority: 500
  21262. };
  21263. }];
  21264. /**
  21265. * @ngdoc directive
  21266. * @name ngCsp
  21267. *
  21268. * @element html
  21269. * @description
  21270. *
  21271. * Angular has some features that can break certain
  21272. * [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) rules.
  21273. *
  21274. * If you intend to implement these rules then you must tell Angular not to use these features.
  21275. *
  21276. * This is necessary when developing things like Google Chrome Extensions or Universal Windows Apps.
  21277. *
  21278. *
  21279. * The following rules affect Angular:
  21280. *
  21281. * * `unsafe-eval`: this rule forbids apps to use `eval` or `Function(string)` generated functions
  21282. * (among other things). Angular makes use of this in the {@link $parse} service to provide a 30%
  21283. * increase in the speed of evaluating Angular expressions.
  21284. *
  21285. * * `unsafe-inline`: this rule forbids apps from inject custom styles into the document. Angular
  21286. * makes use of this to include some CSS rules (e.g. {@link ngCloak} and {@link ngHide}).
  21287. * To make these directives work when a CSP rule is blocking inline styles, you must link to the
  21288. * `angular-csp.css` in your HTML manually.
  21289. *
  21290. * If you do not provide `ngCsp` then Angular tries to autodetect if CSP is blocking unsafe-eval
  21291. * and automatically deactivates this feature in the {@link $parse} service. This autodetection,
  21292. * however, triggers a CSP error to be logged in the console:
  21293. *
  21294. * ```
  21295. * Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of
  21296. * script in the following Content Security Policy directive: "default-src 'self'". Note that
  21297. * 'script-src' was not explicitly set, so 'default-src' is used as a fallback.
  21298. * ```
  21299. *
  21300. * This error is harmless but annoying. To prevent the error from showing up, put the `ngCsp`
  21301. * directive on an element of the HTML document that appears before the `<script>` tag that loads
  21302. * the `angular.js` file.
  21303. *
  21304. * *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
  21305. *
  21306. * You can specify which of the CSP related Angular features should be deactivated by providing
  21307. * a value for the `ng-csp` attribute. The options are as follows:
  21308. *
  21309. * * no-inline-style: this stops Angular from injecting CSS styles into the DOM
  21310. *
  21311. * * no-unsafe-eval: this stops Angular from optimising $parse with unsafe eval of strings
  21312. *
  21313. * You can use these values in the following combinations:
  21314. *
  21315. *
  21316. * * No declaration means that Angular will assume that you can do inline styles, but it will do
  21317. * a runtime check for unsafe-eval. E.g. `<body>`. This is backwardly compatible with previous versions
  21318. * of Angular.
  21319. *
  21320. * * A simple `ng-csp` (or `data-ng-csp`) attribute will tell Angular to deactivate both inline
  21321. * styles and unsafe eval. E.g. `<body ng-csp>`. This is backwardly compatible with previous versions
  21322. * of Angular.
  21323. *
  21324. * * Specifying only `no-unsafe-eval` tells Angular that we must not use eval, but that we can inject
  21325. * inline styles. E.g. `<body ng-csp="no-unsafe-eval">`.
  21326. *
  21327. * * Specifying only `no-inline-style` tells Angular that we must not inject styles, but that we can
  21328. * run eval - no automcatic check for unsafe eval will occur. E.g. `<body ng-csp="no-inline-style">`
  21329. *
  21330. * * Specifying both `no-unsafe-eval` and `no-inline-style` tells Angular that we must not inject
  21331. * styles nor use eval, which is the same as an empty: ng-csp.
  21332. * E.g.`<body ng-csp="no-inline-style;no-unsafe-eval">`
  21333. *
  21334. * @example
  21335. * This example shows how to apply the `ngCsp` directive to the `html` tag.
  21336. ```html
  21337. <!doctype html>
  21338. <html ng-app ng-csp>
  21339. ...
  21340. ...
  21341. </html>
  21342. ```
  21343. * @example
  21344. // Note: the suffix `.csp` in the example name triggers
  21345. // csp mode in our http server!
  21346. <example name="example.csp" module="cspExample" ng-csp="true">
  21347. <file name="index.html">
  21348. <div ng-controller="MainController as ctrl">
  21349. <div>
  21350. <button ng-click="ctrl.inc()" id="inc">Increment</button>
  21351. <span id="counter">
  21352. {{ctrl.counter}}
  21353. </span>
  21354. </div>
  21355. <div>
  21356. <button ng-click="ctrl.evil()" id="evil">Evil</button>
  21357. <span id="evilError">
  21358. {{ctrl.evilError}}
  21359. </span>
  21360. </div>
  21361. </div>
  21362. </file>
  21363. <file name="script.js">
  21364. angular.module('cspExample', [])
  21365. .controller('MainController', function() {
  21366. this.counter = 0;
  21367. this.inc = function() {
  21368. this.counter++;
  21369. };
  21370. this.evil = function() {
  21371. // jshint evil:true
  21372. try {
  21373. eval('1+2');
  21374. } catch (e) {
  21375. this.evilError = e.message;
  21376. }
  21377. };
  21378. });
  21379. </file>
  21380. <file name="protractor.js" type="protractor">
  21381. var util, webdriver;
  21382. var incBtn = element(by.id('inc'));
  21383. var counter = element(by.id('counter'));
  21384. var evilBtn = element(by.id('evil'));
  21385. var evilError = element(by.id('evilError'));
  21386. function getAndClearSevereErrors() {
  21387. return browser.manage().logs().get('browser').then(function(browserLog) {
  21388. return browserLog.filter(function(logEntry) {
  21389. return logEntry.level.value > webdriver.logging.Level.WARNING.value;
  21390. });
  21391. });
  21392. }
  21393. function clearErrors() {
  21394. getAndClearSevereErrors();
  21395. }
  21396. function expectNoErrors() {
  21397. getAndClearSevereErrors().then(function(filteredLog) {
  21398. expect(filteredLog.length).toEqual(0);
  21399. if (filteredLog.length) {
  21400. console.log('browser console errors: ' + util.inspect(filteredLog));
  21401. }
  21402. });
  21403. }
  21404. function expectError(regex) {
  21405. getAndClearSevereErrors().then(function(filteredLog) {
  21406. var found = false;
  21407. filteredLog.forEach(function(log) {
  21408. if (log.message.match(regex)) {
  21409. found = true;
  21410. }
  21411. });
  21412. if (!found) {
  21413. throw new Error('expected an error that matches ' + regex);
  21414. }
  21415. });
  21416. }
  21417. beforeEach(function() {
  21418. util = require('util');
  21419. webdriver = require('protractor/node_modules/selenium-webdriver');
  21420. });
  21421. // For now, we only test on Chrome,
  21422. // as Safari does not load the page with Protractor's injected scripts,
  21423. // and Firefox webdriver always disables content security policy (#6358)
  21424. if (browser.params.browser !== 'chrome') {
  21425. return;
  21426. }
  21427. it('should not report errors when the page is loaded', function() {
  21428. // clear errors so we are not dependent on previous tests
  21429. clearErrors();
  21430. // Need to reload the page as the page is already loaded when
  21431. // we come here
  21432. browser.driver.getCurrentUrl().then(function(url) {
  21433. browser.get(url);
  21434. });
  21435. expectNoErrors();
  21436. });
  21437. it('should evaluate expressions', function() {
  21438. expect(counter.getText()).toEqual('0');
  21439. incBtn.click();
  21440. expect(counter.getText()).toEqual('1');
  21441. expectNoErrors();
  21442. });
  21443. it('should throw and report an error when using "eval"', function() {
  21444. evilBtn.click();
  21445. expect(evilError.getText()).toMatch(/Content Security Policy/);
  21446. expectError(/Content Security Policy/);
  21447. });
  21448. </file>
  21449. </example>
  21450. */
  21451. // ngCsp is not implemented as a proper directive any more, because we need it be processed while we
  21452. // bootstrap the system (before $parse is instantiated), for this reason we just have
  21453. // the csp() fn that looks for the `ng-csp` attribute anywhere in the current doc
  21454. /**
  21455. * @ngdoc directive
  21456. * @name ngClick
  21457. *
  21458. * @description
  21459. * The ngClick directive allows you to specify custom behavior when
  21460. * an element is clicked.
  21461. *
  21462. * @element ANY
  21463. * @priority 0
  21464. * @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
  21465. * click. ({@link guide/expression#-event- Event object is available as `$event`})
  21466. *
  21467. * @example
  21468. <example>
  21469. <file name="index.html">
  21470. <button ng-click="count = count + 1" ng-init="count=0">
  21471. Increment
  21472. </button>
  21473. <span>
  21474. count: {{count}}
  21475. </span>
  21476. </file>
  21477. <file name="protractor.js" type="protractor">
  21478. it('should check ng-click', function() {
  21479. expect(element(by.binding('count')).getText()).toMatch('0');
  21480. element(by.css('button')).click();
  21481. expect(element(by.binding('count')).getText()).toMatch('1');
  21482. });
  21483. </file>
  21484. </example>
  21485. */
  21486. /*
  21487. * A collection of directives that allows creation of custom event handlers that are defined as
  21488. * angular expressions and are compiled and executed within the current scope.
  21489. */
  21490. var ngEventDirectives = {};
  21491. // For events that might fire synchronously during DOM manipulation
  21492. // we need to execute their event handlers asynchronously using $evalAsync,
  21493. // so that they are not executed in an inconsistent state.
  21494. var forceAsyncEvents = {
  21495. 'blur': true,
  21496. 'focus': true
  21497. };
  21498. forEach(
  21499. 'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
  21500. function(eventName) {
  21501. var directiveName = directiveNormalize('ng-' + eventName);
  21502. ngEventDirectives[directiveName] = ['$parse', '$rootScope', function($parse, $rootScope) {
  21503. return {
  21504. restrict: 'A',
  21505. compile: function($element, attr) {
  21506. // We expose the powerful $event object on the scope that provides access to the Window,
  21507. // etc. that isn't protected by the fast paths in $parse. We explicitly request better
  21508. // checks at the cost of speed since event handler expressions are not executed as
  21509. // frequently as regular change detection.
  21510. var fn = $parse(attr[directiveName], /* interceptorFn */ null, /* expensiveChecks */ true);
  21511. return function ngEventHandler(scope, element) {
  21512. element.on(eventName, function(event) {
  21513. var callback = function() {
  21514. fn(scope, {$event:event});
  21515. };
  21516. if (forceAsyncEvents[eventName] && $rootScope.$$phase) {
  21517. scope.$evalAsync(callback);
  21518. } else {
  21519. scope.$apply(callback);
  21520. }
  21521. });
  21522. };
  21523. }
  21524. };
  21525. }];
  21526. }
  21527. );
  21528. /**
  21529. * @ngdoc directive
  21530. * @name ngDblclick
  21531. *
  21532. * @description
  21533. * The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
  21534. *
  21535. * @element ANY
  21536. * @priority 0
  21537. * @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
  21538. * a dblclick. (The Event object is available as `$event`)
  21539. *
  21540. * @example
  21541. <example>
  21542. <file name="index.html">
  21543. <button ng-dblclick="count = count + 1" ng-init="count=0">
  21544. Increment (on double click)
  21545. </button>
  21546. count: {{count}}
  21547. </file>
  21548. </example>
  21549. */
  21550. /**
  21551. * @ngdoc directive
  21552. * @name ngMousedown
  21553. *
  21554. * @description
  21555. * The ngMousedown directive allows you to specify custom behavior on mousedown event.
  21556. *
  21557. * @element ANY
  21558. * @priority 0
  21559. * @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
  21560. * mousedown. ({@link guide/expression#-event- Event object is available as `$event`})
  21561. *
  21562. * @example
  21563. <example>
  21564. <file name="index.html">
  21565. <button ng-mousedown="count = count + 1" ng-init="count=0">
  21566. Increment (on mouse down)
  21567. </button>
  21568. count: {{count}}
  21569. </file>
  21570. </example>
  21571. */
  21572. /**
  21573. * @ngdoc directive
  21574. * @name ngMouseup
  21575. *
  21576. * @description
  21577. * Specify custom behavior on mouseup event.
  21578. *
  21579. * @element ANY
  21580. * @priority 0
  21581. * @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
  21582. * mouseup. ({@link guide/expression#-event- Event object is available as `$event`})
  21583. *
  21584. * @example
  21585. <example>
  21586. <file name="index.html">
  21587. <button ng-mouseup="count = count + 1" ng-init="count=0">
  21588. Increment (on mouse up)
  21589. </button>
  21590. count: {{count}}
  21591. </file>
  21592. </example>
  21593. */
  21594. /**
  21595. * @ngdoc directive
  21596. * @name ngMouseover
  21597. *
  21598. * @description
  21599. * Specify custom behavior on mouseover event.
  21600. *
  21601. * @element ANY
  21602. * @priority 0
  21603. * @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
  21604. * mouseover. ({@link guide/expression#-event- Event object is available as `$event`})
  21605. *
  21606. * @example
  21607. <example>
  21608. <file name="index.html">
  21609. <button ng-mouseover="count = count + 1" ng-init="count=0">
  21610. Increment (when mouse is over)
  21611. </button>
  21612. count: {{count}}
  21613. </file>
  21614. </example>
  21615. */
  21616. /**
  21617. * @ngdoc directive
  21618. * @name ngMouseenter
  21619. *
  21620. * @description
  21621. * Specify custom behavior on mouseenter event.
  21622. *
  21623. * @element ANY
  21624. * @priority 0
  21625. * @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
  21626. * mouseenter. ({@link guide/expression#-event- Event object is available as `$event`})
  21627. *
  21628. * @example
  21629. <example>
  21630. <file name="index.html">
  21631. <button ng-mouseenter="count = count + 1" ng-init="count=0">
  21632. Increment (when mouse enters)
  21633. </button>
  21634. count: {{count}}
  21635. </file>
  21636. </example>
  21637. */
  21638. /**
  21639. * @ngdoc directive
  21640. * @name ngMouseleave
  21641. *
  21642. * @description
  21643. * Specify custom behavior on mouseleave event.
  21644. *
  21645. * @element ANY
  21646. * @priority 0
  21647. * @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
  21648. * mouseleave. ({@link guide/expression#-event- Event object is available as `$event`})
  21649. *
  21650. * @example
  21651. <example>
  21652. <file name="index.html">
  21653. <button ng-mouseleave="count = count + 1" ng-init="count=0">
  21654. Increment (when mouse leaves)
  21655. </button>
  21656. count: {{count}}
  21657. </file>
  21658. </example>
  21659. */
  21660. /**
  21661. * @ngdoc directive
  21662. * @name ngMousemove
  21663. *
  21664. * @description
  21665. * Specify custom behavior on mousemove event.
  21666. *
  21667. * @element ANY
  21668. * @priority 0
  21669. * @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
  21670. * mousemove. ({@link guide/expression#-event- Event object is available as `$event`})
  21671. *
  21672. * @example
  21673. <example>
  21674. <file name="index.html">
  21675. <button ng-mousemove="count = count + 1" ng-init="count=0">
  21676. Increment (when mouse moves)
  21677. </button>
  21678. count: {{count}}
  21679. </file>
  21680. </example>
  21681. */
  21682. /**
  21683. * @ngdoc directive
  21684. * @name ngKeydown
  21685. *
  21686. * @description
  21687. * Specify custom behavior on keydown event.
  21688. *
  21689. * @element ANY
  21690. * @priority 0
  21691. * @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
  21692. * keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21693. *
  21694. * @example
  21695. <example>
  21696. <file name="index.html">
  21697. <input ng-keydown="count = count + 1" ng-init="count=0">
  21698. key down count: {{count}}
  21699. </file>
  21700. </example>
  21701. */
  21702. /**
  21703. * @ngdoc directive
  21704. * @name ngKeyup
  21705. *
  21706. * @description
  21707. * Specify custom behavior on keyup event.
  21708. *
  21709. * @element ANY
  21710. * @priority 0
  21711. * @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
  21712. * keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
  21713. *
  21714. * @example
  21715. <example>
  21716. <file name="index.html">
  21717. <p>Typing in the input box below updates the key count</p>
  21718. <input ng-keyup="count = count + 1" ng-init="count=0"> key up count: {{count}}
  21719. <p>Typing in the input box below updates the keycode</p>
  21720. <input ng-keyup="event=$event">
  21721. <p>event keyCode: {{ event.keyCode }}</p>
  21722. <p>event altKey: {{ event.altKey }}</p>
  21723. </file>
  21724. </example>
  21725. */
  21726. /**
  21727. * @ngdoc directive
  21728. * @name ngKeypress
  21729. *
  21730. * @description
  21731. * Specify custom behavior on keypress event.
  21732. *
  21733. * @element ANY
  21734. * @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
  21735. * keypress. ({@link guide/expression#-event- Event object is available as `$event`}
  21736. * and can be interrogated for keyCode, altKey, etc.)
  21737. *
  21738. * @example
  21739. <example>
  21740. <file name="index.html">
  21741. <input ng-keypress="count = count + 1" ng-init="count=0">
  21742. key press count: {{count}}
  21743. </file>
  21744. </example>
  21745. */
  21746. /**
  21747. * @ngdoc directive
  21748. * @name ngSubmit
  21749. *
  21750. * @description
  21751. * Enables binding angular expressions to onsubmit events.
  21752. *
  21753. * Additionally it prevents the default action (which for form means sending the request to the
  21754. * server and reloading the current page), but only if the form does not contain `action`,
  21755. * `data-action`, or `x-action` attributes.
  21756. *
  21757. * <div class="alert alert-warning">
  21758. * **Warning:** Be careful not to cause "double-submission" by using both the `ngClick` and
  21759. * `ngSubmit` handlers together. See the
  21760. * {@link form#submitting-a-form-and-preventing-the-default-action `form` directive documentation}
  21761. * for a detailed discussion of when `ngSubmit` may be triggered.
  21762. * </div>
  21763. *
  21764. * @element form
  21765. * @priority 0
  21766. * @param {expression} ngSubmit {@link guide/expression Expression} to eval.
  21767. * ({@link guide/expression#-event- Event object is available as `$event`})
  21768. *
  21769. * @example
  21770. <example module="submitExample">
  21771. <file name="index.html">
  21772. <script>
  21773. angular.module('submitExample', [])
  21774. .controller('ExampleController', ['$scope', function($scope) {
  21775. $scope.list = [];
  21776. $scope.text = 'hello';
  21777. $scope.submit = function() {
  21778. if ($scope.text) {
  21779. $scope.list.push(this.text);
  21780. $scope.text = '';
  21781. }
  21782. };
  21783. }]);
  21784. </script>
  21785. <form ng-submit="submit()" ng-controller="ExampleController">
  21786. Enter text and hit enter:
  21787. <input type="text" ng-model="text" name="text" />
  21788. <input type="submit" id="submit" value="Submit" />
  21789. <pre>list={{list}}</pre>
  21790. </form>
  21791. </file>
  21792. <file name="protractor.js" type="protractor">
  21793. it('should check ng-submit', function() {
  21794. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21795. element(by.css('#submit')).click();
  21796. expect(element(by.binding('list')).getText()).toContain('hello');
  21797. expect(element(by.model('text')).getAttribute('value')).toBe('');
  21798. });
  21799. it('should ignore empty strings', function() {
  21800. expect(element(by.binding('list')).getText()).toBe('list=[]');
  21801. element(by.css('#submit')).click();
  21802. element(by.css('#submit')).click();
  21803. expect(element(by.binding('list')).getText()).toContain('hello');
  21804. });
  21805. </file>
  21806. </example>
  21807. */
  21808. /**
  21809. * @ngdoc directive
  21810. * @name ngFocus
  21811. *
  21812. * @description
  21813. * Specify custom behavior on focus event.
  21814. *
  21815. * Note: As the `focus` event is executed synchronously when calling `input.focus()`
  21816. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21817. * during an `$apply` to ensure a consistent state.
  21818. *
  21819. * @element window, input, select, textarea, a
  21820. * @priority 0
  21821. * @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
  21822. * focus. ({@link guide/expression#-event- Event object is available as `$event`})
  21823. *
  21824. * @example
  21825. * See {@link ng.directive:ngClick ngClick}
  21826. */
  21827. /**
  21828. * @ngdoc directive
  21829. * @name ngBlur
  21830. *
  21831. * @description
  21832. * Specify custom behavior on blur event.
  21833. *
  21834. * A [blur event](https://developer.mozilla.org/en-US/docs/Web/Events/blur) fires when
  21835. * an element has lost focus.
  21836. *
  21837. * Note: As the `blur` event is executed synchronously also during DOM manipulations
  21838. * (e.g. removing a focussed input),
  21839. * AngularJS executes the expression using `scope.$evalAsync` if the event is fired
  21840. * during an `$apply` to ensure a consistent state.
  21841. *
  21842. * @element window, input, select, textarea, a
  21843. * @priority 0
  21844. * @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
  21845. * blur. ({@link guide/expression#-event- Event object is available as `$event`})
  21846. *
  21847. * @example
  21848. * See {@link ng.directive:ngClick ngClick}
  21849. */
  21850. /**
  21851. * @ngdoc directive
  21852. * @name ngCopy
  21853. *
  21854. * @description
  21855. * Specify custom behavior on copy event.
  21856. *
  21857. * @element window, input, select, textarea, a
  21858. * @priority 0
  21859. * @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
  21860. * copy. ({@link guide/expression#-event- Event object is available as `$event`})
  21861. *
  21862. * @example
  21863. <example>
  21864. <file name="index.html">
  21865. <input ng-copy="copied=true" ng-init="copied=false; value='copy me'" ng-model="value">
  21866. copied: {{copied}}
  21867. </file>
  21868. </example>
  21869. */
  21870. /**
  21871. * @ngdoc directive
  21872. * @name ngCut
  21873. *
  21874. * @description
  21875. * Specify custom behavior on cut event.
  21876. *
  21877. * @element window, input, select, textarea, a
  21878. * @priority 0
  21879. * @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
  21880. * cut. ({@link guide/expression#-event- Event object is available as `$event`})
  21881. *
  21882. * @example
  21883. <example>
  21884. <file name="index.html">
  21885. <input ng-cut="cut=true" ng-init="cut=false; value='cut me'" ng-model="value">
  21886. cut: {{cut}}
  21887. </file>
  21888. </example>
  21889. */
  21890. /**
  21891. * @ngdoc directive
  21892. * @name ngPaste
  21893. *
  21894. * @description
  21895. * Specify custom behavior on paste event.
  21896. *
  21897. * @element window, input, select, textarea, a
  21898. * @priority 0
  21899. * @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
  21900. * paste. ({@link guide/expression#-event- Event object is available as `$event`})
  21901. *
  21902. * @example
  21903. <example>
  21904. <file name="index.html">
  21905. <input ng-paste="paste=true" ng-init="paste=false" placeholder='paste here'>
  21906. pasted: {{paste}}
  21907. </file>
  21908. </example>
  21909. */
  21910. /**
  21911. * @ngdoc directive
  21912. * @name ngIf
  21913. * @restrict A
  21914. * @multiElement
  21915. *
  21916. * @description
  21917. * The `ngIf` directive removes or recreates a portion of the DOM tree based on an
  21918. * {expression}. If the expression assigned to `ngIf` evaluates to a false
  21919. * value then the element is removed from the DOM, otherwise a clone of the
  21920. * element is reinserted into the DOM.
  21921. *
  21922. * `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
  21923. * element in the DOM rather than changing its visibility via the `display` css property. A common
  21924. * case when this difference is significant is when using css selectors that rely on an element's
  21925. * position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
  21926. *
  21927. * Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
  21928. * is created when the element is restored. The scope created within `ngIf` inherits from
  21929. * its parent scope using
  21930. * [prototypal inheritance](https://github.com/angular/angular.js/wiki/Understanding-Scopes#javascript-prototypal-inheritance).
  21931. * An important implication of this is if `ngModel` is used within `ngIf` to bind to
  21932. * a javascript primitive defined in the parent scope. In this case any modifications made to the
  21933. * variable within the child scope will override (hide) the value in the parent scope.
  21934. *
  21935. * Also, `ngIf` recreates elements using their compiled state. An example of this behavior
  21936. * is if an element's class attribute is directly modified after it's compiled, using something like
  21937. * jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
  21938. * the added class will be lost because the original compiled state is used to regenerate the element.
  21939. *
  21940. * Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
  21941. * and `leave` effects.
  21942. *
  21943. * @animations
  21944. * enter - happens just after the `ngIf` contents change and a new DOM element is created and injected into the `ngIf` container
  21945. * leave - happens just before the `ngIf` contents are removed from the DOM
  21946. *
  21947. * @element ANY
  21948. * @scope
  21949. * @priority 600
  21950. * @param {expression} ngIf If the {@link guide/expression expression} is falsy then
  21951. * the element is removed from the DOM tree. If it is truthy a copy of the compiled
  21952. * element is added to the DOM tree.
  21953. *
  21954. * @example
  21955. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  21956. <file name="index.html">
  21957. <label>Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /></label><br/>
  21958. Show when checked:
  21959. <span ng-if="checked" class="animate-if">
  21960. This is removed when the checkbox is unchecked.
  21961. </span>
  21962. </file>
  21963. <file name="animations.css">
  21964. .animate-if {
  21965. background:white;
  21966. border:1px solid black;
  21967. padding:10px;
  21968. }
  21969. .animate-if.ng-enter, .animate-if.ng-leave {
  21970. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  21971. }
  21972. .animate-if.ng-enter,
  21973. .animate-if.ng-leave.ng-leave-active {
  21974. opacity:0;
  21975. }
  21976. .animate-if.ng-leave,
  21977. .animate-if.ng-enter.ng-enter-active {
  21978. opacity:1;
  21979. }
  21980. </file>
  21981. </example>
  21982. */
  21983. var ngIfDirective = ['$animate', function($animate) {
  21984. return {
  21985. multiElement: true,
  21986. transclude: 'element',
  21987. priority: 600,
  21988. terminal: true,
  21989. restrict: 'A',
  21990. $$tlb: true,
  21991. link: function($scope, $element, $attr, ctrl, $transclude) {
  21992. var block, childScope, previousElements;
  21993. $scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
  21994. if (value) {
  21995. if (!childScope) {
  21996. $transclude(function(clone, newScope) {
  21997. childScope = newScope;
  21998. clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ');
  21999. // Note: We only need the first/last node of the cloned nodes.
  22000. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  22001. // by a directive with templateUrl when its template arrives.
  22002. block = {
  22003. clone: clone
  22004. };
  22005. $animate.enter(clone, $element.parent(), $element);
  22006. });
  22007. }
  22008. } else {
  22009. if (previousElements) {
  22010. previousElements.remove();
  22011. previousElements = null;
  22012. }
  22013. if (childScope) {
  22014. childScope.$destroy();
  22015. childScope = null;
  22016. }
  22017. if (block) {
  22018. previousElements = getBlockNodes(block.clone);
  22019. $animate.leave(previousElements).then(function() {
  22020. previousElements = null;
  22021. });
  22022. block = null;
  22023. }
  22024. }
  22025. });
  22026. }
  22027. };
  22028. }];
  22029. /**
  22030. * @ngdoc directive
  22031. * @name ngInclude
  22032. * @restrict ECA
  22033. *
  22034. * @description
  22035. * Fetches, compiles and includes an external HTML fragment.
  22036. *
  22037. * By default, the template URL is restricted to the same domain and protocol as the
  22038. * application document. This is done by calling {@link $sce#getTrustedResourceUrl
  22039. * $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
  22040. * you may either {@link ng.$sceDelegateProvider#resourceUrlWhitelist whitelist them} or
  22041. * {@link $sce#trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
  22042. * ng.$sce Strict Contextual Escaping}.
  22043. *
  22044. * In addition, the browser's
  22045. * [Same Origin Policy](https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest)
  22046. * and [Cross-Origin Resource Sharing (CORS)](http://www.w3.org/TR/cors/)
  22047. * policy may further restrict whether the template is successfully loaded.
  22048. * For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
  22049. * access on some browsers.
  22050. *
  22051. * @animations
  22052. * enter - animation is used to bring new content into the browser.
  22053. * leave - animation is used to animate existing content away.
  22054. *
  22055. * The enter and leave animation occur concurrently.
  22056. *
  22057. * @scope
  22058. * @priority 400
  22059. *
  22060. * @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
  22061. * make sure you wrap it in **single** quotes, e.g. `src="'myPartialTemplate.html'"`.
  22062. * @param {string=} onload Expression to evaluate when a new partial is loaded.
  22063. * <div class="alert alert-warning">
  22064. * **Note:** When using onload on SVG elements in IE11, the browser will try to call
  22065. * a function with the name on the window element, which will usually throw a
  22066. * "function is undefined" error. To fix this, you can instead use `data-onload` or a
  22067. * different form that {@link guide/directive#normalization matches} `onload`.
  22068. * </div>
  22069. *
  22070. * @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
  22071. * $anchorScroll} to scroll the viewport after the content is loaded.
  22072. *
  22073. * - If the attribute is not set, disable scrolling.
  22074. * - If the attribute is set without value, enable scrolling.
  22075. * - Otherwise enable scrolling only if the expression evaluates to truthy value.
  22076. *
  22077. * @example
  22078. <example module="includeExample" deps="angular-animate.js" animations="true">
  22079. <file name="index.html">
  22080. <div ng-controller="ExampleController">
  22081. <select ng-model="template" ng-options="t.name for t in templates">
  22082. <option value="">(blank)</option>
  22083. </select>
  22084. url of the template: <code>{{template.url}}</code>
  22085. <hr/>
  22086. <div class="slide-animate-container">
  22087. <div class="slide-animate" ng-include="template.url"></div>
  22088. </div>
  22089. </div>
  22090. </file>
  22091. <file name="script.js">
  22092. angular.module('includeExample', ['ngAnimate'])
  22093. .controller('ExampleController', ['$scope', function($scope) {
  22094. $scope.templates =
  22095. [ { name: 'template1.html', url: 'template1.html'},
  22096. { name: 'template2.html', url: 'template2.html'} ];
  22097. $scope.template = $scope.templates[0];
  22098. }]);
  22099. </file>
  22100. <file name="template1.html">
  22101. Content of template1.html
  22102. </file>
  22103. <file name="template2.html">
  22104. Content of template2.html
  22105. </file>
  22106. <file name="animations.css">
  22107. .slide-animate-container {
  22108. position:relative;
  22109. background:white;
  22110. border:1px solid black;
  22111. height:40px;
  22112. overflow:hidden;
  22113. }
  22114. .slide-animate {
  22115. padding:10px;
  22116. }
  22117. .slide-animate.ng-enter, .slide-animate.ng-leave {
  22118. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  22119. position:absolute;
  22120. top:0;
  22121. left:0;
  22122. right:0;
  22123. bottom:0;
  22124. display:block;
  22125. padding:10px;
  22126. }
  22127. .slide-animate.ng-enter {
  22128. top:-50px;
  22129. }
  22130. .slide-animate.ng-enter.ng-enter-active {
  22131. top:0;
  22132. }
  22133. .slide-animate.ng-leave {
  22134. top:0;
  22135. }
  22136. .slide-animate.ng-leave.ng-leave-active {
  22137. top:50px;
  22138. }
  22139. </file>
  22140. <file name="protractor.js" type="protractor">
  22141. var templateSelect = element(by.model('template'));
  22142. var includeElem = element(by.css('[ng-include]'));
  22143. it('should load template1.html', function() {
  22144. expect(includeElem.getText()).toMatch(/Content of template1.html/);
  22145. });
  22146. it('should load template2.html', function() {
  22147. if (browser.params.browser == 'firefox') {
  22148. // Firefox can't handle using selects
  22149. // See https://github.com/angular/protractor/issues/480
  22150. return;
  22151. }
  22152. templateSelect.click();
  22153. templateSelect.all(by.css('option')).get(2).click();
  22154. expect(includeElem.getText()).toMatch(/Content of template2.html/);
  22155. });
  22156. it('should change to blank', function() {
  22157. if (browser.params.browser == 'firefox') {
  22158. // Firefox can't handle using selects
  22159. return;
  22160. }
  22161. templateSelect.click();
  22162. templateSelect.all(by.css('option')).get(0).click();
  22163. expect(includeElem.isPresent()).toBe(false);
  22164. });
  22165. </file>
  22166. </example>
  22167. */
  22168. /**
  22169. * @ngdoc event
  22170. * @name ngInclude#$includeContentRequested
  22171. * @eventType emit on the scope ngInclude was declared in
  22172. * @description
  22173. * Emitted every time the ngInclude content is requested.
  22174. *
  22175. * @param {Object} angularEvent Synthetic event object.
  22176. * @param {String} src URL of content to load.
  22177. */
  22178. /**
  22179. * @ngdoc event
  22180. * @name ngInclude#$includeContentLoaded
  22181. * @eventType emit on the current ngInclude scope
  22182. * @description
  22183. * Emitted every time the ngInclude content is reloaded.
  22184. *
  22185. * @param {Object} angularEvent Synthetic event object.
  22186. * @param {String} src URL of content to load.
  22187. */
  22188. /**
  22189. * @ngdoc event
  22190. * @name ngInclude#$includeContentError
  22191. * @eventType emit on the scope ngInclude was declared in
  22192. * @description
  22193. * Emitted when a template HTTP request yields an erroneous response (status < 200 || status > 299)
  22194. *
  22195. * @param {Object} angularEvent Synthetic event object.
  22196. * @param {String} src URL of content to load.
  22197. */
  22198. var ngIncludeDirective = ['$templateRequest', '$anchorScroll', '$animate',
  22199. function($templateRequest, $anchorScroll, $animate) {
  22200. return {
  22201. restrict: 'ECA',
  22202. priority: 400,
  22203. terminal: true,
  22204. transclude: 'element',
  22205. controller: angular.noop,
  22206. compile: function(element, attr) {
  22207. var srcExp = attr.ngInclude || attr.src,
  22208. onloadExp = attr.onload || '',
  22209. autoScrollExp = attr.autoscroll;
  22210. return function(scope, $element, $attr, ctrl, $transclude) {
  22211. var changeCounter = 0,
  22212. currentScope,
  22213. previousElement,
  22214. currentElement;
  22215. var cleanupLastIncludeContent = function() {
  22216. if (previousElement) {
  22217. previousElement.remove();
  22218. previousElement = null;
  22219. }
  22220. if (currentScope) {
  22221. currentScope.$destroy();
  22222. currentScope = null;
  22223. }
  22224. if (currentElement) {
  22225. $animate.leave(currentElement).then(function() {
  22226. previousElement = null;
  22227. });
  22228. previousElement = currentElement;
  22229. currentElement = null;
  22230. }
  22231. };
  22232. scope.$watch(srcExp, function ngIncludeWatchAction(src) {
  22233. var afterAnimation = function() {
  22234. if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
  22235. $anchorScroll();
  22236. }
  22237. };
  22238. var thisChangeId = ++changeCounter;
  22239. if (src) {
  22240. //set the 2nd param to true to ignore the template request error so that the inner
  22241. //contents and scope can be cleaned up.
  22242. $templateRequest(src, true).then(function(response) {
  22243. if (thisChangeId !== changeCounter) return;
  22244. var newScope = scope.$new();
  22245. ctrl.template = response;
  22246. // Note: This will also link all children of ng-include that were contained in the original
  22247. // html. If that content contains controllers, ... they could pollute/change the scope.
  22248. // However, using ng-include on an element with additional content does not make sense...
  22249. // Note: We can't remove them in the cloneAttchFn of $transclude as that
  22250. // function is called before linking the content, which would apply child
  22251. // directives to non existing elements.
  22252. var clone = $transclude(newScope, function(clone) {
  22253. cleanupLastIncludeContent();
  22254. $animate.enter(clone, null, $element).then(afterAnimation);
  22255. });
  22256. currentScope = newScope;
  22257. currentElement = clone;
  22258. currentScope.$emit('$includeContentLoaded', src);
  22259. scope.$eval(onloadExp);
  22260. }, function() {
  22261. if (thisChangeId === changeCounter) {
  22262. cleanupLastIncludeContent();
  22263. scope.$emit('$includeContentError', src);
  22264. }
  22265. });
  22266. scope.$emit('$includeContentRequested', src);
  22267. } else {
  22268. cleanupLastIncludeContent();
  22269. ctrl.template = null;
  22270. }
  22271. });
  22272. };
  22273. }
  22274. };
  22275. }];
  22276. // This directive is called during the $transclude call of the first `ngInclude` directive.
  22277. // It will replace and compile the content of the element with the loaded template.
  22278. // We need this directive so that the element content is already filled when
  22279. // the link function of another directive on the same element as ngInclude
  22280. // is called.
  22281. var ngIncludeFillContentDirective = ['$compile',
  22282. function($compile) {
  22283. return {
  22284. restrict: 'ECA',
  22285. priority: -400,
  22286. require: 'ngInclude',
  22287. link: function(scope, $element, $attr, ctrl) {
  22288. if (/SVG/.test($element[0].toString())) {
  22289. // WebKit: https://bugs.webkit.org/show_bug.cgi?id=135698 --- SVG elements do not
  22290. // support innerHTML, so detect this here and try to generate the contents
  22291. // specially.
  22292. $element.empty();
  22293. $compile(jqLiteBuildFragment(ctrl.template, document).childNodes)(scope,
  22294. function namespaceAdaptedClone(clone) {
  22295. $element.append(clone);
  22296. }, {futureParentElement: $element});
  22297. return;
  22298. }
  22299. $element.html(ctrl.template);
  22300. $compile($element.contents())(scope);
  22301. }
  22302. };
  22303. }];
  22304. /**
  22305. * @ngdoc directive
  22306. * @name ngInit
  22307. * @restrict AC
  22308. *
  22309. * @description
  22310. * The `ngInit` directive allows you to evaluate an expression in the
  22311. * current scope.
  22312. *
  22313. * <div class="alert alert-danger">
  22314. * This directive can be abused to add unnecessary amounts of logic into your templates.
  22315. * There are only a few appropriate uses of `ngInit`, such as for aliasing special properties of
  22316. * {@link ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below; and for injecting data via
  22317. * server side scripting. Besides these few cases, you should use {@link guide/controller controllers}
  22318. * rather than `ngInit` to initialize values on a scope.
  22319. * </div>
  22320. *
  22321. * <div class="alert alert-warning">
  22322. * **Note**: If you have assignment in `ngInit` along with a {@link ng.$filter `filter`}, make
  22323. * sure you have parentheses to ensure correct operator precedence:
  22324. * <pre class="prettyprint">
  22325. * `<div ng-init="test1 = ($index | toString)"></div>`
  22326. * </pre>
  22327. * </div>
  22328. *
  22329. * @priority 450
  22330. *
  22331. * @element ANY
  22332. * @param {expression} ngInit {@link guide/expression Expression} to eval.
  22333. *
  22334. * @example
  22335. <example module="initExample">
  22336. <file name="index.html">
  22337. <script>
  22338. angular.module('initExample', [])
  22339. .controller('ExampleController', ['$scope', function($scope) {
  22340. $scope.list = [['a', 'b'], ['c', 'd']];
  22341. }]);
  22342. </script>
  22343. <div ng-controller="ExampleController">
  22344. <div ng-repeat="innerList in list" ng-init="outerIndex = $index">
  22345. <div ng-repeat="value in innerList" ng-init="innerIndex = $index">
  22346. <span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
  22347. </div>
  22348. </div>
  22349. </div>
  22350. </file>
  22351. <file name="protractor.js" type="protractor">
  22352. it('should alias index positions', function() {
  22353. var elements = element.all(by.css('.example-init'));
  22354. expect(elements.get(0).getText()).toBe('list[ 0 ][ 0 ] = a;');
  22355. expect(elements.get(1).getText()).toBe('list[ 0 ][ 1 ] = b;');
  22356. expect(elements.get(2).getText()).toBe('list[ 1 ][ 0 ] = c;');
  22357. expect(elements.get(3).getText()).toBe('list[ 1 ][ 1 ] = d;');
  22358. });
  22359. </file>
  22360. </example>
  22361. */
  22362. var ngInitDirective = ngDirective({
  22363. priority: 450,
  22364. compile: function() {
  22365. return {
  22366. pre: function(scope, element, attrs) {
  22367. scope.$eval(attrs.ngInit);
  22368. }
  22369. };
  22370. }
  22371. });
  22372. /**
  22373. * @ngdoc directive
  22374. * @name ngList
  22375. *
  22376. * @description
  22377. * Text input that converts between a delimited string and an array of strings. The default
  22378. * delimiter is a comma followed by a space - equivalent to `ng-list=", "`. You can specify a custom
  22379. * delimiter as the value of the `ngList` attribute - for example, `ng-list=" | "`.
  22380. *
  22381. * The behaviour of the directive is affected by the use of the `ngTrim` attribute.
  22382. * * If `ngTrim` is set to `"false"` then whitespace around both the separator and each
  22383. * list item is respected. This implies that the user of the directive is responsible for
  22384. * dealing with whitespace but also allows you to use whitespace as a delimiter, such as a
  22385. * tab or newline character.
  22386. * * Otherwise whitespace around the delimiter is ignored when splitting (although it is respected
  22387. * when joining the list items back together) and whitespace around each list item is stripped
  22388. * before it is added to the model.
  22389. *
  22390. * ### Example with Validation
  22391. *
  22392. * <example name="ngList-directive" module="listExample">
  22393. * <file name="app.js">
  22394. * angular.module('listExample', [])
  22395. * .controller('ExampleController', ['$scope', function($scope) {
  22396. * $scope.names = ['morpheus', 'neo', 'trinity'];
  22397. * }]);
  22398. * </file>
  22399. * <file name="index.html">
  22400. * <form name="myForm" ng-controller="ExampleController">
  22401. * <label>List: <input name="namesInput" ng-model="names" ng-list required></label>
  22402. * <span role="alert">
  22403. * <span class="error" ng-show="myForm.namesInput.$error.required">
  22404. * Required!</span>
  22405. * </span>
  22406. * <br>
  22407. * <tt>names = {{names}}</tt><br/>
  22408. * <tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
  22409. * <tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
  22410. * <tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
  22411. * <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
  22412. * </form>
  22413. * </file>
  22414. * <file name="protractor.js" type="protractor">
  22415. * var listInput = element(by.model('names'));
  22416. * var names = element(by.exactBinding('names'));
  22417. * var valid = element(by.binding('myForm.namesInput.$valid'));
  22418. * var error = element(by.css('span.error'));
  22419. *
  22420. * it('should initialize to model', function() {
  22421. * expect(names.getText()).toContain('["morpheus","neo","trinity"]');
  22422. * expect(valid.getText()).toContain('true');
  22423. * expect(error.getCssValue('display')).toBe('none');
  22424. * });
  22425. *
  22426. * it('should be invalid if empty', function() {
  22427. * listInput.clear();
  22428. * listInput.sendKeys('');
  22429. *
  22430. * expect(names.getText()).toContain('');
  22431. * expect(valid.getText()).toContain('false');
  22432. * expect(error.getCssValue('display')).not.toBe('none');
  22433. * });
  22434. * </file>
  22435. * </example>
  22436. *
  22437. * ### Example - splitting on newline
  22438. * <example name="ngList-directive-newlines">
  22439. * <file name="index.html">
  22440. * <textarea ng-model="list" ng-list="&#10;" ng-trim="false"></textarea>
  22441. * <pre>{{ list | json }}</pre>
  22442. * </file>
  22443. * <file name="protractor.js" type="protractor">
  22444. * it("should split the text by newlines", function() {
  22445. * var listInput = element(by.model('list'));
  22446. * var output = element(by.binding('list | json'));
  22447. * listInput.sendKeys('abc\ndef\nghi');
  22448. * expect(output.getText()).toContain('[\n "abc",\n "def",\n "ghi"\n]');
  22449. * });
  22450. * </file>
  22451. * </example>
  22452. *
  22453. * @element input
  22454. * @param {string=} ngList optional delimiter that should be used to split the value.
  22455. */
  22456. var ngListDirective = function() {
  22457. return {
  22458. restrict: 'A',
  22459. priority: 100,
  22460. require: 'ngModel',
  22461. link: function(scope, element, attr, ctrl) {
  22462. // We want to control whitespace trimming so we use this convoluted approach
  22463. // to access the ngList attribute, which doesn't pre-trim the attribute
  22464. var ngList = element.attr(attr.$attr.ngList) || ', ';
  22465. var trimValues = attr.ngTrim !== 'false';
  22466. var separator = trimValues ? trim(ngList) : ngList;
  22467. var parse = function(viewValue) {
  22468. // If the viewValue is invalid (say required but empty) it will be `undefined`
  22469. if (isUndefined(viewValue)) return;
  22470. var list = [];
  22471. if (viewValue) {
  22472. forEach(viewValue.split(separator), function(value) {
  22473. if (value) list.push(trimValues ? trim(value) : value);
  22474. });
  22475. }
  22476. return list;
  22477. };
  22478. ctrl.$parsers.push(parse);
  22479. ctrl.$formatters.push(function(value) {
  22480. if (isArray(value)) {
  22481. return value.join(ngList);
  22482. }
  22483. return undefined;
  22484. });
  22485. // Override the standard $isEmpty because an empty array means the input is empty.
  22486. ctrl.$isEmpty = function(value) {
  22487. return !value || !value.length;
  22488. };
  22489. }
  22490. };
  22491. };
  22492. /* global VALID_CLASS: true,
  22493. INVALID_CLASS: true,
  22494. PRISTINE_CLASS: true,
  22495. DIRTY_CLASS: true,
  22496. UNTOUCHED_CLASS: true,
  22497. TOUCHED_CLASS: true,
  22498. */
  22499. var VALID_CLASS = 'ng-valid',
  22500. INVALID_CLASS = 'ng-invalid',
  22501. PRISTINE_CLASS = 'ng-pristine',
  22502. DIRTY_CLASS = 'ng-dirty',
  22503. UNTOUCHED_CLASS = 'ng-untouched',
  22504. TOUCHED_CLASS = 'ng-touched',
  22505. PENDING_CLASS = 'ng-pending';
  22506. var ngModelMinErr = minErr('ngModel');
  22507. /**
  22508. * @ngdoc type
  22509. * @name ngModel.NgModelController
  22510. *
  22511. * @property {*} $viewValue The actual value from the control's view. For `input` elements, this is a
  22512. * String. See {@link ngModel.NgModelController#$setViewValue} for information about when the $viewValue
  22513. * is set.
  22514. * @property {*} $modelValue The value in the model that the control is bound to.
  22515. * @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
  22516. the control reads value from the DOM. The functions are called in array order, each passing
  22517. its return value through to the next. The last return value is forwarded to the
  22518. {@link ngModel.NgModelController#$validators `$validators`} collection.
  22519. Parsers are used to sanitize / convert the {@link ngModel.NgModelController#$viewValue
  22520. `$viewValue`}.
  22521. Returning `undefined` from a parser means a parse error occurred. In that case,
  22522. no {@link ngModel.NgModelController#$validators `$validators`} will run and the `ngModel`
  22523. will be set to `undefined` unless {@link ngModelOptions `ngModelOptions.allowInvalid`}
  22524. is set to `true`. The parse error is stored in `ngModel.$error.parse`.
  22525. *
  22526. * @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
  22527. the model value changes. The functions are called in reverse array order, each passing the value through to the
  22528. next. The last return value is used as the actual DOM value.
  22529. Used to format / convert values for display in the control.
  22530. * ```js
  22531. * function formatter(value) {
  22532. * if (value) {
  22533. * return value.toUpperCase();
  22534. * }
  22535. * }
  22536. * ngModel.$formatters.push(formatter);
  22537. * ```
  22538. *
  22539. * @property {Object.<string, function>} $validators A collection of validators that are applied
  22540. * whenever the model value changes. The key value within the object refers to the name of the
  22541. * validator while the function refers to the validation operation. The validation operation is
  22542. * provided with the model value as an argument and must return a true or false value depending
  22543. * on the response of that validation.
  22544. *
  22545. * ```js
  22546. * ngModel.$validators.validCharacters = function(modelValue, viewValue) {
  22547. * var value = modelValue || viewValue;
  22548. * return /[0-9]+/.test(value) &&
  22549. * /[a-z]+/.test(value) &&
  22550. * /[A-Z]+/.test(value) &&
  22551. * /\W+/.test(value);
  22552. * };
  22553. * ```
  22554. *
  22555. * @property {Object.<string, function>} $asyncValidators A collection of validations that are expected to
  22556. * perform an asynchronous validation (e.g. a HTTP request). The validation function that is provided
  22557. * is expected to return a promise when it is run during the model validation process. Once the promise
  22558. * is delivered then the validation status will be set to true when fulfilled and false when rejected.
  22559. * When the asynchronous validators are triggered, each of the validators will run in parallel and the model
  22560. * value will only be updated once all validators have been fulfilled. As long as an asynchronous validator
  22561. * is unfulfilled, its key will be added to the controllers `$pending` property. Also, all asynchronous validators
  22562. * will only run once all synchronous validators have passed.
  22563. *
  22564. * Please note that if $http is used then it is important that the server returns a success HTTP response code
  22565. * in order to fulfill the validation and a status level of `4xx` in order to reject the validation.
  22566. *
  22567. * ```js
  22568. * ngModel.$asyncValidators.uniqueUsername = function(modelValue, viewValue) {
  22569. * var value = modelValue || viewValue;
  22570. *
  22571. * // Lookup user by username
  22572. * return $http.get('/api/users/' + value).
  22573. * then(function resolved() {
  22574. * //username exists, this means validation fails
  22575. * return $q.reject('exists');
  22576. * }, function rejected() {
  22577. * //username does not exist, therefore this validation passes
  22578. * return true;
  22579. * });
  22580. * };
  22581. * ```
  22582. *
  22583. * @property {Array.<Function>} $viewChangeListeners Array of functions to execute whenever the
  22584. * view value has changed. It is called with no arguments, and its return value is ignored.
  22585. * This can be used in place of additional $watches against the model value.
  22586. *
  22587. * @property {Object} $error An object hash with all failing validator ids as keys.
  22588. * @property {Object} $pending An object hash with all pending validator ids as keys.
  22589. *
  22590. * @property {boolean} $untouched True if control has not lost focus yet.
  22591. * @property {boolean} $touched True if control has lost focus.
  22592. * @property {boolean} $pristine True if user has not interacted with the control yet.
  22593. * @property {boolean} $dirty True if user has already interacted with the control.
  22594. * @property {boolean} $valid True if there is no error.
  22595. * @property {boolean} $invalid True if at least one error on the control.
  22596. * @property {string} $name The name attribute of the control.
  22597. *
  22598. * @description
  22599. *
  22600. * `NgModelController` provides API for the {@link ngModel `ngModel`} directive.
  22601. * The controller contains services for data-binding, validation, CSS updates, and value formatting
  22602. * and parsing. It purposefully does not contain any logic which deals with DOM rendering or
  22603. * listening to DOM events.
  22604. * Such DOM related logic should be provided by other directives which make use of
  22605. * `NgModelController` for data-binding to control elements.
  22606. * Angular provides this DOM logic for most {@link input `input`} elements.
  22607. * At the end of this page you can find a {@link ngModel.NgModelController#custom-control-example
  22608. * custom control example} that uses `ngModelController` to bind to `contenteditable` elements.
  22609. *
  22610. * @example
  22611. * ### Custom Control Example
  22612. * This example shows how to use `NgModelController` with a custom control to achieve
  22613. * data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
  22614. * collaborate together to achieve the desired result.
  22615. *
  22616. * `contenteditable` is an HTML5 attribute, which tells the browser to let the element
  22617. * contents be edited in place by the user.
  22618. *
  22619. * We are using the {@link ng.service:$sce $sce} service here and include the {@link ngSanitize $sanitize}
  22620. * module to automatically remove "bad" content like inline event listener (e.g. `<span onclick="...">`).
  22621. * However, as we are using `$sce` the model can still decide to provide unsafe content if it marks
  22622. * that content using the `$sce` service.
  22623. *
  22624. * <example name="NgModelController" module="customControl" deps="angular-sanitize.js">
  22625. <file name="style.css">
  22626. [contenteditable] {
  22627. border: 1px solid black;
  22628. background-color: white;
  22629. min-height: 20px;
  22630. }
  22631. .ng-invalid {
  22632. border: 1px solid red;
  22633. }
  22634. </file>
  22635. <file name="script.js">
  22636. angular.module('customControl', ['ngSanitize']).
  22637. directive('contenteditable', ['$sce', function($sce) {
  22638. return {
  22639. restrict: 'A', // only activate on element attribute
  22640. require: '?ngModel', // get a hold of NgModelController
  22641. link: function(scope, element, attrs, ngModel) {
  22642. if (!ngModel) return; // do nothing if no ng-model
  22643. // Specify how UI should be updated
  22644. ngModel.$render = function() {
  22645. element.html($sce.getTrustedHtml(ngModel.$viewValue || ''));
  22646. };
  22647. // Listen for change events to enable binding
  22648. element.on('blur keyup change', function() {
  22649. scope.$evalAsync(read);
  22650. });
  22651. read(); // initialize
  22652. // Write data to the model
  22653. function read() {
  22654. var html = element.html();
  22655. // When we clear the content editable the browser leaves a <br> behind
  22656. // If strip-br attribute is provided then we strip this out
  22657. if ( attrs.stripBr && html == '<br>' ) {
  22658. html = '';
  22659. }
  22660. ngModel.$setViewValue(html);
  22661. }
  22662. }
  22663. };
  22664. }]);
  22665. </file>
  22666. <file name="index.html">
  22667. <form name="myForm">
  22668. <div contenteditable
  22669. name="myWidget" ng-model="userContent"
  22670. strip-br="true"
  22671. required>Change me!</div>
  22672. <span ng-show="myForm.myWidget.$error.required">Required!</span>
  22673. <hr>
  22674. <textarea ng-model="userContent" aria-label="Dynamic textarea"></textarea>
  22675. </form>
  22676. </file>
  22677. <file name="protractor.js" type="protractor">
  22678. it('should data-bind and become invalid', function() {
  22679. if (browser.params.browser == 'safari' || browser.params.browser == 'firefox') {
  22680. // SafariDriver can't handle contenteditable
  22681. // and Firefox driver can't clear contenteditables very well
  22682. return;
  22683. }
  22684. var contentEditable = element(by.css('[contenteditable]'));
  22685. var content = 'Change me!';
  22686. expect(contentEditable.getText()).toEqual(content);
  22687. contentEditable.clear();
  22688. contentEditable.sendKeys(protractor.Key.BACK_SPACE);
  22689. expect(contentEditable.getText()).toEqual('');
  22690. expect(contentEditable.getAttribute('class')).toMatch(/ng-invalid-required/);
  22691. });
  22692. </file>
  22693. * </example>
  22694. *
  22695. *
  22696. */
  22697. var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse', '$animate', '$timeout', '$rootScope', '$q', '$interpolate',
  22698. function($scope, $exceptionHandler, $attr, $element, $parse, $animate, $timeout, $rootScope, $q, $interpolate) {
  22699. this.$viewValue = Number.NaN;
  22700. this.$modelValue = Number.NaN;
  22701. this.$$rawModelValue = undefined; // stores the parsed modelValue / model set from scope regardless of validity.
  22702. this.$validators = {};
  22703. this.$asyncValidators = {};
  22704. this.$parsers = [];
  22705. this.$formatters = [];
  22706. this.$viewChangeListeners = [];
  22707. this.$untouched = true;
  22708. this.$touched = false;
  22709. this.$pristine = true;
  22710. this.$dirty = false;
  22711. this.$valid = true;
  22712. this.$invalid = false;
  22713. this.$error = {}; // keep invalid keys here
  22714. this.$$success = {}; // keep valid keys here
  22715. this.$pending = undefined; // keep pending keys here
  22716. this.$name = $interpolate($attr.name || '', false)($scope);
  22717. this.$$parentForm = nullFormCtrl;
  22718. var parsedNgModel = $parse($attr.ngModel),
  22719. parsedNgModelAssign = parsedNgModel.assign,
  22720. ngModelGet = parsedNgModel,
  22721. ngModelSet = parsedNgModelAssign,
  22722. pendingDebounce = null,
  22723. parserValid,
  22724. ctrl = this;
  22725. this.$$setOptions = function(options) {
  22726. ctrl.$options = options;
  22727. if (options && options.getterSetter) {
  22728. var invokeModelGetter = $parse($attr.ngModel + '()'),
  22729. invokeModelSetter = $parse($attr.ngModel + '($$$p)');
  22730. ngModelGet = function($scope) {
  22731. var modelValue = parsedNgModel($scope);
  22732. if (isFunction(modelValue)) {
  22733. modelValue = invokeModelGetter($scope);
  22734. }
  22735. return modelValue;
  22736. };
  22737. ngModelSet = function($scope, newValue) {
  22738. if (isFunction(parsedNgModel($scope))) {
  22739. invokeModelSetter($scope, {$$$p: ctrl.$modelValue});
  22740. } else {
  22741. parsedNgModelAssign($scope, ctrl.$modelValue);
  22742. }
  22743. };
  22744. } else if (!parsedNgModel.assign) {
  22745. throw ngModelMinErr('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
  22746. $attr.ngModel, startingTag($element));
  22747. }
  22748. };
  22749. /**
  22750. * @ngdoc method
  22751. * @name ngModel.NgModelController#$render
  22752. *
  22753. * @description
  22754. * Called when the view needs to be updated. It is expected that the user of the ng-model
  22755. * directive will implement this method.
  22756. *
  22757. * The `$render()` method is invoked in the following situations:
  22758. *
  22759. * * `$rollbackViewValue()` is called. If we are rolling back the view value to the last
  22760. * committed value then `$render()` is called to update the input control.
  22761. * * The value referenced by `ng-model` is changed programmatically and both the `$modelValue` and
  22762. * the `$viewValue` are different from last time.
  22763. *
  22764. * Since `ng-model` does not do a deep watch, `$render()` is only invoked if the values of
  22765. * `$modelValue` and `$viewValue` are actually different from their previous value. If `$modelValue`
  22766. * or `$viewValue` are objects (rather than a string or number) then `$render()` will not be
  22767. * invoked if you only change a property on the objects.
  22768. */
  22769. this.$render = noop;
  22770. /**
  22771. * @ngdoc method
  22772. * @name ngModel.NgModelController#$isEmpty
  22773. *
  22774. * @description
  22775. * This is called when we need to determine if the value of an input is empty.
  22776. *
  22777. * For instance, the required directive does this to work out if the input has data or not.
  22778. *
  22779. * The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
  22780. *
  22781. * You can override this for input directives whose concept of being empty is different from the
  22782. * default. The `checkboxInputType` directive does this because in its case a value of `false`
  22783. * implies empty.
  22784. *
  22785. * @param {*} value The value of the input to check for emptiness.
  22786. * @returns {boolean} True if `value` is "empty".
  22787. */
  22788. this.$isEmpty = function(value) {
  22789. return isUndefined(value) || value === '' || value === null || value !== value;
  22790. };
  22791. var currentValidationRunId = 0;
  22792. /**
  22793. * @ngdoc method
  22794. * @name ngModel.NgModelController#$setValidity
  22795. *
  22796. * @description
  22797. * Change the validity state, and notify the form.
  22798. *
  22799. * This method can be called within $parsers/$formatters or a custom validation implementation.
  22800. * However, in most cases it should be sufficient to use the `ngModel.$validators` and
  22801. * `ngModel.$asyncValidators` collections which will call `$setValidity` automatically.
  22802. *
  22803. * @param {string} validationErrorKey Name of the validator. The `validationErrorKey` will be assigned
  22804. * to either `$error[validationErrorKey]` or `$pending[validationErrorKey]`
  22805. * (for unfulfilled `$asyncValidators`), so that it is available for data-binding.
  22806. * The `validationErrorKey` should be in camelCase and will get converted into dash-case
  22807. * for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
  22808. * class and can be bound to as `{{someForm.someControl.$error.myError}}` .
  22809. * @param {boolean} isValid Whether the current state is valid (true), invalid (false), pending (undefined),
  22810. * or skipped (null). Pending is used for unfulfilled `$asyncValidators`.
  22811. * Skipped is used by Angular when validators do not run because of parse errors and
  22812. * when `$asyncValidators` do not run because any of the `$validators` failed.
  22813. */
  22814. addSetValidityMethod({
  22815. ctrl: this,
  22816. $element: $element,
  22817. set: function(object, property) {
  22818. object[property] = true;
  22819. },
  22820. unset: function(object, property) {
  22821. delete object[property];
  22822. },
  22823. $animate: $animate
  22824. });
  22825. /**
  22826. * @ngdoc method
  22827. * @name ngModel.NgModelController#$setPristine
  22828. *
  22829. * @description
  22830. * Sets the control to its pristine state.
  22831. *
  22832. * This method can be called to remove the `ng-dirty` class and set the control to its pristine
  22833. * state (`ng-pristine` class). A model is considered to be pristine when the control
  22834. * has not been changed from when first compiled.
  22835. */
  22836. this.$setPristine = function() {
  22837. ctrl.$dirty = false;
  22838. ctrl.$pristine = true;
  22839. $animate.removeClass($element, DIRTY_CLASS);
  22840. $animate.addClass($element, PRISTINE_CLASS);
  22841. };
  22842. /**
  22843. * @ngdoc method
  22844. * @name ngModel.NgModelController#$setDirty
  22845. *
  22846. * @description
  22847. * Sets the control to its dirty state.
  22848. *
  22849. * This method can be called to remove the `ng-pristine` class and set the control to its dirty
  22850. * state (`ng-dirty` class). A model is considered to be dirty when the control has been changed
  22851. * from when first compiled.
  22852. */
  22853. this.$setDirty = function() {
  22854. ctrl.$dirty = true;
  22855. ctrl.$pristine = false;
  22856. $animate.removeClass($element, PRISTINE_CLASS);
  22857. $animate.addClass($element, DIRTY_CLASS);
  22858. ctrl.$$parentForm.$setDirty();
  22859. };
  22860. /**
  22861. * @ngdoc method
  22862. * @name ngModel.NgModelController#$setUntouched
  22863. *
  22864. * @description
  22865. * Sets the control to its untouched state.
  22866. *
  22867. * This method can be called to remove the `ng-touched` class and set the control to its
  22868. * untouched state (`ng-untouched` class). Upon compilation, a model is set as untouched
  22869. * by default, however this function can be used to restore that state if the model has
  22870. * already been touched by the user.
  22871. */
  22872. this.$setUntouched = function() {
  22873. ctrl.$touched = false;
  22874. ctrl.$untouched = true;
  22875. $animate.setClass($element, UNTOUCHED_CLASS, TOUCHED_CLASS);
  22876. };
  22877. /**
  22878. * @ngdoc method
  22879. * @name ngModel.NgModelController#$setTouched
  22880. *
  22881. * @description
  22882. * Sets the control to its touched state.
  22883. *
  22884. * This method can be called to remove the `ng-untouched` class and set the control to its
  22885. * touched state (`ng-touched` class). A model is considered to be touched when the user has
  22886. * first focused the control element and then shifted focus away from the control (blur event).
  22887. */
  22888. this.$setTouched = function() {
  22889. ctrl.$touched = true;
  22890. ctrl.$untouched = false;
  22891. $animate.setClass($element, TOUCHED_CLASS, UNTOUCHED_CLASS);
  22892. };
  22893. /**
  22894. * @ngdoc method
  22895. * @name ngModel.NgModelController#$rollbackViewValue
  22896. *
  22897. * @description
  22898. * Cancel an update and reset the input element's value to prevent an update to the `$modelValue`,
  22899. * which may be caused by a pending debounced event or because the input is waiting for a some
  22900. * future event.
  22901. *
  22902. * If you have an input that uses `ng-model-options` to set up debounced events or events such
  22903. * as blur you can have a situation where there is a period when the `$viewValue`
  22904. * is out of synch with the ngModel's `$modelValue`.
  22905. *
  22906. * In this case, you can run into difficulties if you try to update the ngModel's `$modelValue`
  22907. * programmatically before these debounced/future events have resolved/occurred, because Angular's
  22908. * dirty checking mechanism is not able to tell whether the model has actually changed or not.
  22909. *
  22910. * The `$rollbackViewValue()` method should be called before programmatically changing the model of an
  22911. * input which may have such events pending. This is important in order to make sure that the
  22912. * input field will be updated with the new model value and any pending operations are cancelled.
  22913. *
  22914. * <example name="ng-model-cancel-update" module="cancel-update-example">
  22915. * <file name="app.js">
  22916. * angular.module('cancel-update-example', [])
  22917. *
  22918. * .controller('CancelUpdateController', ['$scope', function($scope) {
  22919. * $scope.resetWithCancel = function(e) {
  22920. * if (e.keyCode == 27) {
  22921. * $scope.myForm.myInput1.$rollbackViewValue();
  22922. * $scope.myValue = '';
  22923. * }
  22924. * };
  22925. * $scope.resetWithoutCancel = function(e) {
  22926. * if (e.keyCode == 27) {
  22927. * $scope.myValue = '';
  22928. * }
  22929. * };
  22930. * }]);
  22931. * </file>
  22932. * <file name="index.html">
  22933. * <div ng-controller="CancelUpdateController">
  22934. * <p>Try typing something in each input. See that the model only updates when you
  22935. * blur off the input.
  22936. * </p>
  22937. * <p>Now see what happens if you start typing then press the Escape key</p>
  22938. *
  22939. * <form name="myForm" ng-model-options="{ updateOn: 'blur' }">
  22940. * <p id="inputDescription1">With $rollbackViewValue()</p>
  22941. * <input name="myInput1" aria-describedby="inputDescription1" ng-model="myValue"
  22942. * ng-keydown="resetWithCancel($event)"><br/>
  22943. * myValue: "{{ myValue }}"
  22944. *
  22945. * <p id="inputDescription2">Without $rollbackViewValue()</p>
  22946. * <input name="myInput2" aria-describedby="inputDescription2" ng-model="myValue"
  22947. * ng-keydown="resetWithoutCancel($event)"><br/>
  22948. * myValue: "{{ myValue }}"
  22949. * </form>
  22950. * </div>
  22951. * </file>
  22952. * </example>
  22953. */
  22954. this.$rollbackViewValue = function() {
  22955. $timeout.cancel(pendingDebounce);
  22956. ctrl.$viewValue = ctrl.$$lastCommittedViewValue;
  22957. ctrl.$render();
  22958. };
  22959. /**
  22960. * @ngdoc method
  22961. * @name ngModel.NgModelController#$validate
  22962. *
  22963. * @description
  22964. * Runs each of the registered validators (first synchronous validators and then
  22965. * asynchronous validators).
  22966. * If the validity changes to invalid, the model will be set to `undefined`,
  22967. * unless {@link ngModelOptions `ngModelOptions.allowInvalid`} is `true`.
  22968. * If the validity changes to valid, it will set the model to the last available valid
  22969. * `$modelValue`, i.e. either the last parsed value or the last value set from the scope.
  22970. */
  22971. this.$validate = function() {
  22972. // ignore $validate before model is initialized
  22973. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  22974. return;
  22975. }
  22976. var viewValue = ctrl.$$lastCommittedViewValue;
  22977. // Note: we use the $$rawModelValue as $modelValue might have been
  22978. // set to undefined during a view -> model update that found validation
  22979. // errors. We can't parse the view here, since that could change
  22980. // the model although neither viewValue nor the model on the scope changed
  22981. var modelValue = ctrl.$$rawModelValue;
  22982. var prevValid = ctrl.$valid;
  22983. var prevModelValue = ctrl.$modelValue;
  22984. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  22985. ctrl.$$runValidators(modelValue, viewValue, function(allValid) {
  22986. // If there was no change in validity, don't update the model
  22987. // This prevents changing an invalid modelValue to undefined
  22988. if (!allowInvalid && prevValid !== allValid) {
  22989. // Note: Don't check ctrl.$valid here, as we could have
  22990. // external validators (e.g. calculated on the server),
  22991. // that just call $setValidity and need the model value
  22992. // to calculate their validity.
  22993. ctrl.$modelValue = allValid ? modelValue : undefined;
  22994. if (ctrl.$modelValue !== prevModelValue) {
  22995. ctrl.$$writeModelToScope();
  22996. }
  22997. }
  22998. });
  22999. };
  23000. this.$$runValidators = function(modelValue, viewValue, doneCallback) {
  23001. currentValidationRunId++;
  23002. var localValidationRunId = currentValidationRunId;
  23003. // check parser error
  23004. if (!processParseErrors()) {
  23005. validationDone(false);
  23006. return;
  23007. }
  23008. if (!processSyncValidators()) {
  23009. validationDone(false);
  23010. return;
  23011. }
  23012. processAsyncValidators();
  23013. function processParseErrors() {
  23014. var errorKey = ctrl.$$parserName || 'parse';
  23015. if (isUndefined(parserValid)) {
  23016. setValidity(errorKey, null);
  23017. } else {
  23018. if (!parserValid) {
  23019. forEach(ctrl.$validators, function(v, name) {
  23020. setValidity(name, null);
  23021. });
  23022. forEach(ctrl.$asyncValidators, function(v, name) {
  23023. setValidity(name, null);
  23024. });
  23025. }
  23026. // Set the parse error last, to prevent unsetting it, should a $validators key == parserName
  23027. setValidity(errorKey, parserValid);
  23028. return parserValid;
  23029. }
  23030. return true;
  23031. }
  23032. function processSyncValidators() {
  23033. var syncValidatorsValid = true;
  23034. forEach(ctrl.$validators, function(validator, name) {
  23035. var result = validator(modelValue, viewValue);
  23036. syncValidatorsValid = syncValidatorsValid && result;
  23037. setValidity(name, result);
  23038. });
  23039. if (!syncValidatorsValid) {
  23040. forEach(ctrl.$asyncValidators, function(v, name) {
  23041. setValidity(name, null);
  23042. });
  23043. return false;
  23044. }
  23045. return true;
  23046. }
  23047. function processAsyncValidators() {
  23048. var validatorPromises = [];
  23049. var allValid = true;
  23050. forEach(ctrl.$asyncValidators, function(validator, name) {
  23051. var promise = validator(modelValue, viewValue);
  23052. if (!isPromiseLike(promise)) {
  23053. throw ngModelMinErr("$asyncValidators",
  23054. "Expected asynchronous validator to return a promise but got '{0}' instead.", promise);
  23055. }
  23056. setValidity(name, undefined);
  23057. validatorPromises.push(promise.then(function() {
  23058. setValidity(name, true);
  23059. }, function(error) {
  23060. allValid = false;
  23061. setValidity(name, false);
  23062. }));
  23063. });
  23064. if (!validatorPromises.length) {
  23065. validationDone(true);
  23066. } else {
  23067. $q.all(validatorPromises).then(function() {
  23068. validationDone(allValid);
  23069. }, noop);
  23070. }
  23071. }
  23072. function setValidity(name, isValid) {
  23073. if (localValidationRunId === currentValidationRunId) {
  23074. ctrl.$setValidity(name, isValid);
  23075. }
  23076. }
  23077. function validationDone(allValid) {
  23078. if (localValidationRunId === currentValidationRunId) {
  23079. doneCallback(allValid);
  23080. }
  23081. }
  23082. };
  23083. /**
  23084. * @ngdoc method
  23085. * @name ngModel.NgModelController#$commitViewValue
  23086. *
  23087. * @description
  23088. * Commit a pending update to the `$modelValue`.
  23089. *
  23090. * Updates may be pending by a debounced event or because the input is waiting for a some future
  23091. * event defined in `ng-model-options`. this method is rarely needed as `NgModelController`
  23092. * usually handles calling this in response to input events.
  23093. */
  23094. this.$commitViewValue = function() {
  23095. var viewValue = ctrl.$viewValue;
  23096. $timeout.cancel(pendingDebounce);
  23097. // If the view value has not changed then we should just exit, except in the case where there is
  23098. // a native validator on the element. In this case the validation state may have changed even though
  23099. // the viewValue has stayed empty.
  23100. if (ctrl.$$lastCommittedViewValue === viewValue && (viewValue !== '' || !ctrl.$$hasNativeValidators)) {
  23101. return;
  23102. }
  23103. ctrl.$$lastCommittedViewValue = viewValue;
  23104. // change to dirty
  23105. if (ctrl.$pristine) {
  23106. this.$setDirty();
  23107. }
  23108. this.$$parseAndValidate();
  23109. };
  23110. this.$$parseAndValidate = function() {
  23111. var viewValue = ctrl.$$lastCommittedViewValue;
  23112. var modelValue = viewValue;
  23113. parserValid = isUndefined(modelValue) ? undefined : true;
  23114. if (parserValid) {
  23115. for (var i = 0; i < ctrl.$parsers.length; i++) {
  23116. modelValue = ctrl.$parsers[i](modelValue);
  23117. if (isUndefined(modelValue)) {
  23118. parserValid = false;
  23119. break;
  23120. }
  23121. }
  23122. }
  23123. if (isNumber(ctrl.$modelValue) && isNaN(ctrl.$modelValue)) {
  23124. // ctrl.$modelValue has not been touched yet...
  23125. ctrl.$modelValue = ngModelGet($scope);
  23126. }
  23127. var prevModelValue = ctrl.$modelValue;
  23128. var allowInvalid = ctrl.$options && ctrl.$options.allowInvalid;
  23129. ctrl.$$rawModelValue = modelValue;
  23130. if (allowInvalid) {
  23131. ctrl.$modelValue = modelValue;
  23132. writeToModelIfNeeded();
  23133. }
  23134. // Pass the $$lastCommittedViewValue here, because the cached viewValue might be out of date.
  23135. // This can happen if e.g. $setViewValue is called from inside a parser
  23136. ctrl.$$runValidators(modelValue, ctrl.$$lastCommittedViewValue, function(allValid) {
  23137. if (!allowInvalid) {
  23138. // Note: Don't check ctrl.$valid here, as we could have
  23139. // external validators (e.g. calculated on the server),
  23140. // that just call $setValidity and need the model value
  23141. // to calculate their validity.
  23142. ctrl.$modelValue = allValid ? modelValue : undefined;
  23143. writeToModelIfNeeded();
  23144. }
  23145. });
  23146. function writeToModelIfNeeded() {
  23147. if (ctrl.$modelValue !== prevModelValue) {
  23148. ctrl.$$writeModelToScope();
  23149. }
  23150. }
  23151. };
  23152. this.$$writeModelToScope = function() {
  23153. ngModelSet($scope, ctrl.$modelValue);
  23154. forEach(ctrl.$viewChangeListeners, function(listener) {
  23155. try {
  23156. listener();
  23157. } catch (e) {
  23158. $exceptionHandler(e);
  23159. }
  23160. });
  23161. };
  23162. /**
  23163. * @ngdoc method
  23164. * @name ngModel.NgModelController#$setViewValue
  23165. *
  23166. * @description
  23167. * Update the view value.
  23168. *
  23169. * This method should be called when a control wants to change the view value; typically,
  23170. * this is done from within a DOM event handler. For example, the {@link ng.directive:input input}
  23171. * directive calls it when the value of the input changes and {@link ng.directive:select select}
  23172. * calls it when an option is selected.
  23173. *
  23174. * When `$setViewValue` is called, the new `value` will be staged for committing through the `$parsers`
  23175. * and `$validators` pipelines. If there are no special {@link ngModelOptions} specified then the staged
  23176. * value sent directly for processing, finally to be applied to `$modelValue` and then the
  23177. * **expression** specified in the `ng-model` attribute. Lastly, all the registered change listeners,
  23178. * in the `$viewChangeListeners` list, are called.
  23179. *
  23180. * In case the {@link ng.directive:ngModelOptions ngModelOptions} directive is used with `updateOn`
  23181. * and the `default` trigger is not listed, all those actions will remain pending until one of the
  23182. * `updateOn` events is triggered on the DOM element.
  23183. * All these actions will be debounced if the {@link ng.directive:ngModelOptions ngModelOptions}
  23184. * directive is used with a custom debounce for this particular event.
  23185. * Note that a `$digest` is only triggered once the `updateOn` events are fired, or if `debounce`
  23186. * is specified, once the timer runs out.
  23187. *
  23188. * When used with standard inputs, the view value will always be a string (which is in some cases
  23189. * parsed into another type, such as a `Date` object for `input[date]`.)
  23190. * However, custom controls might also pass objects to this method. In this case, we should make
  23191. * a copy of the object before passing it to `$setViewValue`. This is because `ngModel` does not
  23192. * perform a deep watch of objects, it only looks for a change of identity. If you only change
  23193. * the property of the object then ngModel will not realise that the object has changed and
  23194. * will not invoke the `$parsers` and `$validators` pipelines. For this reason, you should
  23195. * not change properties of the copy once it has been passed to `$setViewValue`.
  23196. * Otherwise you may cause the model value on the scope to change incorrectly.
  23197. *
  23198. * <div class="alert alert-info">
  23199. * In any case, the value passed to the method should always reflect the current value
  23200. * of the control. For example, if you are calling `$setViewValue` for an input element,
  23201. * you should pass the input DOM value. Otherwise, the control and the scope model become
  23202. * out of sync. It's also important to note that `$setViewValue` does not call `$render` or change
  23203. * the control's DOM value in any way. If we want to change the control's DOM value
  23204. * programmatically, we should update the `ngModel` scope expression. Its new value will be
  23205. * picked up by the model controller, which will run it through the `$formatters`, `$render` it
  23206. * to update the DOM, and finally call `$validate` on it.
  23207. * </div>
  23208. *
  23209. * @param {*} value value from the view.
  23210. * @param {string} trigger Event that triggered the update.
  23211. */
  23212. this.$setViewValue = function(value, trigger) {
  23213. ctrl.$viewValue = value;
  23214. if (!ctrl.$options || ctrl.$options.updateOnDefault) {
  23215. ctrl.$$debounceViewValueCommit(trigger);
  23216. }
  23217. };
  23218. this.$$debounceViewValueCommit = function(trigger) {
  23219. var debounceDelay = 0,
  23220. options = ctrl.$options,
  23221. debounce;
  23222. if (options && isDefined(options.debounce)) {
  23223. debounce = options.debounce;
  23224. if (isNumber(debounce)) {
  23225. debounceDelay = debounce;
  23226. } else if (isNumber(debounce[trigger])) {
  23227. debounceDelay = debounce[trigger];
  23228. } else if (isNumber(debounce['default'])) {
  23229. debounceDelay = debounce['default'];
  23230. }
  23231. }
  23232. $timeout.cancel(pendingDebounce);
  23233. if (debounceDelay) {
  23234. pendingDebounce = $timeout(function() {
  23235. ctrl.$commitViewValue();
  23236. }, debounceDelay);
  23237. } else if ($rootScope.$$phase) {
  23238. ctrl.$commitViewValue();
  23239. } else {
  23240. $scope.$apply(function() {
  23241. ctrl.$commitViewValue();
  23242. });
  23243. }
  23244. };
  23245. // model -> value
  23246. // Note: we cannot use a normal scope.$watch as we want to detect the following:
  23247. // 1. scope value is 'a'
  23248. // 2. user enters 'b'
  23249. // 3. ng-change kicks in and reverts scope value to 'a'
  23250. // -> scope value did not change since the last digest as
  23251. // ng-change executes in apply phase
  23252. // 4. view should be changed back to 'a'
  23253. $scope.$watch(function ngModelWatch() {
  23254. var modelValue = ngModelGet($scope);
  23255. // if scope model value and ngModel value are out of sync
  23256. // TODO(perf): why not move this to the action fn?
  23257. if (modelValue !== ctrl.$modelValue &&
  23258. // checks for NaN is needed to allow setting the model to NaN when there's an asyncValidator
  23259. (ctrl.$modelValue === ctrl.$modelValue || modelValue === modelValue)
  23260. ) {
  23261. ctrl.$modelValue = ctrl.$$rawModelValue = modelValue;
  23262. parserValid = undefined;
  23263. var formatters = ctrl.$formatters,
  23264. idx = formatters.length;
  23265. var viewValue = modelValue;
  23266. while (idx--) {
  23267. viewValue = formatters[idx](viewValue);
  23268. }
  23269. if (ctrl.$viewValue !== viewValue) {
  23270. ctrl.$viewValue = ctrl.$$lastCommittedViewValue = viewValue;
  23271. ctrl.$render();
  23272. ctrl.$$runValidators(modelValue, viewValue, noop);
  23273. }
  23274. }
  23275. return modelValue;
  23276. });
  23277. }];
  23278. /**
  23279. * @ngdoc directive
  23280. * @name ngModel
  23281. *
  23282. * @element input
  23283. * @priority 1
  23284. *
  23285. * @description
  23286. * The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
  23287. * property on the scope using {@link ngModel.NgModelController NgModelController},
  23288. * which is created and exposed by this directive.
  23289. *
  23290. * `ngModel` is responsible for:
  23291. *
  23292. * - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
  23293. * require.
  23294. * - Providing validation behavior (i.e. required, number, email, url).
  23295. * - Keeping the state of the control (valid/invalid, dirty/pristine, touched/untouched, validation errors).
  23296. * - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`, `ng-touched`, `ng-untouched`) including animations.
  23297. * - Registering the control with its parent {@link ng.directive:form form}.
  23298. *
  23299. * Note: `ngModel` will try to bind to the property given by evaluating the expression on the
  23300. * current scope. If the property doesn't already exist on this scope, it will be created
  23301. * implicitly and added to the scope.
  23302. *
  23303. * For best practices on using `ngModel`, see:
  23304. *
  23305. * - [Understanding Scopes](https://github.com/angular/angular.js/wiki/Understanding-Scopes)
  23306. *
  23307. * For basic examples, how to use `ngModel`, see:
  23308. *
  23309. * - {@link ng.directive:input input}
  23310. * - {@link input[text] text}
  23311. * - {@link input[checkbox] checkbox}
  23312. * - {@link input[radio] radio}
  23313. * - {@link input[number] number}
  23314. * - {@link input[email] email}
  23315. * - {@link input[url] url}
  23316. * - {@link input[date] date}
  23317. * - {@link input[datetime-local] datetime-local}
  23318. * - {@link input[time] time}
  23319. * - {@link input[month] month}
  23320. * - {@link input[week] week}
  23321. * - {@link ng.directive:select select}
  23322. * - {@link ng.directive:textarea textarea}
  23323. *
  23324. * # CSS classes
  23325. * The following CSS classes are added and removed on the associated input/select/textarea element
  23326. * depending on the validity of the model.
  23327. *
  23328. * - `ng-valid`: the model is valid
  23329. * - `ng-invalid`: the model is invalid
  23330. * - `ng-valid-[key]`: for each valid key added by `$setValidity`
  23331. * - `ng-invalid-[key]`: for each invalid key added by `$setValidity`
  23332. * - `ng-pristine`: the control hasn't been interacted with yet
  23333. * - `ng-dirty`: the control has been interacted with
  23334. * - `ng-touched`: the control has been blurred
  23335. * - `ng-untouched`: the control hasn't been blurred
  23336. * - `ng-pending`: any `$asyncValidators` are unfulfilled
  23337. *
  23338. * Keep in mind that ngAnimate can detect each of these classes when added and removed.
  23339. *
  23340. * ## Animation Hooks
  23341. *
  23342. * Animations within models are triggered when any of the associated CSS classes are added and removed
  23343. * on the input element which is attached to the model. These classes are: `.ng-pristine`, `.ng-dirty`,
  23344. * `.ng-invalid` and `.ng-valid` as well as any other validations that are performed on the model itself.
  23345. * The animations that are triggered within ngModel are similar to how they work in ngClass and
  23346. * animations can be hooked into using CSS transitions, keyframes as well as JS animations.
  23347. *
  23348. * The following example shows a simple way to utilize CSS transitions to style an input element
  23349. * that has been rendered as invalid after it has been validated:
  23350. *
  23351. * <pre>
  23352. * //be sure to include ngAnimate as a module to hook into more
  23353. * //advanced animations
  23354. * .my-input {
  23355. * transition:0.5s linear all;
  23356. * background: white;
  23357. * }
  23358. * .my-input.ng-invalid {
  23359. * background: red;
  23360. * color:white;
  23361. * }
  23362. * </pre>
  23363. *
  23364. * @example
  23365. * <example deps="angular-animate.js" animations="true" fixBase="true" module="inputExample">
  23366. <file name="index.html">
  23367. <script>
  23368. angular.module('inputExample', [])
  23369. .controller('ExampleController', ['$scope', function($scope) {
  23370. $scope.val = '1';
  23371. }]);
  23372. </script>
  23373. <style>
  23374. .my-input {
  23375. transition:all linear 0.5s;
  23376. background: transparent;
  23377. }
  23378. .my-input.ng-invalid {
  23379. color:white;
  23380. background: red;
  23381. }
  23382. </style>
  23383. <p id="inputDescription">
  23384. Update input to see transitions when valid/invalid.
  23385. Integer is a valid value.
  23386. </p>
  23387. <form name="testForm" ng-controller="ExampleController">
  23388. <input ng-model="val" ng-pattern="/^\d+$/" name="anim" class="my-input"
  23389. aria-describedby="inputDescription" />
  23390. </form>
  23391. </file>
  23392. * </example>
  23393. *
  23394. * ## Binding to a getter/setter
  23395. *
  23396. * Sometimes it's helpful to bind `ngModel` to a getter/setter function. A getter/setter is a
  23397. * function that returns a representation of the model when called with zero arguments, and sets
  23398. * the internal state of a model when called with an argument. It's sometimes useful to use this
  23399. * for models that have an internal representation that's different from what the model exposes
  23400. * to the view.
  23401. *
  23402. * <div class="alert alert-success">
  23403. * **Best Practice:** It's best to keep getters fast because Angular is likely to call them more
  23404. * frequently than other parts of your code.
  23405. * </div>
  23406. *
  23407. * You use this behavior by adding `ng-model-options="{ getterSetter: true }"` to an element that
  23408. * has `ng-model` attached to it. You can also add `ng-model-options="{ getterSetter: true }"` to
  23409. * a `<form>`, which will enable this behavior for all `<input>`s within it. See
  23410. * {@link ng.directive:ngModelOptions `ngModelOptions`} for more.
  23411. *
  23412. * The following example shows how to use `ngModel` with a getter/setter:
  23413. *
  23414. * @example
  23415. * <example name="ngModel-getter-setter" module="getterSetterExample">
  23416. <file name="index.html">
  23417. <div ng-controller="ExampleController">
  23418. <form name="userForm">
  23419. <label>Name:
  23420. <input type="text" name="userName"
  23421. ng-model="user.name"
  23422. ng-model-options="{ getterSetter: true }" />
  23423. </label>
  23424. </form>
  23425. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23426. </div>
  23427. </file>
  23428. <file name="app.js">
  23429. angular.module('getterSetterExample', [])
  23430. .controller('ExampleController', ['$scope', function($scope) {
  23431. var _name = 'Brian';
  23432. $scope.user = {
  23433. name: function(newName) {
  23434. // Note that newName can be undefined for two reasons:
  23435. // 1. Because it is called as a getter and thus called with no arguments
  23436. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23437. // input is invalid
  23438. return arguments.length ? (_name = newName) : _name;
  23439. }
  23440. };
  23441. }]);
  23442. </file>
  23443. * </example>
  23444. */
  23445. var ngModelDirective = ['$rootScope', function($rootScope) {
  23446. return {
  23447. restrict: 'A',
  23448. require: ['ngModel', '^?form', '^?ngModelOptions'],
  23449. controller: NgModelController,
  23450. // Prelink needs to run before any input directive
  23451. // so that we can set the NgModelOptions in NgModelController
  23452. // before anyone else uses it.
  23453. priority: 1,
  23454. compile: function ngModelCompile(element) {
  23455. // Setup initial state of the control
  23456. element.addClass(PRISTINE_CLASS).addClass(UNTOUCHED_CLASS).addClass(VALID_CLASS);
  23457. return {
  23458. pre: function ngModelPreLink(scope, element, attr, ctrls) {
  23459. var modelCtrl = ctrls[0],
  23460. formCtrl = ctrls[1] || modelCtrl.$$parentForm;
  23461. modelCtrl.$$setOptions(ctrls[2] && ctrls[2].$options);
  23462. // notify others, especially parent forms
  23463. formCtrl.$addControl(modelCtrl);
  23464. attr.$observe('name', function(newValue) {
  23465. if (modelCtrl.$name !== newValue) {
  23466. modelCtrl.$$parentForm.$$renameControl(modelCtrl, newValue);
  23467. }
  23468. });
  23469. scope.$on('$destroy', function() {
  23470. modelCtrl.$$parentForm.$removeControl(modelCtrl);
  23471. });
  23472. },
  23473. post: function ngModelPostLink(scope, element, attr, ctrls) {
  23474. var modelCtrl = ctrls[0];
  23475. if (modelCtrl.$options && modelCtrl.$options.updateOn) {
  23476. element.on(modelCtrl.$options.updateOn, function(ev) {
  23477. modelCtrl.$$debounceViewValueCommit(ev && ev.type);
  23478. });
  23479. }
  23480. element.on('blur', function(ev) {
  23481. if (modelCtrl.$touched) return;
  23482. if ($rootScope.$$phase) {
  23483. scope.$evalAsync(modelCtrl.$setTouched);
  23484. } else {
  23485. scope.$apply(modelCtrl.$setTouched);
  23486. }
  23487. });
  23488. }
  23489. };
  23490. }
  23491. };
  23492. }];
  23493. var DEFAULT_REGEXP = /(\s+|^)default(\s+|$)/;
  23494. /**
  23495. * @ngdoc directive
  23496. * @name ngModelOptions
  23497. *
  23498. * @description
  23499. * Allows tuning how model updates are done. Using `ngModelOptions` you can specify a custom list of
  23500. * events that will trigger a model update and/or a debouncing delay so that the actual update only
  23501. * takes place when a timer expires; this timer will be reset after another change takes place.
  23502. *
  23503. * Given the nature of `ngModelOptions`, the value displayed inside input fields in the view might
  23504. * be different from the value in the actual model. This means that if you update the model you
  23505. * should also invoke {@link ngModel.NgModelController `$rollbackViewValue`} on the relevant input field in
  23506. * order to make sure it is synchronized with the model and that any debounced action is canceled.
  23507. *
  23508. * The easiest way to reference the control's {@link ngModel.NgModelController `$rollbackViewValue`}
  23509. * method is by making sure the input is placed inside a form that has a `name` attribute. This is
  23510. * important because `form` controllers are published to the related scope under the name in their
  23511. * `name` attribute.
  23512. *
  23513. * Any pending changes will take place immediately when an enclosing form is submitted via the
  23514. * `submit` event. Note that `ngClick` events will occur before the model is updated. Use `ngSubmit`
  23515. * to have access to the updated model.
  23516. *
  23517. * `ngModelOptions` has an effect on the element it's declared on and its descendants.
  23518. *
  23519. * @param {Object} ngModelOptions options to apply to the current model. Valid keys are:
  23520. * - `updateOn`: string specifying which event should the input be bound to. You can set several
  23521. * events using an space delimited list. There is a special event called `default` that
  23522. * matches the default events belonging of the control.
  23523. * - `debounce`: integer value which contains the debounce model update value in milliseconds. A
  23524. * value of 0 triggers an immediate update. If an object is supplied instead, you can specify a
  23525. * custom value for each event. For example:
  23526. * `ng-model-options="{ updateOn: 'default blur', debounce: { 'default': 500, 'blur': 0 } }"`
  23527. * - `allowInvalid`: boolean value which indicates that the model can be set with values that did
  23528. * not validate correctly instead of the default behavior of setting the model to undefined.
  23529. * - `getterSetter`: boolean value which determines whether or not to treat functions bound to
  23530. `ngModel` as getters/setters.
  23531. * - `timezone`: Defines the timezone to be used to read/write the `Date` instance in the model for
  23532. * `<input type="date">`, `<input type="time">`, ... . It understands UTC/GMT and the
  23533. * continental US time zone abbreviations, but for general use, use a time zone offset, for
  23534. * example, `'+0430'` (4 hours, 30 minutes east of the Greenwich meridian)
  23535. * If not specified, the timezone of the browser will be used.
  23536. *
  23537. * @example
  23538. The following example shows how to override immediate updates. Changes on the inputs within the
  23539. form will update the model only when the control loses focus (blur event). If `escape` key is
  23540. pressed while the input field is focused, the value is reset to the value in the current model.
  23541. <example name="ngModelOptions-directive-blur" module="optionsExample">
  23542. <file name="index.html">
  23543. <div ng-controller="ExampleController">
  23544. <form name="userForm">
  23545. <label>Name:
  23546. <input type="text" name="userName"
  23547. ng-model="user.name"
  23548. ng-model-options="{ updateOn: 'blur' }"
  23549. ng-keyup="cancel($event)" />
  23550. </label><br />
  23551. <label>Other data:
  23552. <input type="text" ng-model="user.data" />
  23553. </label><br />
  23554. </form>
  23555. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23556. <pre>user.data = <span ng-bind="user.data"></span></pre>
  23557. </div>
  23558. </file>
  23559. <file name="app.js">
  23560. angular.module('optionsExample', [])
  23561. .controller('ExampleController', ['$scope', function($scope) {
  23562. $scope.user = { name: 'John', data: '' };
  23563. $scope.cancel = function(e) {
  23564. if (e.keyCode == 27) {
  23565. $scope.userForm.userName.$rollbackViewValue();
  23566. }
  23567. };
  23568. }]);
  23569. </file>
  23570. <file name="protractor.js" type="protractor">
  23571. var model = element(by.binding('user.name'));
  23572. var input = element(by.model('user.name'));
  23573. var other = element(by.model('user.data'));
  23574. it('should allow custom events', function() {
  23575. input.sendKeys(' Doe');
  23576. input.click();
  23577. expect(model.getText()).toEqual('John');
  23578. other.click();
  23579. expect(model.getText()).toEqual('John Doe');
  23580. });
  23581. it('should $rollbackViewValue when model changes', function() {
  23582. input.sendKeys(' Doe');
  23583. expect(input.getAttribute('value')).toEqual('John Doe');
  23584. input.sendKeys(protractor.Key.ESCAPE);
  23585. expect(input.getAttribute('value')).toEqual('John');
  23586. other.click();
  23587. expect(model.getText()).toEqual('John');
  23588. });
  23589. </file>
  23590. </example>
  23591. This one shows how to debounce model changes. Model will be updated only 1 sec after last change.
  23592. If the `Clear` button is pressed, any debounced action is canceled and the value becomes empty.
  23593. <example name="ngModelOptions-directive-debounce" module="optionsExample">
  23594. <file name="index.html">
  23595. <div ng-controller="ExampleController">
  23596. <form name="userForm">
  23597. <label>Name:
  23598. <input type="text" name="userName"
  23599. ng-model="user.name"
  23600. ng-model-options="{ debounce: 1000 }" />
  23601. </label>
  23602. <button ng-click="userForm.userName.$rollbackViewValue(); user.name=''">Clear</button>
  23603. <br />
  23604. </form>
  23605. <pre>user.name = <span ng-bind="user.name"></span></pre>
  23606. </div>
  23607. </file>
  23608. <file name="app.js">
  23609. angular.module('optionsExample', [])
  23610. .controller('ExampleController', ['$scope', function($scope) {
  23611. $scope.user = { name: 'Igor' };
  23612. }]);
  23613. </file>
  23614. </example>
  23615. This one shows how to bind to getter/setters:
  23616. <example name="ngModelOptions-directive-getter-setter" module="getterSetterExample">
  23617. <file name="index.html">
  23618. <div ng-controller="ExampleController">
  23619. <form name="userForm">
  23620. <label>Name:
  23621. <input type="text" name="userName"
  23622. ng-model="user.name"
  23623. ng-model-options="{ getterSetter: true }" />
  23624. </label>
  23625. </form>
  23626. <pre>user.name = <span ng-bind="user.name()"></span></pre>
  23627. </div>
  23628. </file>
  23629. <file name="app.js">
  23630. angular.module('getterSetterExample', [])
  23631. .controller('ExampleController', ['$scope', function($scope) {
  23632. var _name = 'Brian';
  23633. $scope.user = {
  23634. name: function(newName) {
  23635. // Note that newName can be undefined for two reasons:
  23636. // 1. Because it is called as a getter and thus called with no arguments
  23637. // 2. Because the property should actually be set to undefined. This happens e.g. if the
  23638. // input is invalid
  23639. return arguments.length ? (_name = newName) : _name;
  23640. }
  23641. };
  23642. }]);
  23643. </file>
  23644. </example>
  23645. */
  23646. var ngModelOptionsDirective = function() {
  23647. return {
  23648. restrict: 'A',
  23649. controller: ['$scope', '$attrs', function($scope, $attrs) {
  23650. var that = this;
  23651. this.$options = copy($scope.$eval($attrs.ngModelOptions));
  23652. // Allow adding/overriding bound events
  23653. if (isDefined(this.$options.updateOn)) {
  23654. this.$options.updateOnDefault = false;
  23655. // extract "default" pseudo-event from list of events that can trigger a model update
  23656. this.$options.updateOn = trim(this.$options.updateOn.replace(DEFAULT_REGEXP, function() {
  23657. that.$options.updateOnDefault = true;
  23658. return ' ';
  23659. }));
  23660. } else {
  23661. this.$options.updateOnDefault = true;
  23662. }
  23663. }]
  23664. };
  23665. };
  23666. // helper methods
  23667. function addSetValidityMethod(context) {
  23668. var ctrl = context.ctrl,
  23669. $element = context.$element,
  23670. classCache = {},
  23671. set = context.set,
  23672. unset = context.unset,
  23673. $animate = context.$animate;
  23674. classCache[INVALID_CLASS] = !(classCache[VALID_CLASS] = $element.hasClass(VALID_CLASS));
  23675. ctrl.$setValidity = setValidity;
  23676. function setValidity(validationErrorKey, state, controller) {
  23677. if (isUndefined(state)) {
  23678. createAndSet('$pending', validationErrorKey, controller);
  23679. } else {
  23680. unsetAndCleanup('$pending', validationErrorKey, controller);
  23681. }
  23682. if (!isBoolean(state)) {
  23683. unset(ctrl.$error, validationErrorKey, controller);
  23684. unset(ctrl.$$success, validationErrorKey, controller);
  23685. } else {
  23686. if (state) {
  23687. unset(ctrl.$error, validationErrorKey, controller);
  23688. set(ctrl.$$success, validationErrorKey, controller);
  23689. } else {
  23690. set(ctrl.$error, validationErrorKey, controller);
  23691. unset(ctrl.$$success, validationErrorKey, controller);
  23692. }
  23693. }
  23694. if (ctrl.$pending) {
  23695. cachedToggleClass(PENDING_CLASS, true);
  23696. ctrl.$valid = ctrl.$invalid = undefined;
  23697. toggleValidationCss('', null);
  23698. } else {
  23699. cachedToggleClass(PENDING_CLASS, false);
  23700. ctrl.$valid = isObjectEmpty(ctrl.$error);
  23701. ctrl.$invalid = !ctrl.$valid;
  23702. toggleValidationCss('', ctrl.$valid);
  23703. }
  23704. // re-read the state as the set/unset methods could have
  23705. // combined state in ctrl.$error[validationError] (used for forms),
  23706. // where setting/unsetting only increments/decrements the value,
  23707. // and does not replace it.
  23708. var combinedState;
  23709. if (ctrl.$pending && ctrl.$pending[validationErrorKey]) {
  23710. combinedState = undefined;
  23711. } else if (ctrl.$error[validationErrorKey]) {
  23712. combinedState = false;
  23713. } else if (ctrl.$$success[validationErrorKey]) {
  23714. combinedState = true;
  23715. } else {
  23716. combinedState = null;
  23717. }
  23718. toggleValidationCss(validationErrorKey, combinedState);
  23719. ctrl.$$parentForm.$setValidity(validationErrorKey, combinedState, ctrl);
  23720. }
  23721. function createAndSet(name, value, controller) {
  23722. if (!ctrl[name]) {
  23723. ctrl[name] = {};
  23724. }
  23725. set(ctrl[name], value, controller);
  23726. }
  23727. function unsetAndCleanup(name, value, controller) {
  23728. if (ctrl[name]) {
  23729. unset(ctrl[name], value, controller);
  23730. }
  23731. if (isObjectEmpty(ctrl[name])) {
  23732. ctrl[name] = undefined;
  23733. }
  23734. }
  23735. function cachedToggleClass(className, switchValue) {
  23736. if (switchValue && !classCache[className]) {
  23737. $animate.addClass($element, className);
  23738. classCache[className] = true;
  23739. } else if (!switchValue && classCache[className]) {
  23740. $animate.removeClass($element, className);
  23741. classCache[className] = false;
  23742. }
  23743. }
  23744. function toggleValidationCss(validationErrorKey, isValid) {
  23745. validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
  23746. cachedToggleClass(VALID_CLASS + validationErrorKey, isValid === true);
  23747. cachedToggleClass(INVALID_CLASS + validationErrorKey, isValid === false);
  23748. }
  23749. }
  23750. function isObjectEmpty(obj) {
  23751. if (obj) {
  23752. for (var prop in obj) {
  23753. if (obj.hasOwnProperty(prop)) {
  23754. return false;
  23755. }
  23756. }
  23757. }
  23758. return true;
  23759. }
  23760. /**
  23761. * @ngdoc directive
  23762. * @name ngNonBindable
  23763. * @restrict AC
  23764. * @priority 1000
  23765. *
  23766. * @description
  23767. * The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
  23768. * DOM element. This is useful if the element contains what appears to be Angular directives and
  23769. * bindings but which should be ignored by Angular. This could be the case if you have a site that
  23770. * displays snippets of code, for instance.
  23771. *
  23772. * @element ANY
  23773. *
  23774. * @example
  23775. * In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
  23776. * but the one wrapped in `ngNonBindable` is left alone.
  23777. *
  23778. * @example
  23779. <example>
  23780. <file name="index.html">
  23781. <div>Normal: {{1 + 2}}</div>
  23782. <div ng-non-bindable>Ignored: {{1 + 2}}</div>
  23783. </file>
  23784. <file name="protractor.js" type="protractor">
  23785. it('should check ng-non-bindable', function() {
  23786. expect(element(by.binding('1 + 2')).getText()).toContain('3');
  23787. expect(element.all(by.css('div')).last().getText()).toMatch(/1 \+ 2/);
  23788. });
  23789. </file>
  23790. </example>
  23791. */
  23792. var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
  23793. /* global jqLiteRemove */
  23794. var ngOptionsMinErr = minErr('ngOptions');
  23795. /**
  23796. * @ngdoc directive
  23797. * @name ngOptions
  23798. * @restrict A
  23799. *
  23800. * @description
  23801. *
  23802. * The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
  23803. * elements for the `<select>` element using the array or object obtained by evaluating the
  23804. * `ngOptions` comprehension expression.
  23805. *
  23806. * In many cases, `ngRepeat` can be used on `<option>` elements instead of `ngOptions` to achieve a
  23807. * similar result. However, `ngOptions` provides some benefits such as reducing memory and
  23808. * increasing speed by not creating a new scope for each repeated instance, as well as providing
  23809. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  23810. * comprehension expression. `ngOptions` should be used when the `<select>` model needs to be bound
  23811. * to a non-string value. This is because an option element can only be bound to string values at
  23812. * present.
  23813. *
  23814. * When an item in the `<select>` menu is selected, the array element or object property
  23815. * represented by the selected option will be bound to the model identified by the `ngModel`
  23816. * directive.
  23817. *
  23818. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  23819. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  23820. * option. See example below for demonstration.
  23821. *
  23822. * ## Complex Models (objects or collections)
  23823. *
  23824. * By default, `ngModel` watches the model by reference, not value. This is important to know when
  23825. * binding the select to a model that is an object or a collection.
  23826. *
  23827. * One issue occurs if you want to preselect an option. For example, if you set
  23828. * the model to an object that is equal to an object in your collection, `ngOptions` won't be able to set the selection,
  23829. * because the objects are not identical. So by default, you should always reference the item in your collection
  23830. * for preselections, e.g.: `$scope.selected = $scope.collection[3]`.
  23831. *
  23832. * Another solution is to use a `track by` clause, because then `ngOptions` will track the identity
  23833. * of the item not by reference, but by the result of the `track by` expression. For example, if your
  23834. * collection items have an id property, you would `track by item.id`.
  23835. *
  23836. * A different issue with objects or collections is that ngModel won't detect if an object property or
  23837. * a collection item changes. For that reason, `ngOptions` additionally watches the model using
  23838. * `$watchCollection`, when the expression contains a `track by` clause or the the select has the `multiple` attribute.
  23839. * This allows ngOptions to trigger a re-rendering of the options even if the actual object/collection
  23840. * has not changed identity, but only a property on the object or an item in the collection changes.
  23841. *
  23842. * Note that `$watchCollection` does a shallow comparison of the properties of the object (or the items in the collection
  23843. * if the model is an array). This means that changing a property deeper than the first level inside the
  23844. * object/collection will not trigger a re-rendering.
  23845. *
  23846. * ## `select` **`as`**
  23847. *
  23848. * Using `select` **`as`** will bind the result of the `select` expression to the model, but
  23849. * the value of the `<select>` and `<option>` html elements will be either the index (for array data sources)
  23850. * or property name (for object data sources) of the value within the collection. If a **`track by`** expression
  23851. * is used, the result of that expression will be set as the value of the `option` and `select` elements.
  23852. *
  23853. *
  23854. * ### `select` **`as`** and **`track by`**
  23855. *
  23856. * <div class="alert alert-warning">
  23857. * Be careful when using `select` **`as`** and **`track by`** in the same expression.
  23858. * </div>
  23859. *
  23860. * Given this array of items on the $scope:
  23861. *
  23862. * ```js
  23863. * $scope.items = [{
  23864. * id: 1,
  23865. * label: 'aLabel',
  23866. * subItem: { name: 'aSubItem' }
  23867. * }, {
  23868. * id: 2,
  23869. * label: 'bLabel',
  23870. * subItem: { name: 'bSubItem' }
  23871. * }];
  23872. * ```
  23873. *
  23874. * This will work:
  23875. *
  23876. * ```html
  23877. * <select ng-options="item as item.label for item in items track by item.id" ng-model="selected"></select>
  23878. * ```
  23879. * ```js
  23880. * $scope.selected = $scope.items[0];
  23881. * ```
  23882. *
  23883. * but this will not work:
  23884. *
  23885. * ```html
  23886. * <select ng-options="item.subItem as item.label for item in items track by item.id" ng-model="selected"></select>
  23887. * ```
  23888. * ```js
  23889. * $scope.selected = $scope.items[0].subItem;
  23890. * ```
  23891. *
  23892. * In both examples, the **`track by`** expression is applied successfully to each `item` in the
  23893. * `items` array. Because the selected option has been set programmatically in the controller, the
  23894. * **`track by`** expression is also applied to the `ngModel` value. In the first example, the
  23895. * `ngModel` value is `items[0]` and the **`track by`** expression evaluates to `items[0].id` with
  23896. * no issue. In the second example, the `ngModel` value is `items[0].subItem` and the **`track by`**
  23897. * expression evaluates to `items[0].subItem.id` (which is undefined). As a result, the model value
  23898. * is not matched against any `<option>` and the `<select>` appears as having no selected value.
  23899. *
  23900. *
  23901. * @param {string} ngModel Assignable angular expression to data-bind to.
  23902. * @param {string=} name Property name of the form under which the control is published.
  23903. * @param {string=} required The control is considered valid only if value is entered.
  23904. * @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
  23905. * the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
  23906. * `required` when you want to data-bind to the `required` attribute.
  23907. * @param {comprehension_expression=} ngOptions in one of the following forms:
  23908. *
  23909. * * for array data sources:
  23910. * * `label` **`for`** `value` **`in`** `array`
  23911. * * `select` **`as`** `label` **`for`** `value` **`in`** `array`
  23912. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
  23913. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array`
  23914. * * `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23915. * * `label` **`disable when`** `disable` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
  23916. * * `label` **`for`** `value` **`in`** `array` | orderBy:`orderexpr` **`track by`** `trackexpr`
  23917. * (for including a filter with `track by`)
  23918. * * for object data sources:
  23919. * * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23920. * * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
  23921. * * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23922. * * `label` **`disable when`** `disable` **`for (`**`key`**`,`** `value`**`) in`** `object`
  23923. * * `select` **`as`** `label` **`group by`** `group`
  23924. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23925. * * `select` **`as`** `label` **`disable when`** `disable`
  23926. * **`for` `(`**`key`**`,`** `value`**`) in`** `object`
  23927. *
  23928. * Where:
  23929. *
  23930. * * `array` / `object`: an expression which evaluates to an array / object to iterate over.
  23931. * * `value`: local variable which will refer to each item in the `array` or each property value
  23932. * of `object` during iteration.
  23933. * * `key`: local variable which will refer to a property name in `object` during iteration.
  23934. * * `label`: The result of this expression will be the label for `<option>` element. The
  23935. * `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
  23936. * * `select`: The result of this expression will be bound to the model of the parent `<select>`
  23937. * element. If not specified, `select` expression will default to `value`.
  23938. * * `group`: The result of this expression will be used to group options using the `<optgroup>`
  23939. * DOM element.
  23940. * * `disable`: The result of this expression will be used to disable the rendered `<option>`
  23941. * element. Return `true` to disable.
  23942. * * `trackexpr`: Used when working with an array of objects. The result of this expression will be
  23943. * used to identify the objects in the array. The `trackexpr` will most likely refer to the
  23944. * `value` variable (e.g. `value.propertyName`). With this the selection is preserved
  23945. * even when the options are recreated (e.g. reloaded from the server).
  23946. *
  23947. * @example
  23948. <example module="selectExample">
  23949. <file name="index.html">
  23950. <script>
  23951. angular.module('selectExample', [])
  23952. .controller('ExampleController', ['$scope', function($scope) {
  23953. $scope.colors = [
  23954. {name:'black', shade:'dark'},
  23955. {name:'white', shade:'light', notAnOption: true},
  23956. {name:'red', shade:'dark'},
  23957. {name:'blue', shade:'dark', notAnOption: true},
  23958. {name:'yellow', shade:'light', notAnOption: false}
  23959. ];
  23960. $scope.myColor = $scope.colors[2]; // red
  23961. }]);
  23962. </script>
  23963. <div ng-controller="ExampleController">
  23964. <ul>
  23965. <li ng-repeat="color in colors">
  23966. <label>Name: <input ng-model="color.name"></label>
  23967. <label><input type="checkbox" ng-model="color.notAnOption"> Disabled?</label>
  23968. <button ng-click="colors.splice($index, 1)" aria-label="Remove">X</button>
  23969. </li>
  23970. <li>
  23971. <button ng-click="colors.push({})">add</button>
  23972. </li>
  23973. </ul>
  23974. <hr/>
  23975. <label>Color (null not allowed):
  23976. <select ng-model="myColor" ng-options="color.name for color in colors"></select>
  23977. </label><br/>
  23978. <label>Color (null allowed):
  23979. <span class="nullable">
  23980. <select ng-model="myColor" ng-options="color.name for color in colors">
  23981. <option value="">-- choose color --</option>
  23982. </select>
  23983. </span></label><br/>
  23984. <label>Color grouped by shade:
  23985. <select ng-model="myColor" ng-options="color.name group by color.shade for color in colors">
  23986. </select>
  23987. </label><br/>
  23988. <label>Color grouped by shade, with some disabled:
  23989. <select ng-model="myColor"
  23990. ng-options="color.name group by color.shade disable when color.notAnOption for color in colors">
  23991. </select>
  23992. </label><br/>
  23993. Select <button ng-click="myColor = { name:'not in list', shade: 'other' }">bogus</button>.
  23994. <br/>
  23995. <hr/>
  23996. Currently selected: {{ {selected_color:myColor} }}
  23997. <div style="border:solid 1px black; height:20px"
  23998. ng-style="{'background-color':myColor.name}">
  23999. </div>
  24000. </div>
  24001. </file>
  24002. <file name="protractor.js" type="protractor">
  24003. it('should check ng-options', function() {
  24004. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('red');
  24005. element.all(by.model('myColor')).first().click();
  24006. element.all(by.css('select[ng-model="myColor"] option')).first().click();
  24007. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('black');
  24008. element(by.css('.nullable select[ng-model="myColor"]')).click();
  24009. element.all(by.css('.nullable select[ng-model="myColor"] option')).first().click();
  24010. expect(element(by.binding('{selected_color:myColor}')).getText()).toMatch('null');
  24011. });
  24012. </file>
  24013. </example>
  24014. */
  24015. // jshint maxlen: false
  24016. // //00001111111111000000000002222222222000000000000000000000333333333300000000000000000000000004444444444400000000000005555555555555550000000006666666666666660000000777777777777777000000000000000888888888800000000000000000009999999999
  24017. var NG_OPTIONS_REGEXP = /^\s*([\s\S]+?)(?:\s+as\s+([\s\S]+?))?(?:\s+group\s+by\s+([\s\S]+?))?(?:\s+disable\s+when\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]+?))?$/;
  24018. // 1: value expression (valueFn)
  24019. // 2: label expression (displayFn)
  24020. // 3: group by expression (groupByFn)
  24021. // 4: disable when expression (disableWhenFn)
  24022. // 5: array item variable name
  24023. // 6: object item key variable name
  24024. // 7: object item value variable name
  24025. // 8: collection expression
  24026. // 9: track by expression
  24027. // jshint maxlen: 100
  24028. var ngOptionsDirective = ['$compile', '$parse', function($compile, $parse) {
  24029. function parseOptionsExpression(optionsExp, selectElement, scope) {
  24030. var match = optionsExp.match(NG_OPTIONS_REGEXP);
  24031. if (!(match)) {
  24032. throw ngOptionsMinErr('iexp',
  24033. "Expected expression in form of " +
  24034. "'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
  24035. " but got '{0}'. Element: {1}",
  24036. optionsExp, startingTag(selectElement));
  24037. }
  24038. // Extract the parts from the ngOptions expression
  24039. // The variable name for the value of the item in the collection
  24040. var valueName = match[5] || match[7];
  24041. // The variable name for the key of the item in the collection
  24042. var keyName = match[6];
  24043. // An expression that generates the viewValue for an option if there is a label expression
  24044. var selectAs = / as /.test(match[0]) && match[1];
  24045. // An expression that is used to track the id of each object in the options collection
  24046. var trackBy = match[9];
  24047. // An expression that generates the viewValue for an option if there is no label expression
  24048. var valueFn = $parse(match[2] ? match[1] : valueName);
  24049. var selectAsFn = selectAs && $parse(selectAs);
  24050. var viewValueFn = selectAsFn || valueFn;
  24051. var trackByFn = trackBy && $parse(trackBy);
  24052. // Get the value by which we are going to track the option
  24053. // if we have a trackFn then use that (passing scope and locals)
  24054. // otherwise just hash the given viewValue
  24055. var getTrackByValueFn = trackBy ?
  24056. function(value, locals) { return trackByFn(scope, locals); } :
  24057. function getHashOfValue(value) { return hashKey(value); };
  24058. var getTrackByValue = function(value, key) {
  24059. return getTrackByValueFn(value, getLocals(value, key));
  24060. };
  24061. var displayFn = $parse(match[2] || match[1]);
  24062. var groupByFn = $parse(match[3] || '');
  24063. var disableWhenFn = $parse(match[4] || '');
  24064. var valuesFn = $parse(match[8]);
  24065. var locals = {};
  24066. var getLocals = keyName ? function(value, key) {
  24067. locals[keyName] = key;
  24068. locals[valueName] = value;
  24069. return locals;
  24070. } : function(value) {
  24071. locals[valueName] = value;
  24072. return locals;
  24073. };
  24074. function Option(selectValue, viewValue, label, group, disabled) {
  24075. this.selectValue = selectValue;
  24076. this.viewValue = viewValue;
  24077. this.label = label;
  24078. this.group = group;
  24079. this.disabled = disabled;
  24080. }
  24081. function getOptionValuesKeys(optionValues) {
  24082. var optionValuesKeys;
  24083. if (!keyName && isArrayLike(optionValues)) {
  24084. optionValuesKeys = optionValues;
  24085. } else {
  24086. // if object, extract keys, in enumeration order, unsorted
  24087. optionValuesKeys = [];
  24088. for (var itemKey in optionValues) {
  24089. if (optionValues.hasOwnProperty(itemKey) && itemKey.charAt(0) !== '$') {
  24090. optionValuesKeys.push(itemKey);
  24091. }
  24092. }
  24093. }
  24094. return optionValuesKeys;
  24095. }
  24096. return {
  24097. trackBy: trackBy,
  24098. getTrackByValue: getTrackByValue,
  24099. getWatchables: $parse(valuesFn, function(optionValues) {
  24100. // Create a collection of things that we would like to watch (watchedArray)
  24101. // so that they can all be watched using a single $watchCollection
  24102. // that only runs the handler once if anything changes
  24103. var watchedArray = [];
  24104. optionValues = optionValues || [];
  24105. var optionValuesKeys = getOptionValuesKeys(optionValues);
  24106. var optionValuesLength = optionValuesKeys.length;
  24107. for (var index = 0; index < optionValuesLength; index++) {
  24108. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  24109. var value = optionValues[key];
  24110. var locals = getLocals(optionValues[key], key);
  24111. var selectValue = getTrackByValueFn(optionValues[key], locals);
  24112. watchedArray.push(selectValue);
  24113. // Only need to watch the displayFn if there is a specific label expression
  24114. if (match[2] || match[1]) {
  24115. var label = displayFn(scope, locals);
  24116. watchedArray.push(label);
  24117. }
  24118. // Only need to watch the disableWhenFn if there is a specific disable expression
  24119. if (match[4]) {
  24120. var disableWhen = disableWhenFn(scope, locals);
  24121. watchedArray.push(disableWhen);
  24122. }
  24123. }
  24124. return watchedArray;
  24125. }),
  24126. getOptions: function() {
  24127. var optionItems = [];
  24128. var selectValueMap = {};
  24129. // The option values were already computed in the `getWatchables` fn,
  24130. // which must have been called to trigger `getOptions`
  24131. var optionValues = valuesFn(scope) || [];
  24132. var optionValuesKeys = getOptionValuesKeys(optionValues);
  24133. var optionValuesLength = optionValuesKeys.length;
  24134. for (var index = 0; index < optionValuesLength; index++) {
  24135. var key = (optionValues === optionValuesKeys) ? index : optionValuesKeys[index];
  24136. var value = optionValues[key];
  24137. var locals = getLocals(value, key);
  24138. var viewValue = viewValueFn(scope, locals);
  24139. var selectValue = getTrackByValueFn(viewValue, locals);
  24140. var label = displayFn(scope, locals);
  24141. var group = groupByFn(scope, locals);
  24142. var disabled = disableWhenFn(scope, locals);
  24143. var optionItem = new Option(selectValue, viewValue, label, group, disabled);
  24144. optionItems.push(optionItem);
  24145. selectValueMap[selectValue] = optionItem;
  24146. }
  24147. return {
  24148. items: optionItems,
  24149. selectValueMap: selectValueMap,
  24150. getOptionFromViewValue: function(value) {
  24151. return selectValueMap[getTrackByValue(value)];
  24152. },
  24153. getViewValueFromOption: function(option) {
  24154. // If the viewValue could be an object that may be mutated by the application,
  24155. // we need to make a copy and not return the reference to the value on the option.
  24156. return trackBy ? angular.copy(option.viewValue) : option.viewValue;
  24157. }
  24158. };
  24159. }
  24160. };
  24161. }
  24162. // we can't just jqLite('<option>') since jqLite is not smart enough
  24163. // to create it in <select> and IE barfs otherwise.
  24164. var optionTemplate = document.createElement('option'),
  24165. optGroupTemplate = document.createElement('optgroup');
  24166. function ngOptionsPostLink(scope, selectElement, attr, ctrls) {
  24167. // if ngModel is not defined, we don't need to do anything
  24168. var ngModelCtrl = ctrls[1];
  24169. if (!ngModelCtrl) return;
  24170. var selectCtrl = ctrls[0];
  24171. var multiple = attr.multiple;
  24172. // The emptyOption allows the application developer to provide their own custom "empty"
  24173. // option when the viewValue does not match any of the option values.
  24174. var emptyOption;
  24175. for (var i = 0, children = selectElement.children(), ii = children.length; i < ii; i++) {
  24176. if (children[i].value === '') {
  24177. emptyOption = children.eq(i);
  24178. break;
  24179. }
  24180. }
  24181. var providedEmptyOption = !!emptyOption;
  24182. var unknownOption = jqLite(optionTemplate.cloneNode(false));
  24183. unknownOption.val('?');
  24184. var options;
  24185. var ngOptions = parseOptionsExpression(attr.ngOptions, selectElement, scope);
  24186. var renderEmptyOption = function() {
  24187. if (!providedEmptyOption) {
  24188. selectElement.prepend(emptyOption);
  24189. }
  24190. selectElement.val('');
  24191. emptyOption.prop('selected', true); // needed for IE
  24192. emptyOption.attr('selected', true);
  24193. };
  24194. var removeEmptyOption = function() {
  24195. if (!providedEmptyOption) {
  24196. emptyOption.remove();
  24197. }
  24198. };
  24199. var renderUnknownOption = function() {
  24200. selectElement.prepend(unknownOption);
  24201. selectElement.val('?');
  24202. unknownOption.prop('selected', true); // needed for IE
  24203. unknownOption.attr('selected', true);
  24204. };
  24205. var removeUnknownOption = function() {
  24206. unknownOption.remove();
  24207. };
  24208. // Update the controller methods for multiple selectable options
  24209. if (!multiple) {
  24210. selectCtrl.writeValue = function writeNgOptionsValue(value) {
  24211. var option = options.getOptionFromViewValue(value);
  24212. if (option && !option.disabled) {
  24213. if (selectElement[0].value !== option.selectValue) {
  24214. removeUnknownOption();
  24215. removeEmptyOption();
  24216. selectElement[0].value = option.selectValue;
  24217. option.element.selected = true;
  24218. option.element.setAttribute('selected', 'selected');
  24219. }
  24220. } else {
  24221. if (value === null || providedEmptyOption) {
  24222. removeUnknownOption();
  24223. renderEmptyOption();
  24224. } else {
  24225. removeEmptyOption();
  24226. renderUnknownOption();
  24227. }
  24228. }
  24229. };
  24230. selectCtrl.readValue = function readNgOptionsValue() {
  24231. var selectedOption = options.selectValueMap[selectElement.val()];
  24232. if (selectedOption && !selectedOption.disabled) {
  24233. removeEmptyOption();
  24234. removeUnknownOption();
  24235. return options.getViewValueFromOption(selectedOption);
  24236. }
  24237. return null;
  24238. };
  24239. // If we are using `track by` then we must watch the tracked value on the model
  24240. // since ngModel only watches for object identity change
  24241. if (ngOptions.trackBy) {
  24242. scope.$watch(
  24243. function() { return ngOptions.getTrackByValue(ngModelCtrl.$viewValue); },
  24244. function() { ngModelCtrl.$render(); }
  24245. );
  24246. }
  24247. } else {
  24248. ngModelCtrl.$isEmpty = function(value) {
  24249. return !value || value.length === 0;
  24250. };
  24251. selectCtrl.writeValue = function writeNgOptionsMultiple(value) {
  24252. options.items.forEach(function(option) {
  24253. option.element.selected = false;
  24254. });
  24255. if (value) {
  24256. value.forEach(function(item) {
  24257. var option = options.getOptionFromViewValue(item);
  24258. if (option && !option.disabled) option.element.selected = true;
  24259. });
  24260. }
  24261. };
  24262. selectCtrl.readValue = function readNgOptionsMultiple() {
  24263. var selectedValues = selectElement.val() || [],
  24264. selections = [];
  24265. forEach(selectedValues, function(value) {
  24266. var option = options.selectValueMap[value];
  24267. if (option && !option.disabled) selections.push(options.getViewValueFromOption(option));
  24268. });
  24269. return selections;
  24270. };
  24271. // If we are using `track by` then we must watch these tracked values on the model
  24272. // since ngModel only watches for object identity change
  24273. if (ngOptions.trackBy) {
  24274. scope.$watchCollection(function() {
  24275. if (isArray(ngModelCtrl.$viewValue)) {
  24276. return ngModelCtrl.$viewValue.map(function(value) {
  24277. return ngOptions.getTrackByValue(value);
  24278. });
  24279. }
  24280. }, function() {
  24281. ngModelCtrl.$render();
  24282. });
  24283. }
  24284. }
  24285. if (providedEmptyOption) {
  24286. // we need to remove it before calling selectElement.empty() because otherwise IE will
  24287. // remove the label from the element. wtf?
  24288. emptyOption.remove();
  24289. // compile the element since there might be bindings in it
  24290. $compile(emptyOption)(scope);
  24291. // remove the class, which is added automatically because we recompile the element and it
  24292. // becomes the compilation root
  24293. emptyOption.removeClass('ng-scope');
  24294. } else {
  24295. emptyOption = jqLite(optionTemplate.cloneNode(false));
  24296. }
  24297. // We need to do this here to ensure that the options object is defined
  24298. // when we first hit it in writeNgOptionsValue
  24299. updateOptions();
  24300. // We will re-render the option elements if the option values or labels change
  24301. scope.$watchCollection(ngOptions.getWatchables, updateOptions);
  24302. // ------------------------------------------------------------------ //
  24303. function updateOptionElement(option, element) {
  24304. option.element = element;
  24305. element.disabled = option.disabled;
  24306. // NOTE: The label must be set before the value, otherwise IE10/11/EDGE create unresponsive
  24307. // selects in certain circumstances when multiple selects are next to each other and display
  24308. // the option list in listbox style, i.e. the select is [multiple], or specifies a [size].
  24309. // See https://github.com/angular/angular.js/issues/11314 for more info.
  24310. // This is unfortunately untestable with unit / e2e tests
  24311. if (option.label !== element.label) {
  24312. element.label = option.label;
  24313. element.textContent = option.label;
  24314. }
  24315. if (option.value !== element.value) element.value = option.selectValue;
  24316. }
  24317. function addOrReuseElement(parent, current, type, templateElement) {
  24318. var element;
  24319. // Check whether we can reuse the next element
  24320. if (current && lowercase(current.nodeName) === type) {
  24321. // The next element is the right type so reuse it
  24322. element = current;
  24323. } else {
  24324. // The next element is not the right type so create a new one
  24325. element = templateElement.cloneNode(false);
  24326. if (!current) {
  24327. // There are no more elements so just append it to the select
  24328. parent.appendChild(element);
  24329. } else {
  24330. // The next element is not a group so insert the new one
  24331. parent.insertBefore(element, current);
  24332. }
  24333. }
  24334. return element;
  24335. }
  24336. function removeExcessElements(current) {
  24337. var next;
  24338. while (current) {
  24339. next = current.nextSibling;
  24340. jqLiteRemove(current);
  24341. current = next;
  24342. }
  24343. }
  24344. function skipEmptyAndUnknownOptions(current) {
  24345. var emptyOption_ = emptyOption && emptyOption[0];
  24346. var unknownOption_ = unknownOption && unknownOption[0];
  24347. // We cannot rely on the extracted empty option being the same as the compiled empty option,
  24348. // because the compiled empty option might have been replaced by a comment because
  24349. // it had an "element" transclusion directive on it (such as ngIf)
  24350. if (emptyOption_ || unknownOption_) {
  24351. while (current &&
  24352. (current === emptyOption_ ||
  24353. current === unknownOption_ ||
  24354. current.nodeType === NODE_TYPE_COMMENT ||
  24355. current.value === '')) {
  24356. current = current.nextSibling;
  24357. }
  24358. }
  24359. return current;
  24360. }
  24361. function updateOptions() {
  24362. var previousValue = options && selectCtrl.readValue();
  24363. options = ngOptions.getOptions();
  24364. var groupMap = {};
  24365. var currentElement = selectElement[0].firstChild;
  24366. // Ensure that the empty option is always there if it was explicitly provided
  24367. if (providedEmptyOption) {
  24368. selectElement.prepend(emptyOption);
  24369. }
  24370. currentElement = skipEmptyAndUnknownOptions(currentElement);
  24371. options.items.forEach(function updateOption(option) {
  24372. var group;
  24373. var groupElement;
  24374. var optionElement;
  24375. if (option.group) {
  24376. // This option is to live in a group
  24377. // See if we have already created this group
  24378. group = groupMap[option.group];
  24379. if (!group) {
  24380. // We have not already created this group
  24381. groupElement = addOrReuseElement(selectElement[0],
  24382. currentElement,
  24383. 'optgroup',
  24384. optGroupTemplate);
  24385. // Move to the next element
  24386. currentElement = groupElement.nextSibling;
  24387. // Update the label on the group element
  24388. groupElement.label = option.group;
  24389. // Store it for use later
  24390. group = groupMap[option.group] = {
  24391. groupElement: groupElement,
  24392. currentOptionElement: groupElement.firstChild
  24393. };
  24394. }
  24395. // So now we have a group for this option we add the option to the group
  24396. optionElement = addOrReuseElement(group.groupElement,
  24397. group.currentOptionElement,
  24398. 'option',
  24399. optionTemplate);
  24400. updateOptionElement(option, optionElement);
  24401. // Move to the next element
  24402. group.currentOptionElement = optionElement.nextSibling;
  24403. } else {
  24404. // This option is not in a group
  24405. optionElement = addOrReuseElement(selectElement[0],
  24406. currentElement,
  24407. 'option',
  24408. optionTemplate);
  24409. updateOptionElement(option, optionElement);
  24410. // Move to the next element
  24411. currentElement = optionElement.nextSibling;
  24412. }
  24413. });
  24414. // Now remove all excess options and group
  24415. Object.keys(groupMap).forEach(function(key) {
  24416. removeExcessElements(groupMap[key].currentOptionElement);
  24417. });
  24418. removeExcessElements(currentElement);
  24419. ngModelCtrl.$render();
  24420. // Check to see if the value has changed due to the update to the options
  24421. if (!ngModelCtrl.$isEmpty(previousValue)) {
  24422. var nextValue = selectCtrl.readValue();
  24423. if (ngOptions.trackBy ? !equals(previousValue, nextValue) : previousValue !== nextValue) {
  24424. ngModelCtrl.$setViewValue(nextValue);
  24425. ngModelCtrl.$render();
  24426. }
  24427. }
  24428. }
  24429. }
  24430. return {
  24431. restrict: 'A',
  24432. terminal: true,
  24433. require: ['select', '?ngModel'],
  24434. link: {
  24435. pre: function ngOptionsPreLink(scope, selectElement, attr, ctrls) {
  24436. // Deactivate the SelectController.register method to prevent
  24437. // option directives from accidentally registering themselves
  24438. // (and unwanted $destroy handlers etc.)
  24439. ctrls[0].registerOption = noop;
  24440. },
  24441. post: ngOptionsPostLink
  24442. }
  24443. };
  24444. }];
  24445. /**
  24446. * @ngdoc directive
  24447. * @name ngPluralize
  24448. * @restrict EA
  24449. *
  24450. * @description
  24451. * `ngPluralize` is a directive that displays messages according to en-US localization rules.
  24452. * These rules are bundled with angular.js, but can be overridden
  24453. * (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
  24454. * by specifying the mappings between
  24455. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24456. * and the strings to be displayed.
  24457. *
  24458. * # Plural categories and explicit number rules
  24459. * There are two
  24460. * [plural categories](http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html)
  24461. * in Angular's default en-US locale: "one" and "other".
  24462. *
  24463. * While a plural category may match many numbers (for example, in en-US locale, "other" can match
  24464. * any number that is not 1), an explicit number rule can only match one number. For example, the
  24465. * explicit number rule for "3" matches the number 3. There are examples of plural categories
  24466. * and explicit number rules throughout the rest of this documentation.
  24467. *
  24468. * # Configuring ngPluralize
  24469. * You configure ngPluralize by providing 2 attributes: `count` and `when`.
  24470. * You can also provide an optional attribute, `offset`.
  24471. *
  24472. * The value of the `count` attribute can be either a string or an {@link guide/expression
  24473. * Angular expression}; these are evaluated on the current scope for its bound value.
  24474. *
  24475. * The `when` attribute specifies the mappings between plural categories and the actual
  24476. * string to be displayed. The value of the attribute should be a JSON object.
  24477. *
  24478. * The following example shows how to configure ngPluralize:
  24479. *
  24480. * ```html
  24481. * <ng-pluralize count="personCount"
  24482. when="{'0': 'Nobody is viewing.',
  24483. * 'one': '1 person is viewing.',
  24484. * 'other': '{} people are viewing.'}">
  24485. * </ng-pluralize>
  24486. *```
  24487. *
  24488. * In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
  24489. * specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
  24490. * would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
  24491. * other numbers, for example 12, so that instead of showing "12 people are viewing", you can
  24492. * show "a dozen people are viewing".
  24493. *
  24494. * You can use a set of closed braces (`{}`) as a placeholder for the number that you want substituted
  24495. * into pluralized strings. In the previous example, Angular will replace `{}` with
  24496. * <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
  24497. * for <span ng-non-bindable>{{numberExpression}}</span>.
  24498. *
  24499. * If no rule is defined for a category, then an empty string is displayed and a warning is generated.
  24500. * Note that some locales define more categories than `one` and `other`. For example, fr-fr defines `few` and `many`.
  24501. *
  24502. * # Configuring ngPluralize with offset
  24503. * The `offset` attribute allows further customization of pluralized text, which can result in
  24504. * a better user experience. For example, instead of the message "4 people are viewing this document",
  24505. * you might display "John, Kate and 2 others are viewing this document".
  24506. * The offset attribute allows you to offset a number by any desired value.
  24507. * Let's take a look at an example:
  24508. *
  24509. * ```html
  24510. * <ng-pluralize count="personCount" offset=2
  24511. * when="{'0': 'Nobody is viewing.',
  24512. * '1': '{{person1}} is viewing.',
  24513. * '2': '{{person1}} and {{person2}} are viewing.',
  24514. * 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24515. * 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24516. * </ng-pluralize>
  24517. * ```
  24518. *
  24519. * Notice that we are still using two plural categories(one, other), but we added
  24520. * three explicit number rules 0, 1 and 2.
  24521. * When one person, perhaps John, views the document, "John is viewing" will be shown.
  24522. * When three people view the document, no explicit number rule is found, so
  24523. * an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
  24524. * In this case, plural category 'one' is matched and "John, Mary and one other person are viewing"
  24525. * is shown.
  24526. *
  24527. * Note that when you specify offsets, you must provide explicit number rules for
  24528. * numbers from 0 up to and including the offset. If you use an offset of 3, for example,
  24529. * you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
  24530. * plural categories "one" and "other".
  24531. *
  24532. * @param {string|expression} count The variable to be bound to.
  24533. * @param {string} when The mapping between plural category to its corresponding strings.
  24534. * @param {number=} offset Offset to deduct from the total number.
  24535. *
  24536. * @example
  24537. <example module="pluralizeExample">
  24538. <file name="index.html">
  24539. <script>
  24540. angular.module('pluralizeExample', [])
  24541. .controller('ExampleController', ['$scope', function($scope) {
  24542. $scope.person1 = 'Igor';
  24543. $scope.person2 = 'Misko';
  24544. $scope.personCount = 1;
  24545. }]);
  24546. </script>
  24547. <div ng-controller="ExampleController">
  24548. <label>Person 1:<input type="text" ng-model="person1" value="Igor" /></label><br/>
  24549. <label>Person 2:<input type="text" ng-model="person2" value="Misko" /></label><br/>
  24550. <label>Number of People:<input type="text" ng-model="personCount" value="1" /></label><br/>
  24551. <!--- Example with simple pluralization rules for en locale --->
  24552. Without Offset:
  24553. <ng-pluralize count="personCount"
  24554. when="{'0': 'Nobody is viewing.',
  24555. 'one': '1 person is viewing.',
  24556. 'other': '{} people are viewing.'}">
  24557. </ng-pluralize><br>
  24558. <!--- Example with offset --->
  24559. With Offset(2):
  24560. <ng-pluralize count="personCount" offset=2
  24561. when="{'0': 'Nobody is viewing.',
  24562. '1': '{{person1}} is viewing.',
  24563. '2': '{{person1}} and {{person2}} are viewing.',
  24564. 'one': '{{person1}}, {{person2}} and one other person are viewing.',
  24565. 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
  24566. </ng-pluralize>
  24567. </div>
  24568. </file>
  24569. <file name="protractor.js" type="protractor">
  24570. it('should show correct pluralized string', function() {
  24571. var withoutOffset = element.all(by.css('ng-pluralize')).get(0);
  24572. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24573. var countInput = element(by.model('personCount'));
  24574. expect(withoutOffset.getText()).toEqual('1 person is viewing.');
  24575. expect(withOffset.getText()).toEqual('Igor is viewing.');
  24576. countInput.clear();
  24577. countInput.sendKeys('0');
  24578. expect(withoutOffset.getText()).toEqual('Nobody is viewing.');
  24579. expect(withOffset.getText()).toEqual('Nobody is viewing.');
  24580. countInput.clear();
  24581. countInput.sendKeys('2');
  24582. expect(withoutOffset.getText()).toEqual('2 people are viewing.');
  24583. expect(withOffset.getText()).toEqual('Igor and Misko are viewing.');
  24584. countInput.clear();
  24585. countInput.sendKeys('3');
  24586. expect(withoutOffset.getText()).toEqual('3 people are viewing.');
  24587. expect(withOffset.getText()).toEqual('Igor, Misko and one other person are viewing.');
  24588. countInput.clear();
  24589. countInput.sendKeys('4');
  24590. expect(withoutOffset.getText()).toEqual('4 people are viewing.');
  24591. expect(withOffset.getText()).toEqual('Igor, Misko and 2 other people are viewing.');
  24592. });
  24593. it('should show data-bound names', function() {
  24594. var withOffset = element.all(by.css('ng-pluralize')).get(1);
  24595. var personCount = element(by.model('personCount'));
  24596. var person1 = element(by.model('person1'));
  24597. var person2 = element(by.model('person2'));
  24598. personCount.clear();
  24599. personCount.sendKeys('4');
  24600. person1.clear();
  24601. person1.sendKeys('Di');
  24602. person2.clear();
  24603. person2.sendKeys('Vojta');
  24604. expect(withOffset.getText()).toEqual('Di, Vojta and 2 other people are viewing.');
  24605. });
  24606. </file>
  24607. </example>
  24608. */
  24609. var ngPluralizeDirective = ['$locale', '$interpolate', '$log', function($locale, $interpolate, $log) {
  24610. var BRACE = /{}/g,
  24611. IS_WHEN = /^when(Minus)?(.+)$/;
  24612. return {
  24613. link: function(scope, element, attr) {
  24614. var numberExp = attr.count,
  24615. whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
  24616. offset = attr.offset || 0,
  24617. whens = scope.$eval(whenExp) || {},
  24618. whensExpFns = {},
  24619. startSymbol = $interpolate.startSymbol(),
  24620. endSymbol = $interpolate.endSymbol(),
  24621. braceReplacement = startSymbol + numberExp + '-' + offset + endSymbol,
  24622. watchRemover = angular.noop,
  24623. lastCount;
  24624. forEach(attr, function(expression, attributeName) {
  24625. var tmpMatch = IS_WHEN.exec(attributeName);
  24626. if (tmpMatch) {
  24627. var whenKey = (tmpMatch[1] ? '-' : '') + lowercase(tmpMatch[2]);
  24628. whens[whenKey] = element.attr(attr.$attr[attributeName]);
  24629. }
  24630. });
  24631. forEach(whens, function(expression, key) {
  24632. whensExpFns[key] = $interpolate(expression.replace(BRACE, braceReplacement));
  24633. });
  24634. scope.$watch(numberExp, function ngPluralizeWatchAction(newVal) {
  24635. var count = parseFloat(newVal);
  24636. var countIsNaN = isNaN(count);
  24637. if (!countIsNaN && !(count in whens)) {
  24638. // If an explicit number rule such as 1, 2, 3... is defined, just use it.
  24639. // Otherwise, check it against pluralization rules in $locale service.
  24640. count = $locale.pluralCat(count - offset);
  24641. }
  24642. // If both `count` and `lastCount` are NaN, we don't need to re-register a watch.
  24643. // In JS `NaN !== NaN`, so we have to exlicitly check.
  24644. if ((count !== lastCount) && !(countIsNaN && isNumber(lastCount) && isNaN(lastCount))) {
  24645. watchRemover();
  24646. var whenExpFn = whensExpFns[count];
  24647. if (isUndefined(whenExpFn)) {
  24648. if (newVal != null) {
  24649. $log.debug("ngPluralize: no rule defined for '" + count + "' in " + whenExp);
  24650. }
  24651. watchRemover = noop;
  24652. updateElementText();
  24653. } else {
  24654. watchRemover = scope.$watch(whenExpFn, updateElementText);
  24655. }
  24656. lastCount = count;
  24657. }
  24658. });
  24659. function updateElementText(newText) {
  24660. element.text(newText || '');
  24661. }
  24662. }
  24663. };
  24664. }];
  24665. /**
  24666. * @ngdoc directive
  24667. * @name ngRepeat
  24668. * @multiElement
  24669. *
  24670. * @description
  24671. * The `ngRepeat` directive instantiates a template once per item from a collection. Each template
  24672. * instance gets its own scope, where the given loop variable is set to the current collection item,
  24673. * and `$index` is set to the item index or key.
  24674. *
  24675. * Special properties are exposed on the local scope of each template instance, including:
  24676. *
  24677. * | Variable | Type | Details |
  24678. * |-----------|-----------------|-----------------------------------------------------------------------------|
  24679. * | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
  24680. * | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
  24681. * | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
  24682. * | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
  24683. * | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
  24684. * | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
  24685. *
  24686. * <div class="alert alert-info">
  24687. * Creating aliases for these properties is possible with {@link ng.directive:ngInit `ngInit`}.
  24688. * This may be useful when, for instance, nesting ngRepeats.
  24689. * </div>
  24690. *
  24691. *
  24692. * # Iterating over object properties
  24693. *
  24694. * It is possible to get `ngRepeat` to iterate over the properties of an object using the following
  24695. * syntax:
  24696. *
  24697. * ```js
  24698. * <div ng-repeat="(key, value) in myObj"> ... </div>
  24699. * ```
  24700. *
  24701. * You need to be aware that the JavaScript specification does not define the order of keys
  24702. * returned for an object. (To mitigate this in Angular 1.3 the `ngRepeat` directive
  24703. * used to sort the keys alphabetically.)
  24704. *
  24705. * Version 1.4 removed the alphabetic sorting. We now rely on the order returned by the browser
  24706. * when running `for key in myObj`. It seems that browsers generally follow the strategy of providing
  24707. * keys in the order in which they were defined, although there are exceptions when keys are deleted
  24708. * and reinstated. See the [MDN page on `delete` for more info](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete#Cross-browser_notes).
  24709. *
  24710. * If this is not desired, the recommended workaround is to convert your object into an array
  24711. * that is sorted into the order that you prefer before providing it to `ngRepeat`. You could
  24712. * do this with a filter such as [toArrayFilter](http://ngmodules.org/modules/angular-toArrayFilter)
  24713. * or implement a `$watch` on the object yourself.
  24714. *
  24715. *
  24716. * # Tracking and Duplicates
  24717. *
  24718. * `ngRepeat` uses {@link $rootScope.Scope#$watchCollection $watchCollection} to detect changes in
  24719. * the collection. When a change happens, ngRepeat then makes the corresponding changes to the DOM:
  24720. *
  24721. * * When an item is added, a new instance of the template is added to the DOM.
  24722. * * When an item is removed, its template instance is removed from the DOM.
  24723. * * When items are reordered, their respective templates are reordered in the DOM.
  24724. *
  24725. * To minimize creation of DOM elements, `ngRepeat` uses a function
  24726. * to "keep track" of all items in the collection and their corresponding DOM elements.
  24727. * For example, if an item is added to the collection, ngRepeat will know that all other items
  24728. * already have DOM elements, and will not re-render them.
  24729. *
  24730. * The default tracking function (which tracks items by their identity) does not allow
  24731. * duplicate items in arrays. This is because when there are duplicates, it is not possible
  24732. * to maintain a one-to-one mapping between collection items and DOM elements.
  24733. *
  24734. * If you do need to repeat duplicate items, you can substitute the default tracking behavior
  24735. * with your own using the `track by` expression.
  24736. *
  24737. * For example, you may track items by the index of each item in the collection, using the
  24738. * special scope property `$index`:
  24739. * ```html
  24740. * <div ng-repeat="n in [42, 42, 43, 43] track by $index">
  24741. * {{n}}
  24742. * </div>
  24743. * ```
  24744. *
  24745. * You may also use arbitrary expressions in `track by`, including references to custom functions
  24746. * on the scope:
  24747. * ```html
  24748. * <div ng-repeat="n in [42, 42, 43, 43] track by myTrackingFunction(n)">
  24749. * {{n}}
  24750. * </div>
  24751. * ```
  24752. *
  24753. * <div class="alert alert-success">
  24754. * If you are working with objects that have an identifier property, you should track
  24755. * by the identifier instead of the whole object. Should you reload your data later, `ngRepeat`
  24756. * will not have to rebuild the DOM elements for items it has already rendered, even if the
  24757. * JavaScript objects in the collection have been substituted for new ones. For large collections,
  24758. * this signifincantly improves rendering performance. If you don't have a unique identifier,
  24759. * `track by $index` can also provide a performance boost.
  24760. * </div>
  24761. * ```html
  24762. * <div ng-repeat="model in collection track by model.id">
  24763. * {{model.name}}
  24764. * </div>
  24765. * ```
  24766. *
  24767. * When no `track by` expression is provided, it is equivalent to tracking by the built-in
  24768. * `$id` function, which tracks items by their identity:
  24769. * ```html
  24770. * <div ng-repeat="obj in collection track by $id(obj)">
  24771. * {{obj.prop}}
  24772. * </div>
  24773. * ```
  24774. *
  24775. * <div class="alert alert-warning">
  24776. * **Note:** `track by` must always be the last expression:
  24777. * </div>
  24778. * ```
  24779. * <div ng-repeat="model in collection | orderBy: 'id' as filtered_result track by model.id">
  24780. * {{model.name}}
  24781. * </div>
  24782. * ```
  24783. *
  24784. * # Special repeat start and end points
  24785. * To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
  24786. * the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
  24787. * 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)
  24788. * up to and including the ending HTML tag where **ng-repeat-end** is placed.
  24789. *
  24790. * The example below makes use of this feature:
  24791. * ```html
  24792. * <header ng-repeat-start="item in items">
  24793. * Header {{ item }}
  24794. * </header>
  24795. * <div class="body">
  24796. * Body {{ item }}
  24797. * </div>
  24798. * <footer ng-repeat-end>
  24799. * Footer {{ item }}
  24800. * </footer>
  24801. * ```
  24802. *
  24803. * And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
  24804. * ```html
  24805. * <header>
  24806. * Header A
  24807. * </header>
  24808. * <div class="body">
  24809. * Body A
  24810. * </div>
  24811. * <footer>
  24812. * Footer A
  24813. * </footer>
  24814. * <header>
  24815. * Header B
  24816. * </header>
  24817. * <div class="body">
  24818. * Body B
  24819. * </div>
  24820. * <footer>
  24821. * Footer B
  24822. * </footer>
  24823. * ```
  24824. *
  24825. * The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
  24826. * as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
  24827. *
  24828. * @animations
  24829. * **.enter** - when a new item is added to the list or when an item is revealed after a filter
  24830. *
  24831. * **.leave** - when an item is removed from the list or when an item is filtered out
  24832. *
  24833. * **.move** - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
  24834. *
  24835. * @element ANY
  24836. * @scope
  24837. * @priority 1000
  24838. * @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
  24839. * formats are currently supported:
  24840. *
  24841. * * `variable in expression` – where variable is the user defined loop variable and `expression`
  24842. * is a scope expression giving the collection to enumerate.
  24843. *
  24844. * For example: `album in artist.albums`.
  24845. *
  24846. * * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
  24847. * and `expression` is the scope expression giving the collection to enumerate.
  24848. *
  24849. * For example: `(name, age) in {'adam':10, 'amalie':12}`.
  24850. *
  24851. * * `variable in expression track by tracking_expression` – You can also provide an optional tracking expression
  24852. * which can be used to associate the objects in the collection with the DOM elements. If no tracking expression
  24853. * is specified, ng-repeat associates elements by identity. It is an error to have
  24854. * more than one tracking expression value resolve to the same key. (This would mean that two distinct objects are
  24855. * mapped to the same DOM element, which is not possible.)
  24856. *
  24857. * Note that the tracking expression must come last, after any filters, and the alias expression.
  24858. *
  24859. * For example: `item in items` is equivalent to `item in items track by $id(item)`. This implies that the DOM elements
  24860. * will be associated by item identity in the array.
  24861. *
  24862. * For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
  24863. * `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
  24864. * with the corresponding item in the array by identity. Moving the same object in array would move the DOM
  24865. * element in the same way in the DOM.
  24866. *
  24867. * For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
  24868. * case the object identity does not matter. Two objects are considered equivalent as long as their `id`
  24869. * property is same.
  24870. *
  24871. * For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
  24872. * to items in conjunction with a tracking expression.
  24873. *
  24874. * * `variable in expression as alias_expression` – You can also provide an optional alias expression which will then store the
  24875. * intermediate results of the repeater after the filters have been applied. Typically this is used to render a special message
  24876. * when a filter is active on the repeater, but the filtered result set is empty.
  24877. *
  24878. * For example: `item in items | filter:x as results` will store the fragment of the repeated items as `results`, but only after
  24879. * the items have been processed through the filter.
  24880. *
  24881. * Please note that `as [variable name] is not an operator but rather a part of ngRepeat micro-syntax so it can be used only at the end
  24882. * (and not as operator, inside an expression).
  24883. *
  24884. * For example: `item in items | filter : x | orderBy : order | limitTo : limit as results` .
  24885. *
  24886. * @example
  24887. * This example initializes the scope to a list of names and
  24888. * then uses `ngRepeat` to display every person:
  24889. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  24890. <file name="index.html">
  24891. <div ng-init="friends = [
  24892. {name:'John', age:25, gender:'boy'},
  24893. {name:'Jessie', age:30, gender:'girl'},
  24894. {name:'Johanna', age:28, gender:'girl'},
  24895. {name:'Joy', age:15, gender:'girl'},
  24896. {name:'Mary', age:28, gender:'girl'},
  24897. {name:'Peter', age:95, gender:'boy'},
  24898. {name:'Sebastian', age:50, gender:'boy'},
  24899. {name:'Erika', age:27, gender:'girl'},
  24900. {name:'Patrick', age:40, gender:'boy'},
  24901. {name:'Samantha', age:60, gender:'girl'}
  24902. ]">
  24903. I have {{friends.length}} friends. They are:
  24904. <input type="search" ng-model="q" placeholder="filter friends..." aria-label="filter friends" />
  24905. <ul class="example-animate-container">
  24906. <li class="animate-repeat" ng-repeat="friend in friends | filter:q as results">
  24907. [{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
  24908. </li>
  24909. <li class="animate-repeat" ng-if="results.length == 0">
  24910. <strong>No results found...</strong>
  24911. </li>
  24912. </ul>
  24913. </div>
  24914. </file>
  24915. <file name="animations.css">
  24916. .example-animate-container {
  24917. background:white;
  24918. border:1px solid black;
  24919. list-style:none;
  24920. margin:0;
  24921. padding:0 10px;
  24922. }
  24923. .animate-repeat {
  24924. line-height:40px;
  24925. list-style:none;
  24926. box-sizing:border-box;
  24927. }
  24928. .animate-repeat.ng-move,
  24929. .animate-repeat.ng-enter,
  24930. .animate-repeat.ng-leave {
  24931. transition:all linear 0.5s;
  24932. }
  24933. .animate-repeat.ng-leave.ng-leave-active,
  24934. .animate-repeat.ng-move,
  24935. .animate-repeat.ng-enter {
  24936. opacity:0;
  24937. max-height:0;
  24938. }
  24939. .animate-repeat.ng-leave,
  24940. .animate-repeat.ng-move.ng-move-active,
  24941. .animate-repeat.ng-enter.ng-enter-active {
  24942. opacity:1;
  24943. max-height:40px;
  24944. }
  24945. </file>
  24946. <file name="protractor.js" type="protractor">
  24947. var friends = element.all(by.repeater('friend in friends'));
  24948. it('should render initial data set', function() {
  24949. expect(friends.count()).toBe(10);
  24950. expect(friends.get(0).getText()).toEqual('[1] John who is 25 years old.');
  24951. expect(friends.get(1).getText()).toEqual('[2] Jessie who is 30 years old.');
  24952. expect(friends.last().getText()).toEqual('[10] Samantha who is 60 years old.');
  24953. expect(element(by.binding('friends.length')).getText())
  24954. .toMatch("I have 10 friends. They are:");
  24955. });
  24956. it('should update repeater when filter predicate changes', function() {
  24957. expect(friends.count()).toBe(10);
  24958. element(by.model('q')).sendKeys('ma');
  24959. expect(friends.count()).toBe(2);
  24960. expect(friends.get(0).getText()).toEqual('[1] Mary who is 28 years old.');
  24961. expect(friends.last().getText()).toEqual('[2] Samantha who is 60 years old.');
  24962. });
  24963. </file>
  24964. </example>
  24965. */
  24966. var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
  24967. var NG_REMOVED = '$$NG_REMOVED';
  24968. var ngRepeatMinErr = minErr('ngRepeat');
  24969. var updateScope = function(scope, index, valueIdentifier, value, keyIdentifier, key, arrayLength) {
  24970. // TODO(perf): generate setters to shave off ~40ms or 1-1.5%
  24971. scope[valueIdentifier] = value;
  24972. if (keyIdentifier) scope[keyIdentifier] = key;
  24973. scope.$index = index;
  24974. scope.$first = (index === 0);
  24975. scope.$last = (index === (arrayLength - 1));
  24976. scope.$middle = !(scope.$first || scope.$last);
  24977. // jshint bitwise: false
  24978. scope.$odd = !(scope.$even = (index&1) === 0);
  24979. // jshint bitwise: true
  24980. };
  24981. var getBlockStart = function(block) {
  24982. return block.clone[0];
  24983. };
  24984. var getBlockEnd = function(block) {
  24985. return block.clone[block.clone.length - 1];
  24986. };
  24987. return {
  24988. restrict: 'A',
  24989. multiElement: true,
  24990. transclude: 'element',
  24991. priority: 1000,
  24992. terminal: true,
  24993. $$tlb: true,
  24994. compile: function ngRepeatCompile($element, $attr) {
  24995. var expression = $attr.ngRepeat;
  24996. var ngRepeatEndComment = document.createComment(' end ngRepeat: ' + expression + ' ');
  24997. 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*$/);
  24998. if (!match) {
  24999. throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
  25000. expression);
  25001. }
  25002. var lhs = match[1];
  25003. var rhs = match[2];
  25004. var aliasAs = match[3];
  25005. var trackByExp = match[4];
  25006. match = lhs.match(/^(?:(\s*[\$\w]+)|\(\s*([\$\w]+)\s*,\s*([\$\w]+)\s*\))$/);
  25007. if (!match) {
  25008. throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
  25009. lhs);
  25010. }
  25011. var valueIdentifier = match[3] || match[1];
  25012. var keyIdentifier = match[2];
  25013. if (aliasAs && (!/^[$a-zA-Z_][$a-zA-Z0-9_]*$/.test(aliasAs) ||
  25014. /^(null|undefined|this|\$index|\$first|\$middle|\$last|\$even|\$odd|\$parent|\$root|\$id)$/.test(aliasAs))) {
  25015. throw ngRepeatMinErr('badident', "alias '{0}' is invalid --- must be a valid JS identifier which is not a reserved name.",
  25016. aliasAs);
  25017. }
  25018. var trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn;
  25019. var hashFnLocals = {$id: hashKey};
  25020. if (trackByExp) {
  25021. trackByExpGetter = $parse(trackByExp);
  25022. } else {
  25023. trackByIdArrayFn = function(key, value) {
  25024. return hashKey(value);
  25025. };
  25026. trackByIdObjFn = function(key) {
  25027. return key;
  25028. };
  25029. }
  25030. return function ngRepeatLink($scope, $element, $attr, ctrl, $transclude) {
  25031. if (trackByExpGetter) {
  25032. trackByIdExpFn = function(key, value, index) {
  25033. // assign key, value, and $index to the locals so that they can be used in hash functions
  25034. if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
  25035. hashFnLocals[valueIdentifier] = value;
  25036. hashFnLocals.$index = index;
  25037. return trackByExpGetter($scope, hashFnLocals);
  25038. };
  25039. }
  25040. // Store a list of elements from previous run. This is a hash where key is the item from the
  25041. // iterator, and the value is objects with following properties.
  25042. // - scope: bound scope
  25043. // - element: previous element.
  25044. // - index: position
  25045. //
  25046. // We are using no-proto object so that we don't need to guard against inherited props via
  25047. // hasOwnProperty.
  25048. var lastBlockMap = createMap();
  25049. //watch props
  25050. $scope.$watchCollection(rhs, function ngRepeatAction(collection) {
  25051. var index, length,
  25052. previousNode = $element[0], // node that cloned nodes should be inserted after
  25053. // initialized to the comment node anchor
  25054. nextNode,
  25055. // Same as lastBlockMap but it has the current state. It will become the
  25056. // lastBlockMap on the next iteration.
  25057. nextBlockMap = createMap(),
  25058. collectionLength,
  25059. key, value, // key/value of iteration
  25060. trackById,
  25061. trackByIdFn,
  25062. collectionKeys,
  25063. block, // last object information {scope, element, id}
  25064. nextBlockOrder,
  25065. elementsToRemove;
  25066. if (aliasAs) {
  25067. $scope[aliasAs] = collection;
  25068. }
  25069. if (isArrayLike(collection)) {
  25070. collectionKeys = collection;
  25071. trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
  25072. } else {
  25073. trackByIdFn = trackByIdExpFn || trackByIdObjFn;
  25074. // if object, extract keys, in enumeration order, unsorted
  25075. collectionKeys = [];
  25076. for (var itemKey in collection) {
  25077. if (hasOwnProperty.call(collection, itemKey) && itemKey.charAt(0) !== '$') {
  25078. collectionKeys.push(itemKey);
  25079. }
  25080. }
  25081. }
  25082. collectionLength = collectionKeys.length;
  25083. nextBlockOrder = new Array(collectionLength);
  25084. // locate existing items
  25085. for (index = 0; index < collectionLength; index++) {
  25086. key = (collection === collectionKeys) ? index : collectionKeys[index];
  25087. value = collection[key];
  25088. trackById = trackByIdFn(key, value, index);
  25089. if (lastBlockMap[trackById]) {
  25090. // found previously seen block
  25091. block = lastBlockMap[trackById];
  25092. delete lastBlockMap[trackById];
  25093. nextBlockMap[trackById] = block;
  25094. nextBlockOrder[index] = block;
  25095. } else if (nextBlockMap[trackById]) {
  25096. // if collision detected. restore lastBlockMap and throw an error
  25097. forEach(nextBlockOrder, function(block) {
  25098. if (block && block.scope) lastBlockMap[block.id] = block;
  25099. });
  25100. throw ngRepeatMinErr('dupes',
  25101. "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}, Duplicate value: {2}",
  25102. expression, trackById, value);
  25103. } else {
  25104. // new never before seen block
  25105. nextBlockOrder[index] = {id: trackById, scope: undefined, clone: undefined};
  25106. nextBlockMap[trackById] = true;
  25107. }
  25108. }
  25109. // remove leftover items
  25110. for (var blockKey in lastBlockMap) {
  25111. block = lastBlockMap[blockKey];
  25112. elementsToRemove = getBlockNodes(block.clone);
  25113. $animate.leave(elementsToRemove);
  25114. if (elementsToRemove[0].parentNode) {
  25115. // if the element was not removed yet because of pending animation, mark it as deleted
  25116. // so that we can ignore it later
  25117. for (index = 0, length = elementsToRemove.length; index < length; index++) {
  25118. elementsToRemove[index][NG_REMOVED] = true;
  25119. }
  25120. }
  25121. block.scope.$destroy();
  25122. }
  25123. // we are not using forEach for perf reasons (trying to avoid #call)
  25124. for (index = 0; index < collectionLength; index++) {
  25125. key = (collection === collectionKeys) ? index : collectionKeys[index];
  25126. value = collection[key];
  25127. block = nextBlockOrder[index];
  25128. if (block.scope) {
  25129. // if we have already seen this object, then we need to reuse the
  25130. // associated scope/element
  25131. nextNode = previousNode;
  25132. // skip nodes that are already pending removal via leave animation
  25133. do {
  25134. nextNode = nextNode.nextSibling;
  25135. } while (nextNode && nextNode[NG_REMOVED]);
  25136. if (getBlockStart(block) != nextNode) {
  25137. // existing item which got moved
  25138. $animate.move(getBlockNodes(block.clone), null, jqLite(previousNode));
  25139. }
  25140. previousNode = getBlockEnd(block);
  25141. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  25142. } else {
  25143. // new item which we don't know about
  25144. $transclude(function ngRepeatTransclude(clone, scope) {
  25145. block.scope = scope;
  25146. // http://jsperf.com/clone-vs-createcomment
  25147. var endNode = ngRepeatEndComment.cloneNode(false);
  25148. clone[clone.length++] = endNode;
  25149. // TODO(perf): support naked previousNode in `enter` to avoid creation of jqLite wrapper?
  25150. $animate.enter(clone, null, jqLite(previousNode));
  25151. previousNode = endNode;
  25152. // Note: We only need the first/last node of the cloned nodes.
  25153. // However, we need to keep the reference to the jqlite wrapper as it might be changed later
  25154. // by a directive with templateUrl when its template arrives.
  25155. block.clone = clone;
  25156. nextBlockMap[block.id] = block;
  25157. updateScope(block.scope, index, valueIdentifier, value, keyIdentifier, key, collectionLength);
  25158. });
  25159. }
  25160. }
  25161. lastBlockMap = nextBlockMap;
  25162. });
  25163. };
  25164. }
  25165. };
  25166. }];
  25167. var NG_HIDE_CLASS = 'ng-hide';
  25168. var NG_HIDE_IN_PROGRESS_CLASS = 'ng-hide-animate';
  25169. /**
  25170. * @ngdoc directive
  25171. * @name ngShow
  25172. * @multiElement
  25173. *
  25174. * @description
  25175. * The `ngShow` directive shows or hides the given HTML element based on the expression
  25176. * provided to the `ngShow` attribute. The element is shown or hidden by removing or adding
  25177. * the `.ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  25178. * in AngularJS and sets the display style to none (using an !important flag).
  25179. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25180. *
  25181. * ```html
  25182. * <!-- when $scope.myValue is truthy (element is visible) -->
  25183. * <div ng-show="myValue"></div>
  25184. *
  25185. * <!-- when $scope.myValue is falsy (element is hidden) -->
  25186. * <div ng-show="myValue" class="ng-hide"></div>
  25187. * ```
  25188. *
  25189. * When the `ngShow` expression evaluates to a falsy value then the `.ng-hide` CSS class is added to the class
  25190. * attribute on the element causing it to become hidden. When truthy, the `.ng-hide` CSS class is removed
  25191. * from the element causing the element not to appear hidden.
  25192. *
  25193. * ## Why is !important used?
  25194. *
  25195. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  25196. * can be easily overridden by heavier selectors. For example, something as simple
  25197. * as changing the display style on a HTML list item would make hidden elements appear visible.
  25198. * This also becomes a bigger issue when dealing with CSS frameworks.
  25199. *
  25200. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  25201. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  25202. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  25203. *
  25204. * ### Overriding `.ng-hide`
  25205. *
  25206. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  25207. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  25208. * class CSS. Note that the selector that needs to be used is actually `.ng-hide:not(.ng-hide-animate)` to cope
  25209. * with extra animation classes that can be added.
  25210. *
  25211. * ```css
  25212. * .ng-hide:not(.ng-hide-animate) {
  25213. * /&#42; this is just another form of hiding an element &#42;/
  25214. * display: block!important;
  25215. * position: absolute;
  25216. * top: -9999px;
  25217. * left: -9999px;
  25218. * }
  25219. * ```
  25220. *
  25221. * By default you don't need to override in CSS anything and the animations will work around the display style.
  25222. *
  25223. * ## A note about animations with `ngShow`
  25224. *
  25225. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  25226. * is true and false. This system works like the animation system present with ngClass except that
  25227. * you must also include the !important flag to override the display property
  25228. * so that you can perform an animation when the element is hidden during the time of the animation.
  25229. *
  25230. * ```css
  25231. * //
  25232. * //a working example can be found at the bottom of this page
  25233. * //
  25234. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  25235. * /&#42; this is required as of 1.3x to properly
  25236. * apply all styling in a show/hide animation &#42;/
  25237. * transition: 0s linear all;
  25238. * }
  25239. *
  25240. * .my-element.ng-hide-add-active,
  25241. * .my-element.ng-hide-remove-active {
  25242. * /&#42; the transition is defined in the active class &#42;/
  25243. * transition: 1s linear all;
  25244. * }
  25245. *
  25246. * .my-element.ng-hide-add { ... }
  25247. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25248. * .my-element.ng-hide-remove { ... }
  25249. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25250. * ```
  25251. *
  25252. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25253. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25254. *
  25255. * @animations
  25256. * addClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a truthy value and the just before contents are set to visible
  25257. * removeClass: `.ng-hide` - happens after the `ngShow` expression evaluates to a non truthy value and just before the contents are set to hidden
  25258. *
  25259. * @element ANY
  25260. * @param {expression} ngShow If the {@link guide/expression expression} is truthy
  25261. * then the element is shown or hidden respectively.
  25262. *
  25263. * @example
  25264. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25265. <file name="index.html">
  25266. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngHide"><br/>
  25267. <div>
  25268. Show:
  25269. <div class="check-element animate-show" ng-show="checked">
  25270. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25271. </div>
  25272. </div>
  25273. <div>
  25274. Hide:
  25275. <div class="check-element animate-show" ng-hide="checked">
  25276. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25277. </div>
  25278. </div>
  25279. </file>
  25280. <file name="glyphicons.css">
  25281. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25282. </file>
  25283. <file name="animations.css">
  25284. .animate-show {
  25285. line-height: 20px;
  25286. opacity: 1;
  25287. padding: 10px;
  25288. border: 1px solid black;
  25289. background: white;
  25290. }
  25291. .animate-show.ng-hide-add, .animate-show.ng-hide-remove {
  25292. transition: all linear 0.5s;
  25293. }
  25294. .animate-show.ng-hide {
  25295. line-height: 0;
  25296. opacity: 0;
  25297. padding: 0 10px;
  25298. }
  25299. .check-element {
  25300. padding: 10px;
  25301. border: 1px solid black;
  25302. background: white;
  25303. }
  25304. </file>
  25305. <file name="protractor.js" type="protractor">
  25306. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25307. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25308. it('should check ng-show / ng-hide', function() {
  25309. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25310. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25311. element(by.model('checked')).click();
  25312. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25313. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25314. });
  25315. </file>
  25316. </example>
  25317. */
  25318. var ngShowDirective = ['$animate', function($animate) {
  25319. return {
  25320. restrict: 'A',
  25321. multiElement: true,
  25322. link: function(scope, element, attr) {
  25323. scope.$watch(attr.ngShow, function ngShowWatchAction(value) {
  25324. // we're adding a temporary, animation-specific class for ng-hide since this way
  25325. // we can control when the element is actually displayed on screen without having
  25326. // to have a global/greedy CSS selector that breaks when other animations are run.
  25327. // Read: https://github.com/angular/angular.js/issues/9103#issuecomment-58335845
  25328. $animate[value ? 'removeClass' : 'addClass'](element, NG_HIDE_CLASS, {
  25329. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25330. });
  25331. });
  25332. }
  25333. };
  25334. }];
  25335. /**
  25336. * @ngdoc directive
  25337. * @name ngHide
  25338. * @multiElement
  25339. *
  25340. * @description
  25341. * The `ngHide` directive shows or hides the given HTML element based on the expression
  25342. * provided to the `ngHide` attribute. The element is shown or hidden by removing or adding
  25343. * the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
  25344. * in AngularJS and sets the display style to none (using an !important flag).
  25345. * For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
  25346. *
  25347. * ```html
  25348. * <!-- when $scope.myValue is truthy (element is hidden) -->
  25349. * <div ng-hide="myValue" class="ng-hide"></div>
  25350. *
  25351. * <!-- when $scope.myValue is falsy (element is visible) -->
  25352. * <div ng-hide="myValue"></div>
  25353. * ```
  25354. *
  25355. * When the `ngHide` expression evaluates to a truthy value then the `.ng-hide` CSS class is added to the class
  25356. * attribute on the element causing it to become hidden. When falsy, the `.ng-hide` CSS class is removed
  25357. * from the element causing the element not to appear hidden.
  25358. *
  25359. * ## Why is !important used?
  25360. *
  25361. * You may be wondering why !important is used for the `.ng-hide` CSS class. This is because the `.ng-hide` selector
  25362. * can be easily overridden by heavier selectors. For example, something as simple
  25363. * as changing the display style on a HTML list item would make hidden elements appear visible.
  25364. * This also becomes a bigger issue when dealing with CSS frameworks.
  25365. *
  25366. * By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
  25367. * specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
  25368. * styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
  25369. *
  25370. * ### Overriding `.ng-hide`
  25371. *
  25372. * By default, the `.ng-hide` class will style the element with `display: none!important`. If you wish to change
  25373. * the hide behavior with ngShow/ngHide then this can be achieved by restating the styles for the `.ng-hide`
  25374. * class in CSS:
  25375. *
  25376. * ```css
  25377. * .ng-hide {
  25378. * /&#42; this is just another form of hiding an element &#42;/
  25379. * display: block!important;
  25380. * position: absolute;
  25381. * top: -9999px;
  25382. * left: -9999px;
  25383. * }
  25384. * ```
  25385. *
  25386. * By default you don't need to override in CSS anything and the animations will work around the display style.
  25387. *
  25388. * ## A note about animations with `ngHide`
  25389. *
  25390. * Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
  25391. * is true and false. This system works like the animation system present with ngClass, except that the `.ng-hide`
  25392. * CSS class is added and removed for you instead of your own CSS class.
  25393. *
  25394. * ```css
  25395. * //
  25396. * //a working example can be found at the bottom of this page
  25397. * //
  25398. * .my-element.ng-hide-add, .my-element.ng-hide-remove {
  25399. * transition: 0.5s linear all;
  25400. * }
  25401. *
  25402. * .my-element.ng-hide-add { ... }
  25403. * .my-element.ng-hide-add.ng-hide-add-active { ... }
  25404. * .my-element.ng-hide-remove { ... }
  25405. * .my-element.ng-hide-remove.ng-hide-remove-active { ... }
  25406. * ```
  25407. *
  25408. * Keep in mind that, as of AngularJS version 1.3.0-beta.11, there is no need to change the display
  25409. * property to block during animation states--ngAnimate will handle the style toggling automatically for you.
  25410. *
  25411. * @animations
  25412. * removeClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a truthy value and just before the contents are set to hidden
  25413. * addClass: `.ng-hide` - happens after the `ngHide` expression evaluates to a non truthy value and just before the contents are set to visible
  25414. *
  25415. * @element ANY
  25416. * @param {expression} ngHide If the {@link guide/expression expression} is truthy then
  25417. * the element is shown or hidden respectively.
  25418. *
  25419. * @example
  25420. <example module="ngAnimate" deps="angular-animate.js" animations="true">
  25421. <file name="index.html">
  25422. Click me: <input type="checkbox" ng-model="checked" aria-label="Toggle ngShow"><br/>
  25423. <div>
  25424. Show:
  25425. <div class="check-element animate-hide" ng-show="checked">
  25426. <span class="glyphicon glyphicon-thumbs-up"></span> I show up when your checkbox is checked.
  25427. </div>
  25428. </div>
  25429. <div>
  25430. Hide:
  25431. <div class="check-element animate-hide" ng-hide="checked">
  25432. <span class="glyphicon glyphicon-thumbs-down"></span> I hide when your checkbox is checked.
  25433. </div>
  25434. </div>
  25435. </file>
  25436. <file name="glyphicons.css">
  25437. @import url(../../components/bootstrap-3.1.1/css/bootstrap.css);
  25438. </file>
  25439. <file name="animations.css">
  25440. .animate-hide {
  25441. transition: all linear 0.5s;
  25442. line-height: 20px;
  25443. opacity: 1;
  25444. padding: 10px;
  25445. border: 1px solid black;
  25446. background: white;
  25447. }
  25448. .animate-hide.ng-hide {
  25449. line-height: 0;
  25450. opacity: 0;
  25451. padding: 0 10px;
  25452. }
  25453. .check-element {
  25454. padding: 10px;
  25455. border: 1px solid black;
  25456. background: white;
  25457. }
  25458. </file>
  25459. <file name="protractor.js" type="protractor">
  25460. var thumbsUp = element(by.css('span.glyphicon-thumbs-up'));
  25461. var thumbsDown = element(by.css('span.glyphicon-thumbs-down'));
  25462. it('should check ng-show / ng-hide', function() {
  25463. expect(thumbsUp.isDisplayed()).toBeFalsy();
  25464. expect(thumbsDown.isDisplayed()).toBeTruthy();
  25465. element(by.model('checked')).click();
  25466. expect(thumbsUp.isDisplayed()).toBeTruthy();
  25467. expect(thumbsDown.isDisplayed()).toBeFalsy();
  25468. });
  25469. </file>
  25470. </example>
  25471. */
  25472. var ngHideDirective = ['$animate', function($animate) {
  25473. return {
  25474. restrict: 'A',
  25475. multiElement: true,
  25476. link: function(scope, element, attr) {
  25477. scope.$watch(attr.ngHide, function ngHideWatchAction(value) {
  25478. // The comment inside of the ngShowDirective explains why we add and
  25479. // remove a temporary class for the show/hide animation
  25480. $animate[value ? 'addClass' : 'removeClass'](element,NG_HIDE_CLASS, {
  25481. tempClasses: NG_HIDE_IN_PROGRESS_CLASS
  25482. });
  25483. });
  25484. }
  25485. };
  25486. }];
  25487. /**
  25488. * @ngdoc directive
  25489. * @name ngStyle
  25490. * @restrict AC
  25491. *
  25492. * @description
  25493. * The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
  25494. *
  25495. * @element ANY
  25496. * @param {expression} ngStyle
  25497. *
  25498. * {@link guide/expression Expression} which evals to an
  25499. * object whose keys are CSS style names and values are corresponding values for those CSS
  25500. * keys.
  25501. *
  25502. * Since some CSS style names are not valid keys for an object, they must be quoted.
  25503. * See the 'background-color' style in the example below.
  25504. *
  25505. * @example
  25506. <example>
  25507. <file name="index.html">
  25508. <input type="button" value="set color" ng-click="myStyle={color:'red'}">
  25509. <input type="button" value="set background" ng-click="myStyle={'background-color':'blue'}">
  25510. <input type="button" value="clear" ng-click="myStyle={}">
  25511. <br/>
  25512. <span ng-style="myStyle">Sample Text</span>
  25513. <pre>myStyle={{myStyle}}</pre>
  25514. </file>
  25515. <file name="style.css">
  25516. span {
  25517. color: black;
  25518. }
  25519. </file>
  25520. <file name="protractor.js" type="protractor">
  25521. var colorSpan = element(by.css('span'));
  25522. it('should check ng-style', function() {
  25523. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25524. element(by.css('input[value=\'set color\']')).click();
  25525. expect(colorSpan.getCssValue('color')).toBe('rgba(255, 0, 0, 1)');
  25526. element(by.css('input[value=clear]')).click();
  25527. expect(colorSpan.getCssValue('color')).toBe('rgba(0, 0, 0, 1)');
  25528. });
  25529. </file>
  25530. </example>
  25531. */
  25532. var ngStyleDirective = ngDirective(function(scope, element, attr) {
  25533. scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
  25534. if (oldStyles && (newStyles !== oldStyles)) {
  25535. forEach(oldStyles, function(val, style) { element.css(style, '');});
  25536. }
  25537. if (newStyles) element.css(newStyles);
  25538. }, true);
  25539. });
  25540. /**
  25541. * @ngdoc directive
  25542. * @name ngSwitch
  25543. * @restrict EA
  25544. *
  25545. * @description
  25546. * The `ngSwitch` directive is used to conditionally swap DOM structure on your template based on a scope expression.
  25547. * Elements within `ngSwitch` but without `ngSwitchWhen` or `ngSwitchDefault` directives will be preserved at the location
  25548. * as specified in the template.
  25549. *
  25550. * The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
  25551. * from the template cache), `ngSwitch` simply chooses one of the nested elements and makes it visible based on which element
  25552. * matches the value obtained from the evaluated expression. In other words, you define a container element
  25553. * (where you place the directive), place an expression on the **`on="..."` attribute**
  25554. * (or the **`ng-switch="..."` attribute**), define any inner elements inside of the directive and place
  25555. * a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
  25556. * expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
  25557. * attribute is displayed.
  25558. *
  25559. * <div class="alert alert-info">
  25560. * Be aware that the attribute values to match against cannot be expressions. They are interpreted
  25561. * as literal string values to match against.
  25562. * For example, **`ng-switch-when="someVal"`** will match against the string `"someVal"` not against the
  25563. * value of the expression `$scope.someVal`.
  25564. * </div>
  25565. * @animations
  25566. * enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
  25567. * leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
  25568. *
  25569. * @usage
  25570. *
  25571. * ```
  25572. * <ANY ng-switch="expression">
  25573. * <ANY ng-switch-when="matchValue1">...</ANY>
  25574. * <ANY ng-switch-when="matchValue2">...</ANY>
  25575. * <ANY ng-switch-default>...</ANY>
  25576. * </ANY>
  25577. * ```
  25578. *
  25579. *
  25580. * @scope
  25581. * @priority 1200
  25582. * @param {*} ngSwitch|on expression to match against <code>ng-switch-when</code>.
  25583. * On child elements add:
  25584. *
  25585. * * `ngSwitchWhen`: the case statement to match against. If match then this
  25586. * case will be displayed. If the same match appears multiple times, all the
  25587. * elements will be displayed.
  25588. * * `ngSwitchDefault`: the default case when no other case match. If there
  25589. * are multiple default cases, all of them will be displayed when no other
  25590. * case match.
  25591. *
  25592. *
  25593. * @example
  25594. <example module="switchExample" deps="angular-animate.js" animations="true">
  25595. <file name="index.html">
  25596. <div ng-controller="ExampleController">
  25597. <select ng-model="selection" ng-options="item for item in items">
  25598. </select>
  25599. <code>selection={{selection}}</code>
  25600. <hr/>
  25601. <div class="animate-switch-container"
  25602. ng-switch on="selection">
  25603. <div class="animate-switch" ng-switch-when="settings">Settings Div</div>
  25604. <div class="animate-switch" ng-switch-when="home">Home Span</div>
  25605. <div class="animate-switch" ng-switch-default>default</div>
  25606. </div>
  25607. </div>
  25608. </file>
  25609. <file name="script.js">
  25610. angular.module('switchExample', ['ngAnimate'])
  25611. .controller('ExampleController', ['$scope', function($scope) {
  25612. $scope.items = ['settings', 'home', 'other'];
  25613. $scope.selection = $scope.items[0];
  25614. }]);
  25615. </file>
  25616. <file name="animations.css">
  25617. .animate-switch-container {
  25618. position:relative;
  25619. background:white;
  25620. border:1px solid black;
  25621. height:40px;
  25622. overflow:hidden;
  25623. }
  25624. .animate-switch {
  25625. padding:10px;
  25626. }
  25627. .animate-switch.ng-animate {
  25628. transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
  25629. position:absolute;
  25630. top:0;
  25631. left:0;
  25632. right:0;
  25633. bottom:0;
  25634. }
  25635. .animate-switch.ng-leave.ng-leave-active,
  25636. .animate-switch.ng-enter {
  25637. top:-50px;
  25638. }
  25639. .animate-switch.ng-leave,
  25640. .animate-switch.ng-enter.ng-enter-active {
  25641. top:0;
  25642. }
  25643. </file>
  25644. <file name="protractor.js" type="protractor">
  25645. var switchElem = element(by.css('[ng-switch]'));
  25646. var select = element(by.model('selection'));
  25647. it('should start in settings', function() {
  25648. expect(switchElem.getText()).toMatch(/Settings Div/);
  25649. });
  25650. it('should change to home', function() {
  25651. select.all(by.css('option')).get(1).click();
  25652. expect(switchElem.getText()).toMatch(/Home Span/);
  25653. });
  25654. it('should select default', function() {
  25655. select.all(by.css('option')).get(2).click();
  25656. expect(switchElem.getText()).toMatch(/default/);
  25657. });
  25658. </file>
  25659. </example>
  25660. */
  25661. var ngSwitchDirective = ['$animate', function($animate) {
  25662. return {
  25663. require: 'ngSwitch',
  25664. // asks for $scope to fool the BC controller module
  25665. controller: ['$scope', function ngSwitchController() {
  25666. this.cases = {};
  25667. }],
  25668. link: function(scope, element, attr, ngSwitchController) {
  25669. var watchExpr = attr.ngSwitch || attr.on,
  25670. selectedTranscludes = [],
  25671. selectedElements = [],
  25672. previousLeaveAnimations = [],
  25673. selectedScopes = [];
  25674. var spliceFactory = function(array, index) {
  25675. return function() { array.splice(index, 1); };
  25676. };
  25677. scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
  25678. var i, ii;
  25679. for (i = 0, ii = previousLeaveAnimations.length; i < ii; ++i) {
  25680. $animate.cancel(previousLeaveAnimations[i]);
  25681. }
  25682. previousLeaveAnimations.length = 0;
  25683. for (i = 0, ii = selectedScopes.length; i < ii; ++i) {
  25684. var selected = getBlockNodes(selectedElements[i].clone);
  25685. selectedScopes[i].$destroy();
  25686. var promise = previousLeaveAnimations[i] = $animate.leave(selected);
  25687. promise.then(spliceFactory(previousLeaveAnimations, i));
  25688. }
  25689. selectedElements.length = 0;
  25690. selectedScopes.length = 0;
  25691. if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
  25692. forEach(selectedTranscludes, function(selectedTransclude) {
  25693. selectedTransclude.transclude(function(caseElement, selectedScope) {
  25694. selectedScopes.push(selectedScope);
  25695. var anchor = selectedTransclude.element;
  25696. caseElement[caseElement.length++] = document.createComment(' end ngSwitchWhen: ');
  25697. var block = { clone: caseElement };
  25698. selectedElements.push(block);
  25699. $animate.enter(caseElement, anchor.parent(), anchor);
  25700. });
  25701. });
  25702. }
  25703. });
  25704. }
  25705. };
  25706. }];
  25707. var ngSwitchWhenDirective = ngDirective({
  25708. transclude: 'element',
  25709. priority: 1200,
  25710. require: '^ngSwitch',
  25711. multiElement: true,
  25712. link: function(scope, element, attrs, ctrl, $transclude) {
  25713. ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
  25714. ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: $transclude, element: element });
  25715. }
  25716. });
  25717. var ngSwitchDefaultDirective = ngDirective({
  25718. transclude: 'element',
  25719. priority: 1200,
  25720. require: '^ngSwitch',
  25721. multiElement: true,
  25722. link: function(scope, element, attr, ctrl, $transclude) {
  25723. ctrl.cases['?'] = (ctrl.cases['?'] || []);
  25724. ctrl.cases['?'].push({ transclude: $transclude, element: element });
  25725. }
  25726. });
  25727. /**
  25728. * @ngdoc directive
  25729. * @name ngTransclude
  25730. * @restrict EAC
  25731. *
  25732. * @description
  25733. * Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
  25734. *
  25735. * Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
  25736. *
  25737. * @element ANY
  25738. *
  25739. * @example
  25740. <example module="transcludeExample">
  25741. <file name="index.html">
  25742. <script>
  25743. angular.module('transcludeExample', [])
  25744. .directive('pane', function(){
  25745. return {
  25746. restrict: 'E',
  25747. transclude: true,
  25748. scope: { title:'@' },
  25749. template: '<div style="border: 1px solid black;">' +
  25750. '<div style="background-color: gray">{{title}}</div>' +
  25751. '<ng-transclude></ng-transclude>' +
  25752. '</div>'
  25753. };
  25754. })
  25755. .controller('ExampleController', ['$scope', function($scope) {
  25756. $scope.title = 'Lorem Ipsum';
  25757. $scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
  25758. }]);
  25759. </script>
  25760. <div ng-controller="ExampleController">
  25761. <input ng-model="title" aria-label="title"> <br/>
  25762. <textarea ng-model="text" aria-label="text"></textarea> <br/>
  25763. <pane title="{{title}}">{{text}}</pane>
  25764. </div>
  25765. </file>
  25766. <file name="protractor.js" type="protractor">
  25767. it('should have transcluded', function() {
  25768. var titleElement = element(by.model('title'));
  25769. titleElement.clear();
  25770. titleElement.sendKeys('TITLE');
  25771. var textElement = element(by.model('text'));
  25772. textElement.clear();
  25773. textElement.sendKeys('TEXT');
  25774. expect(element(by.binding('title')).getText()).toEqual('TITLE');
  25775. expect(element(by.binding('text')).getText()).toEqual('TEXT');
  25776. });
  25777. </file>
  25778. </example>
  25779. *
  25780. */
  25781. var ngTranscludeDirective = ngDirective({
  25782. restrict: 'EAC',
  25783. link: function($scope, $element, $attrs, controller, $transclude) {
  25784. if (!$transclude) {
  25785. throw minErr('ngTransclude')('orphan',
  25786. 'Illegal use of ngTransclude directive in the template! ' +
  25787. 'No parent directive that requires a transclusion found. ' +
  25788. 'Element: {0}',
  25789. startingTag($element));
  25790. }
  25791. $transclude(function(clone) {
  25792. $element.empty();
  25793. $element.append(clone);
  25794. });
  25795. }
  25796. });
  25797. /**
  25798. * @ngdoc directive
  25799. * @name script
  25800. * @restrict E
  25801. *
  25802. * @description
  25803. * Load the content of a `<script>` element into {@link ng.$templateCache `$templateCache`}, so that the
  25804. * template can be used by {@link ng.directive:ngInclude `ngInclude`},
  25805. * {@link ngRoute.directive:ngView `ngView`}, or {@link guide/directive directives}. The type of the
  25806. * `<script>` element must be specified as `text/ng-template`, and a cache name for the template must be
  25807. * assigned through the element's `id`, which can then be used as a directive's `templateUrl`.
  25808. *
  25809. * @param {string} type Must be set to `'text/ng-template'`.
  25810. * @param {string} id Cache name of the template.
  25811. *
  25812. * @example
  25813. <example>
  25814. <file name="index.html">
  25815. <script type="text/ng-template" id="/tpl.html">
  25816. Content of the template.
  25817. </script>
  25818. <a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
  25819. <div id="tpl-content" ng-include src="currentTpl"></div>
  25820. </file>
  25821. <file name="protractor.js" type="protractor">
  25822. it('should load template defined inside script tag', function() {
  25823. element(by.css('#tpl-link')).click();
  25824. expect(element(by.css('#tpl-content')).getText()).toMatch(/Content of the template/);
  25825. });
  25826. </file>
  25827. </example>
  25828. */
  25829. var scriptDirective = ['$templateCache', function($templateCache) {
  25830. return {
  25831. restrict: 'E',
  25832. terminal: true,
  25833. compile: function(element, attr) {
  25834. if (attr.type == 'text/ng-template') {
  25835. var templateUrl = attr.id,
  25836. text = element[0].text;
  25837. $templateCache.put(templateUrl, text);
  25838. }
  25839. }
  25840. };
  25841. }];
  25842. var noopNgModelController = { $setViewValue: noop, $render: noop };
  25843. function chromeHack(optionElement) {
  25844. // Workaround for https://code.google.com/p/chromium/issues/detail?id=381459
  25845. // Adding an <option selected="selected"> element to a <select required="required"> should
  25846. // automatically select the new element
  25847. if (optionElement[0].hasAttribute('selected')) {
  25848. optionElement[0].selected = true;
  25849. }
  25850. }
  25851. /**
  25852. * @ngdoc type
  25853. * @name select.SelectController
  25854. * @description
  25855. * The controller for the `<select>` directive. This provides support for reading
  25856. * and writing the selected value(s) of the control and also coordinates dynamically
  25857. * added `<option>` elements, perhaps by an `ngRepeat` directive.
  25858. */
  25859. var SelectController =
  25860. ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
  25861. var self = this,
  25862. optionsMap = new HashMap();
  25863. // If the ngModel doesn't get provided then provide a dummy noop version to prevent errors
  25864. self.ngModelCtrl = noopNgModelController;
  25865. // The "unknown" option is one that is prepended to the list if the viewValue
  25866. // does not match any of the options. When it is rendered the value of the unknown
  25867. // option is '? XXX ?' where XXX is the hashKey of the value that is not known.
  25868. //
  25869. // We can't just jqLite('<option>') since jqLite is not smart enough
  25870. // to create it in <select> and IE barfs otherwise.
  25871. self.unknownOption = jqLite(document.createElement('option'));
  25872. self.renderUnknownOption = function(val) {
  25873. var unknownVal = '? ' + hashKey(val) + ' ?';
  25874. self.unknownOption.val(unknownVal);
  25875. $element.prepend(self.unknownOption);
  25876. $element.val(unknownVal);
  25877. };
  25878. $scope.$on('$destroy', function() {
  25879. // disable unknown option so that we don't do work when the whole select is being destroyed
  25880. self.renderUnknownOption = noop;
  25881. });
  25882. self.removeUnknownOption = function() {
  25883. if (self.unknownOption.parent()) self.unknownOption.remove();
  25884. };
  25885. // Read the value of the select control, the implementation of this changes depending
  25886. // upon whether the select can have multiple values and whether ngOptions is at work.
  25887. self.readValue = function readSingleValue() {
  25888. self.removeUnknownOption();
  25889. return $element.val();
  25890. };
  25891. // Write the value to the select control, the implementation of this changes depending
  25892. // upon whether the select can have multiple values and whether ngOptions is at work.
  25893. self.writeValue = function writeSingleValue(value) {
  25894. if (self.hasOption(value)) {
  25895. self.removeUnknownOption();
  25896. $element.val(value);
  25897. if (value === '') self.emptyOption.prop('selected', true); // to make IE9 happy
  25898. } else {
  25899. if (value == null && self.emptyOption) {
  25900. self.removeUnknownOption();
  25901. $element.val('');
  25902. } else {
  25903. self.renderUnknownOption(value);
  25904. }
  25905. }
  25906. };
  25907. // Tell the select control that an option, with the given value, has been added
  25908. self.addOption = function(value, element) {
  25909. assertNotHasOwnProperty(value, '"option value"');
  25910. if (value === '') {
  25911. self.emptyOption = element;
  25912. }
  25913. var count = optionsMap.get(value) || 0;
  25914. optionsMap.put(value, count + 1);
  25915. self.ngModelCtrl.$render();
  25916. chromeHack(element);
  25917. };
  25918. // Tell the select control that an option, with the given value, has been removed
  25919. self.removeOption = function(value) {
  25920. var count = optionsMap.get(value);
  25921. if (count) {
  25922. if (count === 1) {
  25923. optionsMap.remove(value);
  25924. if (value === '') {
  25925. self.emptyOption = undefined;
  25926. }
  25927. } else {
  25928. optionsMap.put(value, count - 1);
  25929. }
  25930. }
  25931. };
  25932. // Check whether the select control has an option matching the given value
  25933. self.hasOption = function(value) {
  25934. return !!optionsMap.get(value);
  25935. };
  25936. self.registerOption = function(optionScope, optionElement, optionAttrs, interpolateValueFn, interpolateTextFn) {
  25937. if (interpolateValueFn) {
  25938. // The value attribute is interpolated
  25939. var oldVal;
  25940. optionAttrs.$observe('value', function valueAttributeObserveAction(newVal) {
  25941. if (isDefined(oldVal)) {
  25942. self.removeOption(oldVal);
  25943. }
  25944. oldVal = newVal;
  25945. self.addOption(newVal, optionElement);
  25946. });
  25947. } else if (interpolateTextFn) {
  25948. // The text content is interpolated
  25949. optionScope.$watch(interpolateTextFn, function interpolateWatchAction(newVal, oldVal) {
  25950. optionAttrs.$set('value', newVal);
  25951. if (oldVal !== newVal) {
  25952. self.removeOption(oldVal);
  25953. }
  25954. self.addOption(newVal, optionElement);
  25955. });
  25956. } else {
  25957. // The value attribute is static
  25958. self.addOption(optionAttrs.value, optionElement);
  25959. }
  25960. optionElement.on('$destroy', function() {
  25961. self.removeOption(optionAttrs.value);
  25962. self.ngModelCtrl.$render();
  25963. });
  25964. };
  25965. }];
  25966. /**
  25967. * @ngdoc directive
  25968. * @name select
  25969. * @restrict E
  25970. *
  25971. * @description
  25972. * HTML `SELECT` element with angular data-binding.
  25973. *
  25974. * The `select` directive is used together with {@link ngModel `ngModel`} to provide data-binding
  25975. * between the scope and the `<select>` control (including setting default values).
  25976. * Ìt also handles dynamic `<option>` elements, which can be added using the {@link ngRepeat `ngRepeat}` or
  25977. * {@link ngOptions `ngOptions`} directives.
  25978. *
  25979. * When an item in the `<select>` menu is selected, the value of the selected option will be bound
  25980. * to the model identified by the `ngModel` directive. With static or repeated options, this is
  25981. * the content of the `value` attribute or the textContent of the `<option>`, if the value attribute is missing.
  25982. * If you want dynamic value attributes, you can use interpolation inside the value attribute.
  25983. *
  25984. * <div class="alert alert-warning">
  25985. * Note that the value of a `select` directive used without `ngOptions` is always a string.
  25986. * When the model needs to be bound to a non-string value, you must either explictly convert it
  25987. * using a directive (see example below) or use `ngOptions` to specify the set of options.
  25988. * This is because an option element can only be bound to string values at present.
  25989. * </div>
  25990. *
  25991. * If the viewValue of `ngModel` does not match any of the options, then the control
  25992. * will automatically add an "unknown" option, which it then removes when the mismatch is resolved.
  25993. *
  25994. * Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
  25995. * be nested into the `<select>` element. This element will then represent the `null` or "not selected"
  25996. * option. See example below for demonstration.
  25997. *
  25998. * <div class="alert alert-info">
  25999. * In many cases, `ngRepeat` can be used on `<option>` elements instead of {@link ng.directive:ngOptions
  26000. * ngOptions} to achieve a similar result. However, `ngOptions` provides some benefits, such as
  26001. * more flexibility in how the `<select>`'s model is assigned via the `select` **`as`** part of the
  26002. * comprehension expression, and additionally in reducing memory and increasing speed by not creating
  26003. * a new scope for each repeated instance.
  26004. * </div>
  26005. *
  26006. *
  26007. * @param {string} ngModel Assignable angular expression to data-bind to.
  26008. * @param {string=} name Property name of the form under which the control is published.
  26009. * @param {string=} multiple Allows multiple options to be selected. The selected values will be
  26010. * bound to the model as an array.
  26011. * @param {string=} required Sets `required` validation error key if the value is not entered.
  26012. * @param {string=} ngRequired Adds required attribute and required validation constraint to
  26013. * the element when the ngRequired expression evaluates to true. Use ngRequired instead of required
  26014. * when you want to data-bind to the required attribute.
  26015. * @param {string=} ngChange Angular expression to be executed when selected option(s) changes due to user
  26016. * interaction with the select element.
  26017. * @param {string=} ngOptions sets the options that the select is populated with and defines what is
  26018. * set on the model on selection. See {@link ngOptions `ngOptions`}.
  26019. *
  26020. * @example
  26021. * ### Simple `select` elements with static options
  26022. *
  26023. * <example name="static-select" module="staticSelect">
  26024. * <file name="index.html">
  26025. * <div ng-controller="ExampleController">
  26026. * <form name="myForm">
  26027. * <label for="singleSelect"> Single select: </label><br>
  26028. * <select name="singleSelect" ng-model="data.singleSelect">
  26029. * <option value="option-1">Option 1</option>
  26030. * <option value="option-2">Option 2</option>
  26031. * </select><br>
  26032. *
  26033. * <label for="singleSelect"> Single select with "not selected" option and dynamic option values: </label><br>
  26034. * <select name="singleSelect" id="singleSelect" ng-model="data.singleSelect">
  26035. * <option value="">---Please select---</option> <!-- not selected / blank option -->
  26036. * <option value="{{data.option1}}">Option 1</option> <!-- interpolation -->
  26037. * <option value="option-2">Option 2</option>
  26038. * </select><br>
  26039. * <button ng-click="forceUnknownOption()">Force unknown option</button><br>
  26040. * <tt>singleSelect = {{data.singleSelect}}</tt>
  26041. *
  26042. * <hr>
  26043. * <label for="multipleSelect"> Multiple select: </label><br>
  26044. * <select name="multipleSelect" id="multipleSelect" ng-model="data.multipleSelect" multiple>
  26045. * <option value="option-1">Option 1</option>
  26046. * <option value="option-2">Option 2</option>
  26047. * <option value="option-3">Option 3</option>
  26048. * </select><br>
  26049. * <tt>multipleSelect = {{data.multipleSelect}}</tt><br/>
  26050. * </form>
  26051. * </div>
  26052. * </file>
  26053. * <file name="app.js">
  26054. * angular.module('staticSelect', [])
  26055. * .controller('ExampleController', ['$scope', function($scope) {
  26056. * $scope.data = {
  26057. * singleSelect: null,
  26058. * multipleSelect: [],
  26059. * option1: 'option-1',
  26060. * };
  26061. *
  26062. * $scope.forceUnknownOption = function() {
  26063. * $scope.data.singleSelect = 'nonsense';
  26064. * };
  26065. * }]);
  26066. * </file>
  26067. *</example>
  26068. *
  26069. * ### Using `ngRepeat` to generate `select` options
  26070. * <example name="ngrepeat-select" module="ngrepeatSelect">
  26071. * <file name="index.html">
  26072. * <div ng-controller="ExampleController">
  26073. * <form name="myForm">
  26074. * <label for="repeatSelect"> Repeat select: </label>
  26075. * <select name="repeatSelect" id="repeatSelect" ng-model="data.repeatSelect">
  26076. * <option ng-repeat="option in data.availableOptions" value="{{option.id}}">{{option.name}}</option>
  26077. * </select>
  26078. * </form>
  26079. * <hr>
  26080. * <tt>repeatSelect = {{data.repeatSelect}}</tt><br/>
  26081. * </div>
  26082. * </file>
  26083. * <file name="app.js">
  26084. * angular.module('ngrepeatSelect', [])
  26085. * .controller('ExampleController', ['$scope', function($scope) {
  26086. * $scope.data = {
  26087. * repeatSelect: null,
  26088. * availableOptions: [
  26089. * {id: '1', name: 'Option A'},
  26090. * {id: '2', name: 'Option B'},
  26091. * {id: '3', name: 'Option C'}
  26092. * ],
  26093. * };
  26094. * }]);
  26095. * </file>
  26096. *</example>
  26097. *
  26098. *
  26099. * ### Using `select` with `ngOptions` and setting a default value
  26100. * See the {@link ngOptions ngOptions documentation} for more `ngOptions` usage examples.
  26101. *
  26102. * <example name="select-with-default-values" module="defaultValueSelect">
  26103. * <file name="index.html">
  26104. * <div ng-controller="ExampleController">
  26105. * <form name="myForm">
  26106. * <label for="mySelect">Make a choice:</label>
  26107. * <select name="mySelect" id="mySelect"
  26108. * ng-options="option.name for option in data.availableOptions track by option.id"
  26109. * ng-model="data.selectedOption"></select>
  26110. * </form>
  26111. * <hr>
  26112. * <tt>option = {{data.selectedOption}}</tt><br/>
  26113. * </div>
  26114. * </file>
  26115. * <file name="app.js">
  26116. * angular.module('defaultValueSelect', [])
  26117. * .controller('ExampleController', ['$scope', function($scope) {
  26118. * $scope.data = {
  26119. * availableOptions: [
  26120. * {id: '1', name: 'Option A'},
  26121. * {id: '2', name: 'Option B'},
  26122. * {id: '3', name: 'Option C'}
  26123. * ],
  26124. * selectedOption: {id: '3', name: 'Option C'} //This sets the default value of the select in the ui
  26125. * };
  26126. * }]);
  26127. * </file>
  26128. *</example>
  26129. *
  26130. *
  26131. * ### Binding `select` to a non-string value via `ngModel` parsing / formatting
  26132. *
  26133. * <example name="select-with-non-string-options" module="nonStringSelect">
  26134. * <file name="index.html">
  26135. * <select ng-model="model.id" convert-to-number>
  26136. * <option value="0">Zero</option>
  26137. * <option value="1">One</option>
  26138. * <option value="2">Two</option>
  26139. * </select>
  26140. * {{ model }}
  26141. * </file>
  26142. * <file name="app.js">
  26143. * angular.module('nonStringSelect', [])
  26144. * .run(function($rootScope) {
  26145. * $rootScope.model = { id: 2 };
  26146. * })
  26147. * .directive('convertToNumber', function() {
  26148. * return {
  26149. * require: 'ngModel',
  26150. * link: function(scope, element, attrs, ngModel) {
  26151. * ngModel.$parsers.push(function(val) {
  26152. * return parseInt(val, 10);
  26153. * });
  26154. * ngModel.$formatters.push(function(val) {
  26155. * return '' + val;
  26156. * });
  26157. * }
  26158. * };
  26159. * });
  26160. * </file>
  26161. * <file name="protractor.js" type="protractor">
  26162. * it('should initialize to model', function() {
  26163. * var select = element(by.css('select'));
  26164. * expect(element(by.model('model.id')).$('option:checked').getText()).toEqual('Two');
  26165. * });
  26166. * </file>
  26167. * </example>
  26168. *
  26169. */
  26170. var selectDirective = function() {
  26171. return {
  26172. restrict: 'E',
  26173. require: ['select', '?ngModel'],
  26174. controller: SelectController,
  26175. priority: 1,
  26176. link: {
  26177. pre: selectPreLink
  26178. }
  26179. };
  26180. function selectPreLink(scope, element, attr, ctrls) {
  26181. // if ngModel is not defined, we don't need to do anything
  26182. var ngModelCtrl = ctrls[1];
  26183. if (!ngModelCtrl) return;
  26184. var selectCtrl = ctrls[0];
  26185. selectCtrl.ngModelCtrl = ngModelCtrl;
  26186. // We delegate rendering to the `writeValue` method, which can be changed
  26187. // if the select can have multiple selected values or if the options are being
  26188. // generated by `ngOptions`
  26189. ngModelCtrl.$render = function() {
  26190. selectCtrl.writeValue(ngModelCtrl.$viewValue);
  26191. };
  26192. // When the selected item(s) changes we delegate getting the value of the select control
  26193. // to the `readValue` method, which can be changed if the select can have multiple
  26194. // selected values or if the options are being generated by `ngOptions`
  26195. element.on('change', function() {
  26196. scope.$apply(function() {
  26197. ngModelCtrl.$setViewValue(selectCtrl.readValue());
  26198. });
  26199. });
  26200. // If the select allows multiple values then we need to modify how we read and write
  26201. // values from and to the control; also what it means for the value to be empty and
  26202. // we have to add an extra watch since ngModel doesn't work well with arrays - it
  26203. // doesn't trigger rendering if only an item in the array changes.
  26204. if (attr.multiple) {
  26205. // Read value now needs to check each option to see if it is selected
  26206. selectCtrl.readValue = function readMultipleValue() {
  26207. var array = [];
  26208. forEach(element.find('option'), function(option) {
  26209. if (option.selected) {
  26210. array.push(option.value);
  26211. }
  26212. });
  26213. return array;
  26214. };
  26215. // Write value now needs to set the selected property of each matching option
  26216. selectCtrl.writeValue = function writeMultipleValue(value) {
  26217. var items = new HashMap(value);
  26218. forEach(element.find('option'), function(option) {
  26219. option.selected = isDefined(items.get(option.value));
  26220. });
  26221. };
  26222. // we have to do it on each watch since ngModel watches reference, but
  26223. // we need to work of an array, so we need to see if anything was inserted/removed
  26224. var lastView, lastViewRef = NaN;
  26225. scope.$watch(function selectMultipleWatch() {
  26226. if (lastViewRef === ngModelCtrl.$viewValue && !equals(lastView, ngModelCtrl.$viewValue)) {
  26227. lastView = shallowCopy(ngModelCtrl.$viewValue);
  26228. ngModelCtrl.$render();
  26229. }
  26230. lastViewRef = ngModelCtrl.$viewValue;
  26231. });
  26232. // If we are a multiple select then value is now a collection
  26233. // so the meaning of $isEmpty changes
  26234. ngModelCtrl.$isEmpty = function(value) {
  26235. return !value || value.length === 0;
  26236. };
  26237. }
  26238. }
  26239. };
  26240. // The option directive is purely designed to communicate the existence (or lack of)
  26241. // of dynamically created (and destroyed) option elements to their containing select
  26242. // directive via its controller.
  26243. var optionDirective = ['$interpolate', function($interpolate) {
  26244. return {
  26245. restrict: 'E',
  26246. priority: 100,
  26247. compile: function(element, attr) {
  26248. if (isDefined(attr.value)) {
  26249. // If the value attribute is defined, check if it contains an interpolation
  26250. var interpolateValueFn = $interpolate(attr.value, true);
  26251. } else {
  26252. // If the value attribute is not defined then we fall back to the
  26253. // text content of the option element, which may be interpolated
  26254. var interpolateTextFn = $interpolate(element.text(), true);
  26255. if (!interpolateTextFn) {
  26256. attr.$set('value', element.text());
  26257. }
  26258. }
  26259. return function(scope, element, attr) {
  26260. // This is an optimization over using ^^ since we don't want to have to search
  26261. // all the way to the root of the DOM for every single option element
  26262. var selectCtrlName = '$selectController',
  26263. parent = element.parent(),
  26264. selectCtrl = parent.data(selectCtrlName) ||
  26265. parent.parent().data(selectCtrlName); // in case we are in optgroup
  26266. if (selectCtrl) {
  26267. selectCtrl.registerOption(scope, element, attr, interpolateValueFn, interpolateTextFn);
  26268. }
  26269. };
  26270. }
  26271. };
  26272. }];
  26273. var styleDirective = valueFn({
  26274. restrict: 'E',
  26275. terminal: false
  26276. });
  26277. var requiredDirective = function() {
  26278. return {
  26279. restrict: 'A',
  26280. require: '?ngModel',
  26281. link: function(scope, elm, attr, ctrl) {
  26282. if (!ctrl) return;
  26283. attr.required = true; // force truthy in case we are on non input element
  26284. ctrl.$validators.required = function(modelValue, viewValue) {
  26285. return !attr.required || !ctrl.$isEmpty(viewValue);
  26286. };
  26287. attr.$observe('required', function() {
  26288. ctrl.$validate();
  26289. });
  26290. }
  26291. };
  26292. };
  26293. var patternDirective = function() {
  26294. return {
  26295. restrict: 'A',
  26296. require: '?ngModel',
  26297. link: function(scope, elm, attr, ctrl) {
  26298. if (!ctrl) return;
  26299. var regexp, patternExp = attr.ngPattern || attr.pattern;
  26300. attr.$observe('pattern', function(regex) {
  26301. if (isString(regex) && regex.length > 0) {
  26302. regex = new RegExp('^' + regex + '$');
  26303. }
  26304. if (regex && !regex.test) {
  26305. throw minErr('ngPattern')('noregexp',
  26306. 'Expected {0} to be a RegExp but was {1}. Element: {2}', patternExp,
  26307. regex, startingTag(elm));
  26308. }
  26309. regexp = regex || undefined;
  26310. ctrl.$validate();
  26311. });
  26312. ctrl.$validators.pattern = function(modelValue, viewValue) {
  26313. // HTML5 pattern constraint validates the input value, so we validate the viewValue
  26314. return ctrl.$isEmpty(viewValue) || isUndefined(regexp) || regexp.test(viewValue);
  26315. };
  26316. }
  26317. };
  26318. };
  26319. var maxlengthDirective = function() {
  26320. return {
  26321. restrict: 'A',
  26322. require: '?ngModel',
  26323. link: function(scope, elm, attr, ctrl) {
  26324. if (!ctrl) return;
  26325. var maxlength = -1;
  26326. attr.$observe('maxlength', function(value) {
  26327. var intVal = toInt(value);
  26328. maxlength = isNaN(intVal) ? -1 : intVal;
  26329. ctrl.$validate();
  26330. });
  26331. ctrl.$validators.maxlength = function(modelValue, viewValue) {
  26332. return (maxlength < 0) || ctrl.$isEmpty(viewValue) || (viewValue.length <= maxlength);
  26333. };
  26334. }
  26335. };
  26336. };
  26337. var minlengthDirective = function() {
  26338. return {
  26339. restrict: 'A',
  26340. require: '?ngModel',
  26341. link: function(scope, elm, attr, ctrl) {
  26342. if (!ctrl) return;
  26343. var minlength = 0;
  26344. attr.$observe('minlength', function(value) {
  26345. minlength = toInt(value) || 0;
  26346. ctrl.$validate();
  26347. });
  26348. ctrl.$validators.minlength = function(modelValue, viewValue) {
  26349. return ctrl.$isEmpty(viewValue) || viewValue.length >= minlength;
  26350. };
  26351. }
  26352. };
  26353. };
  26354. if (window.angular.bootstrap) {
  26355. //AngularJS is already loaded, so we can return here...
  26356. console.log('WARNING: Tried to load angular more than once.');
  26357. return;
  26358. }
  26359. //try to bind to jquery now so that one can write jqLite(document).ready()
  26360. //but we will rebind on bootstrap again.
  26361. bindJQuery();
  26362. publishExternalAPI(angular);
  26363. angular.module("ngLocale", [], ["$provide", function($provide) {
  26364. var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
  26365. function getDecimals(n) {
  26366. n = n + '';
  26367. var i = n.indexOf('.');
  26368. return (i == -1) ? 0 : n.length - i - 1;
  26369. }
  26370. function getVF(n, opt_precision) {
  26371. var v = opt_precision;
  26372. if (undefined === v) {
  26373. v = Math.min(getDecimals(n), 3);
  26374. }
  26375. var base = Math.pow(10, v);
  26376. var f = ((n * base) | 0) % base;
  26377. return {v: v, f: f};
  26378. }
  26379. $provide.value("$locale", {
  26380. "DATETIME_FORMATS": {
  26381. "AMPMS": [
  26382. "AM",
  26383. "PM"
  26384. ],
  26385. "DAY": [
  26386. "Sunday",
  26387. "Monday",
  26388. "Tuesday",
  26389. "Wednesday",
  26390. "Thursday",
  26391. "Friday",
  26392. "Saturday"
  26393. ],
  26394. "ERANAMES": [
  26395. "Before Christ",
  26396. "Anno Domini"
  26397. ],
  26398. "ERAS": [
  26399. "BC",
  26400. "AD"
  26401. ],
  26402. "FIRSTDAYOFWEEK": 6,
  26403. "MONTH": [
  26404. "January",
  26405. "February",
  26406. "March",
  26407. "April",
  26408. "May",
  26409. "June",
  26410. "July",
  26411. "August",
  26412. "September",
  26413. "October",
  26414. "November",
  26415. "December"
  26416. ],
  26417. "SHORTDAY": [
  26418. "Sun",
  26419. "Mon",
  26420. "Tue",
  26421. "Wed",
  26422. "Thu",
  26423. "Fri",
  26424. "Sat"
  26425. ],
  26426. "SHORTMONTH": [
  26427. "Jan",
  26428. "Feb",
  26429. "Mar",
  26430. "Apr",
  26431. "May",
  26432. "Jun",
  26433. "Jul",
  26434. "Aug",
  26435. "Sep",
  26436. "Oct",
  26437. "Nov",
  26438. "Dec"
  26439. ],
  26440. "WEEKENDRANGE": [
  26441. 5,
  26442. 6
  26443. ],
  26444. "fullDate": "EEEE, MMMM d, y",
  26445. "longDate": "MMMM d, y",
  26446. "medium": "MMM d, y h:mm:ss a",
  26447. "mediumDate": "MMM d, y",
  26448. "mediumTime": "h:mm:ss a",
  26449. "short": "M/d/yy h:mm a",
  26450. "shortDate": "M/d/yy",
  26451. "shortTime": "h:mm a"
  26452. },
  26453. "NUMBER_FORMATS": {
  26454. "CURRENCY_SYM": "$",
  26455. "DECIMAL_SEP": ".",
  26456. "GROUP_SEP": ",",
  26457. "PATTERNS": [
  26458. {
  26459. "gSize": 3,
  26460. "lgSize": 3,
  26461. "maxFrac": 3,
  26462. "minFrac": 0,
  26463. "minInt": 1,
  26464. "negPre": "-",
  26465. "negSuf": "",
  26466. "posPre": "",
  26467. "posSuf": ""
  26468. },
  26469. {
  26470. "gSize": 3,
  26471. "lgSize": 3,
  26472. "maxFrac": 2,
  26473. "minFrac": 2,
  26474. "minInt": 1,
  26475. "negPre": "-\u00a4",
  26476. "negSuf": "",
  26477. "posPre": "\u00a4",
  26478. "posSuf": ""
  26479. }
  26480. ]
  26481. },
  26482. "id": "en-us",
  26483. "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER;}
  26484. });
  26485. }]);
  26486. jqLite(document).ready(function() {
  26487. angularInit(document, bootstrap);
  26488. });
  26489. })(window, document);
  26490. !window.angular.$$csp().noInlineStyle && window.angular.element(document.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;}.ng-animate-shim{visibility:hidden;}.ng-anchor{position:absolute;}</style>');